Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all 595 articles
Browse latest View live

Laravel MultiAuth

$
0
0

For the development of dynamic and higher level website Laravel is the best platform.

To manage the content and other stuffs of the site we always need an admin panel through which we can handle the content of the site.
To implement a separate admin panel in any laravel project we need to add multiple authentication functionality in site. Let us proceed to that.

Laravel 5.2 comes with new artisan command which will generate route, controller and views for users table.
Open terminal, go to your project directory and fire below command :

php artisan make:auth

After you fire this command your controller will have following files :

app/Http/Controllers/Auth/AuthController
app/Http/Controllers/Auth/PasswordController

Now create new table called admin (For simplicity you can create same migration for admin as users table)

Now create new directory called AdminAuth in app/Http/Controllers and copy above files to AdminAuth directory, the directory structure will be like:

app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController

Now Copy files from resources/views/auth directory to resources/views/admin/auth directory and update the action path of the forms accordingly.

Now let’s modify config/auth.php,
replace below code in auth.php

/* Authentication Guard*/

   ‘guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
    ],

/*User Providers */

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ]
    ],

/* Resetting Passwords*/

'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admin',
            'email' => 'admin.auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

Now let’s add new rules for admin in Routes.php

Route::group(['middleware' => ['web']], function () {
    //Admin Login Routes...
    Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');
    Route::post('/admin/login','AdminAuth\AuthController@login');
    Route::get('/admin/logout','AdminAuth\AuthController@logout');

    /*Registration Routes...
    I have commented out registration routes for admin as in my case I don’t want to add registration functionality for admin, you can use it if you want to add the same functionality by just removing the comments */

    /*Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');
    Route::post('admin/register', 'AdminAuth\AuthController@register');*/

    Route::post('admin/password/email','AdminAuth\PasswordController@sendResetLinkEmail');
    Route::post('admin/password/reset','AdminAuth\PasswordController@reset');
    Route::get('admin/password/reset/{token?}','AdminAuth\PasswordController@showResetForm');

    Route::get('/admin', 'admin\Dashboard@index');
});

Now go to AdminAuth\AuthController.php and override two methods and variables below:

protected $redirectTo = '/admin';
    protected $redirectAfterLogout = '/admin/login';
    protected $guard = 'admin';

    public function showLoginForm(){
        if(session()->pull('url.intended') == URL::to('/')){
            session()->set('url.intended', URL::to('/admin'));
        }

        if(view()->exists('auth.authenticate')){
            return view('auth.authenticate');
        }
        return view('admin.auth.login');
    }

    public function showRegistrationForm(){

        return view('admin.auth.register');
    }

In above code you can see that we have overridden three protected variables which will change the actual behaviour of the laravel authentication library.

$redirectTo will be used to redirect the user once s/he successfully logged in to the admin panel.

$redirectAfterLogout will define where to redirect user after logout from admin panel.

$guard this is the crucial part of the Auth, here we are defining the guard for the panel as we have added new guard in Auth.php.

showLoginForm()  will override the actual behaviour of auth and will show the admin login form.

showRegistrationForm() will show the admin registration form. In my case, this is not needed as I have removed the registration functionality for admin.

Now create new middleware called RedirectIfNotAdmin using below command

php artisan make:middleware RedirectIfNotAdmin

Now add below code in the middleware

use Illuminate\Support\Facades\Auth;
use Illuminate\Session\Console;
use Session;
class RedirectIfNotAdmin 
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = 'admin')
    {
        if (!Auth::guard($guard)->check()) {
             session()->set('url.intended', $request->url());
            return redirect('/admin/login');
        }

        return $next($request);
    }
}

Now Register middleware in kernel.php

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];

Now we will use this middleware in our AdminController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function __construct(){
        $this->middleware('admin');
   }
public function index(){
        return view('admin.dashboard');
    }
}

That’s it!! this is all we needed to make it working.

Please Note:
We can access authenticated user details directly using Auth::user() but if we have multiple authentication then we have to use :

Auth::guard(‘guard_name’)->user();

For logout
Auth::guard(‘guard_name’)->user->logout();

And to get details of authenticated user in json format :
Auth::guard(‘guard_name’)->user();

For Password Reset

In App/Http/Controllers/AdminAuth/PasswordController.php  file, add two protected variables

protected $guard = ‘admin’; //For guard

protected $broker = ‘admins’; //For letting laravel know which config you’re going to use for resetting password

Now add below mentioned three public methods

public function getEmail()
{
    return $this->showLinkRequestForm();
}

public function showLinkRequestForm()
{
    if (property_exists($this, 'linkRequestView')) {
        return view($this->linkRequestView);
    }

    if (view()->exists('admin.auth.passwords.email')) {
        return view('admin.auth.passwords.email');
    }

    return view('admin.auth.password');
}

public function showResetForm(Request $request, $token = null)
{

    if (is_null($token)) {
        return $this->getEmail();
    }
    $email = $request->input('email');

    if (property_exists($this, 'resetView')) {
        return view($this->resetView)->with(compact('token', 'email'));
    }

    if (view()->exists('admin.auth.passwords.reset')) {
        return view('admin.auth.passwords.reset')->with(compact('token', 'email'));
    }

    return view('admin.passwords.auth.reset')->with(compact('token', 'email'));
}

public function getEmail()
{
    return $this->showLinkRequestForm();
}

public function showLinkRequestForm()
{
    if (property_exists($this, 'linkRequestView')) {
        return view($this->linkRequestView);
    }

    if (view()->exists('admin.auth.passwords.email')) {
        return view('admin.auth.passwords.email');
    }

    return view('admin.auth.password');
}

public function showResetForm(Request $request, $token = null)
{

    if (is_null($token)) {
        return $this->getEmail();
    }
    $email = $request->input('email');

    if (property_exists($this, 'resetView')) {
        return view($this->resetView)->with(compact('token', 'email'));
    }

    if (view()->exists('admin.auth.passwords.reset')) {
        return view('admin.auth.passwords.reset')->with(compact('token', 'email'));
    }

    return view('admin.passwords.auth.reset')->with(compact('token', 'email'));
}

That’s all with the Laravel MultiAuth functionality.

Chirag Malaviya

Chirag Malaviya | Web Developer

Chirag is a PHP Web Developer at Yudiz Solutions Pvt. Ltd., who has the knowledge of Codeigniter and laravel frameworks, Node.js and socket programming. He is always eager to learn latest technology and find the tricky ways to make the things easy. He likes to face the technological challenges. He likes to get in touch with people with whom he can do something innovative.

Getting started with GCD in Swift 3

$
0
0

Swift 3 brings with it many improvements to GCD (Grand Central Dispatch) syntax and usage.Let’s see what’s new things.


dispatch_async

GCD patterns is to perform work on a global background queue and update the UI on the main queue as soon as the work is done.

Previously, we have to choose dispatch method (sync vs async) and then the queue we wanted to dispatch our task to. Now GCD reverses this order – select the queue and then apply a dispatch method.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
// Background thread
dispatch_async(dispatch_get_main_queue()) { () -> Void in
// UI Updates
}
}

Now, new syntax like below:

DispatchQueue.global().async {
// Background thread
DispatchQueue.main.async(execute: {
// UI Updates
})
}

Queue attributes

Queues now take attributes on init. This is a Swift OptionSet and can include queue options such as serial vs concurrent, memory and activity management options and the quality of service (QoSClass.default, QoSClass.userInteractive, QoSClass.userInitiated, QoSClass.utility and QoSClass.background).

/*
- background : The background quality of service class.
- utility : The utility quality of service class.
- `default` : The default quality of service class.
- userInitiated : The user-initiated quality of service class.
- userInteractive : The user-interactive quality of service class.
- unspecified : The absence of a quality of service class.
*/
public enum QoSClass {
case background
case utility
case `default`
case userInitiated
case userInteractive
case unspecified
public init?(rawValue: qos_class_t)
public var rawValue: qos_class_t { get }
}

Work items

Queues are not the only part of GCD to get a Swift OptionSet. There’s an updated Swift syntax like below:

let workItem = DispatchWorkItem(qos: .userInitiated, flags: .assignCurrentContext) {
// Do stuff
}
DispatchQueue.main.async(execute: workItem)

A work item can now declare a quality or service and/or flags on init. Both of these are optional and affect the execution of the work item. The flags are an option set that includes the following options:

public static let barrier: DispatchWorkItemFlags

public static let detached: DispatchWorkItemFlags

public static let assignCurrentContext: DispatchWorkItemFlags

public static let noQoS: DispatchWorkItemFlags

public static let inheritQoS: DispatchWorkItemFlags

public static let enforceQoS: DispatchWorkItemFlags

dispatch_once

In Swift 3, dispatch_once is deprecated and should be replaced with either global or static variables and constants.

// Static
class Video {
static let sharedInstance = Video()
func doSomething(){
print("❤")
}
}

// Global constant.
let constant = Video()

// Global variable.
var variable: Video = {
let variable = Video()
variable.doSomething()
return variable
}()

dispatch_time_t

dispatch_time_t was a function that translated a specified time to a UInt64 that could be provided to a queue.

Previously, we are using NSEC_PER_SEC

let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC)))
     dispatch_after(delay, dispatch_get_main_queue()) { () -> Void in
// Do something
}

now, syntax is easy to use

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
// Do something
}

The .seconds is part of a new enum called DispatchTimeInterval. The cases have an associated value representing the count. It currently supports:

public enum DispatchTimeInterval {

         case seconds(Int)

         case milliseconds(Int)

         case microseconds(Int)

         case nanoseconds(Int)
     }

dispatchPrecondition

Also we have new dispatch preconditions. Allow you to check whether or not you are on the expected thread before executing code. This is particularly useful for functions that update the UI and must be executed on the main queue.

let mainQueue = DispatchQueue.main
mainQueue.async {
dispatchPrecondition(condition: .notOnQueue(mainQueue))
// This code won't execute
}
let queue = DispatchQueue.global()
queue.async {
dispatchPrecondition(condition: .onQueue(queue))
// This code will execute
}

There are many more GCD improvements included in Swift 3 . To learn more about GCD go deeper:

  1. apple/swift-evolution
  2. Dispatch
  3. Concurrent Programming With GCD in Swift 3 – WWDC – 2016 – Video
Sandeep Joshi

Sandeep Joshi | iOS Developer

I’m Sandeep Joshi - an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App Development company. I am ambitious and intensely interested in what I do. You'll quickly find that I do not merely develop software - I develop highly maintainable, elegant code that will save you enormous sums in the long run.

File Sharing Using NFC

$
0
0

What is NFC?

Near Field Communication  is full form of NFC. NFC is a contactless exchange of data. Wireless LAN and Bluetooth are wide range of technologies but in NFC, maximum distance of two devices is 10 cm.

NFC Data Exchange Format (NDEF) is used in following two manners:

  • Reading NDEF data from an NFC tag
  • Beaming NDEF messages from one device to another with Android Beam

NFC tag contains NDEF data. NFC tag can be ready by tag dispatch system, which analyzes discovered NFC tag, categorizes data and start application that is interested in categorized data. Interested application can handle scanned NFC tag and declare an intent filter and request to handle the data.

The Android Beam feature allows a device to send an NDEF message to another device by gathering two devices together. This is  an easier way to send data compared to other wireless technologies like Bluetooth, because when we are using NFC there is  no need of pairing or device discovery. Two devices connect automatically when they come into range. Any application is able to transmit data between devices using android beam which is available through a set of NFC.For example, the Browser, contacts, and YouTube applications use Android Beam to share web pages, and contacts with other devices.

Now we will discuss about How to share file or data using Android Beam :-

In this blog, you will learn the basics about P2P (peer to peer) communication and create an application which can share large files, such as videos and images, from one device to another using NFC.

Following are requirements of the Android Beam file transfer:

  1. Android Beam file transfer for large files is available only in Android 4.1 (API level 16) and higher.
  2. Files you want to transfer must have in external storage.
  3. Each file you want to transfer must have to be world-readable,So you can set this permission by File.setReadable(true, false);
  4. You can transfer a file by providing file URI.

We can start with creating new project and selecting blank activity in it. You should have to select a minimum SDK version of API level 16, because Android Beam file transfer is supported from Android 4.1 (API level 16) and above.Don’t forget to choose your own package name, I’ve chosen com.yudiz.nfcdemo,because Yudiz.com is the domain of my website(http://www.yudiz.com)and the other part refers to the topic of this application which is nfcdemo.

<uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="19" />

To get access of the NFC, you must have to set permission in manifest.If the NFC is compulsory for an application then you can also provide uses-feature tag in manifest.If NFC is compulsory for an application then it can not be installed on Non NFC devices as google play displays that application to users who have an NFC supported devices.

<uses-permission android:name="android.permission.NFC" />

<uses-feature
android:name="android.hardware.nfc"
android:required="true" />

You can allow your application to read data from external storage. By specifying following permission, add this permission in your manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

In your activity_main.xml file put following code.There is nothing in it. Just one simple button is placed in relative layout and user can share file via clicking that share file button.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp" >

<Button
android:id="@+id/act_main_btn_sendfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Send File" />

</RelativeLayout>

You can communicate with NFC via the NfcAdapter class.If NFCAdapter is null then device doesn’t support NFC.

package com.yudiz.nfcdemo;

public class MainActivity extends Activity implements OnClickListener {

    private NfcAdapter nfcAdapter;
    private Button btnSendFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        PackageManager pm = this.getPackageManager();
        // Check if NFC is available on device
        if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
            // NFC isn’t available on the device.
            Toast.makeText(this, "The device does not has NFC hardware.",
                    Toast.LENGTH_SHORT).show();
        }
        // Check if device is running Android 4.1 or higher
        else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            // Android Beam feature isn’t  supported.
            Toast.makeText(this, "Android Beam isn’t supported.",
                    Toast.LENGTH_SHORT).show();
        } else {
            // NFC and Android Beam file transfer is supported.
            Toast.makeText(this, "Android Beam is supported.",
                    Toast.LENGTH_SHORT).show();
        }
    }
    private void initUI() {
        btnSendFile = (Button) findViewById(R.id.act_main_btn_sendfile);
        btnSendFile.setOnClickListener(this);
    }
@Override
    public void onClick(View v) {
    }

If we run our app now then we can find the text whether NFC is enabled or disabled and Android Beam is supported on your device or not.

Now after this if NFC is not enabled on your device then you can make it enable. Android Beam will automatically enable once you enable NFC. If Android Beam is not enabled then you can make it enable from settings of your device.

Once you are sure whether your device supports Android Beam file transfer,By adding callback method system will know that android beam want to send file to another android device. In this callback method, return an array of Uri objects. Android beam send a copy of file given by these uris and send it to receiving device.You must also have permanent read access for the file to transfer a file.

public void sendFile() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        // Check if NFC is enabled on device
        if (!nfcAdapter.isEnabled()) {
            // NFC is disabled, open settings using intent to enable NFC.
            Toast.makeText(this, "Please enable NFC.", Toast.LENGTH_SHORT)
                    .show();
            startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
        }
        // Check if Android Beam feature is enabled on device
        else if (!nfcAdapter.isNdefPushEnabled()) {
                /*
Android Beam is disabled, open settings using intent to enable      
AndroidBeam    
*/    
            Toast.makeText(this, "Please enable Android Beam.",
                    Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
        } else {
            // Android Beam and NFC  both are enabled
            String fName = "yudizNFCDemo.jpg";
            // Get path of user's public pictures directory
            File fDirectory = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

            // Create a file using the specified directory and name
            File fToTransfer = new File(fDirectory, fName);
            fToTransfer.setReadable(true, false);
            nfcAdapter.setBeamPushUris(
                    new Uri[] { Uri.fromFile(fToTransfer) }, this);
        }
    }

Android Beam can send one or more uris using setBeamPushUris.Each file you want to transfer must have to be world-readable,So you can set this permission by File.setReadable(true, false);

Here is full source code of file sharing using Android beam:-

package com.yudiz.nfcdemo;

...

public class MainActivity extends Activity implements OnClickListener {
    private NfcAdapter nfcAdapter;
    private Button btnSendFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        PackageManager pm = this.getPackageManager();
        // Check if NFC is available on device
        if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
            // NFC is not available on the device.
            Toast.makeText(this, "The device doesn’t have NFC.",
                    Toast.LENGTH_SHORT).show();
        }
        // Check if device is running on Android API 4.1 or higher
        else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            // Android Beam is not supported.
            Toast.makeText(this, "Android Beam isn’t supported.",
                    Toast.LENGTH_SHORT).show();
        } else {
            // NFC and Android Beam file transfer is supported.
            Toast.makeText(this, "Android Beam is supported.",
                    Toast.LENGTH_SHORT).show();
}
    }
    private void initUI() {
        btnSendFile = (Button) findViewById(R.id.act_main_btn_sendfile);
        btnSendFile.setOnClickListener(this);
    }
    public void sendFile() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        // Check if NFC is enabled on device
        if (!nfcAdapter.isEnabled()) {
            // NFC is disabled, open settings using intent to enable NFC            
            Toast.makeText(this, "Please enable NFC.", Toast.LENGTH_SHORT)
                    .show();
            startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
        }
        // Check if Android Beam is enabled on device
        else if (!nfcAdapter.isNdefPushEnabled()) {
            /*
Android Beam is disabled, open settings using intent to enable      
AndroidBeam    
*/        
             Toast.makeText(this, "Enable Android Beam.",
                    Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
        } else {
            // Android Beam and NFC both are enabled
            String fName = "yudizNFCDemo.jpg";
            // Get path of user's public pictures directory
            File fDirectory = Environment
        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            // Create a file using the specified directory and name
            File fToTransfer = new File(fDirectory, fName);
            fToTransfer.setReadable(true, false);
            nfcAdapter.setBeamPushUris(
                    new Uri[] { Uri.fromFile(fToTransfer) }, this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.act_main_btn_sendfile:
            sendFile();
            break;
        }
    }
}

Conclusion

In this tutorial I have shown you a very easy way to exchange of data (called Android Beam).You can find more useful tutorials on {Link}.

Disha Shah

Disha Shah | Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a leading mobile app development company and Android programming has been my passion since i started my carrier , learning new technology and doing more complex things has always been interesting part for mine.

How SVG Path works

$
0
0

Working with “SVG Path” and Creating Yudiz logo with SVG

Now a days svg graphics take a vital place in design element like website, here we are discuss about “Path” which is one of the element of svg.

Basically path is working with (x,y) axis coordinate respectively .

There are some other tool(sub-command) to create and give some styling to path like,

Following are some basic element to create, shaping and styling the path.

For Create and Shaping Path
M = moveto
L = lineto
H = horizontal lineto (Case sensitive element)
V = vertical lineto (Case sensitive element)
C = curveto (Case sensitive element)
S = smooth curveto (Case sensitive element)
Z = closepath

For “Case sensitive element”

A lowercase element take positioning relative from point of origin. And an uppercase element take positioning absolute.

For Styling Path

stroke-width
stroke
stroke-dasharray
stroke-dashoffset
stroke-linejoin (miter- for angular cornering, round- for bound cornering, bevel- for two parallel new angular).

Following “Yudiz Logo” example indicate the actual work with path (without curve) design.

yudiz-logo

First decide origin point where you want to actually start,

I divided yudiz logo in four path. You can also create using only one path, it is based on your understanding and flexibility.

Cross right hand section

path_1

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path1" d="M95 120 L145 120 L120 70 L170 70 L145 20" />
        </g>
    </svg>
</div>

Cross left hand section

path_2

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path2" d="M95,120 L45,120 70,70 20,70" />
        </g>
    </svg>
</div>

Cross bottom section

path_3

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path3" d="M95,120 L120,170 70,170 95,220" />
        </g>
    </svg>
</div>

All over border to origin point

path_4

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path4" d="M95,120 L120,70 145,20 195,20 170,70 145,120 120,170 95,220 45,220 70,170 45,120 20,70 45,20 70,70 95,120 70,170" />
        </g>
    </svg>
</div>

Step by Step path indication

step 1:

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path1" d="M95 120 L145 120 L120 70 L170 70 L145 20" />
            <path class="path2" d="M95,120 L45,120 70,70 20,70" />
        </g>
    </svg>
</div>

step 2:

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path1" d="M95 120 L145 120 L120 70 L170 70 L145 20" />
            <path class="path2" d="M95,120 L45,120 70,70 20,70" />
        </g>
    </svg>
</div>

step 3:

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path1" d="M95 120 L145 120 L120 70 L170 70 L145 20" />
            <path class="path2" d="M95,120 L45,120 70,70 20,70" />
            <path class="path3" d="M95,120 L120,170 70,170 95,220" />
        </g>
    </svg>
</div>

step 4:

<div style="text-align: center;">
    <svg width="200" height="270" >
        <g stroke="#ffffff" stroke-width="2" fill="none">
            <path class="path1" d="M95 120 L145 120 L120 70 L170 70 L145 20" />
            <path class="path2" d="M95,120 L45,120 70,70 20,70" />
            <path class="path3" d="M95,120 L120,170 70,170 95,220" />
            <path class="path4" d="M95,120 L120,70 145,20 195,20 170,70 145,120 120,170 95,220 45,220 70,170 45,120 20,70 45,20 70,70 95,120 70,170" />
        </g>
    </svg>
</div>

For additional add coloured triangle using path

You can take one group under another like “ ”

<g>
<path class="fill fill1" d="M45,20 L20,70 70,70 45,20" fill="#139579"/>
<path class="fill fill2" d="M20,70 L70,70 45,120 20,70" fill="#23AF8E"/>
<path class="fill fill3" d="M45,120 L70,70 95,120 45,120" fill="#7D4192"/>
<path class="fill fill4" d="M95,120 L45,120 70,170 95,120" fill="#A26EAB"/>
<path class="fill fill5" d="M70,170 L95,120 120,170 70,170" fill="#E04134"/>
<path class="fill fill6" d="M70,170 L45,220 95,220 70,170" fill="#EBBB17"/>
<path class="fill fill7" d="M70,170 L120,170 95,220 70,170" fill="#EE8F1D"/>
<path class="fill fill8" d="M120,170 L95,120 145,120 120,170" fill="#B63226"/>
<path class="fill fill9" d="M95,120 L145,120 120,70 95,120" fill="#338ACD"/>
<path class="fill fill10" d="M120,70 L145,120 170,70 120,70" fill="#2576AE"/>
<path class="fill fill11" d="M120,70 L145,20 170,70 120,70" fill="#353F59"/>
<path class="fill fill12" d="M145,20 L195,20 170,70 145,20" fill="#0E1A35"/>
</g>

finally we created a full logo with pure svg path.

Now its a time to give some animation for the svg path.

First: you have to use jquery.easing and jquery.drawsvg.js for get same effect like as Demo link which mentioned below.

Second: Just add some script for get effect like draw svg path as your origin to end point.

<script>
    var $svg = $("svg").drawsvg({
        duration: 6000
    }).drawsvg("animate");
</script>

Now your logo get a fill-up effect.

Its turn for colour triangle to randomly fade in with minor blink effect. In this portion we will add some css to stylesheet to fade in functionality and time interval, you can also give any other animation using css.

For animation declaration:

@keyframes fill {
    0% { opacity: 0;}
    90% { opacity: 0;}
    95% { opacity: 0.1}
    100% { opacity: 1;}
}

common class for every triangle to link up with animation effect.

.fill { animation-name: fill; }

individual separate classes for random time animation.

.fill1{animation-duration: 22s;}
.fill2{animation-duration: 17s;}
.fill3{animation-duration: 15s;}
.fill4{animation-duration: 12s;}
.fill5{animation-duration: 19s;}
.fill6{animation-duration: 16s;}
.fill7{animation-duration: 11s;}
.fill8{animation-duration: 21s;}
.fill9{animation-duration: 18s;}
.fill10{animation-duration: 13s;}
.fill11{animation-duration: 14s;}
.fill12{animation-duration: 20s;}

Bingo your logo using svg path with animation is completed.

BONUS (Yoat in SVG)

Below some bonus for you, if you found any relevant work with it.

svg yoat

<svg width="700" height="500" >
<g stroke="#ffffff" stroke-width="2" fill="none">
<path d="M150,370 C140,350 130,330 125,300 C125,300 123,290 135,295 C135,295 350,320 523,310 C523,310 530,308 535,325 C535,325 540,360 525,370 M120,283 C220,298 430,310 525,300"/>
<g>
<path d=" "/>
<path d="M135,295 v-10" />
<path d="M230,304 v-10" />
<path d="M325,310 v-10" />
<path d="M420,313 v-10" />
<path d="M520,310 v-10" />
</g>
<g>
<path d="M180,300 C182,302 215,330 250,306 C250,306 290,335 330,310 C330,310 365,345 420,312 C420,312 460,345 500,311 "/>
<circle cx="250" cy="315" r="9"/>
<circle cx="250" cy="315" r="4" stroke-width="1"/>
<path d="M245,309 L248,312 M258,310 L253,313 M256,323 L252,318 M243,322 L248,318" stroke-width="1"/>
<circle cx="330" cy="321" r="9"/>
<circle cx="330" cy="321" r="4" stroke-width="1"/>
<path d="M324,314 L328,318 M337,317 L333,319 M337,328 L333,324 M322,326 L327,323" stroke-width="1"/>
<circle cx="420" cy="324" r="9"/>
<circle cx="420" cy="324" r="4" stroke-width="1"/>
<path d="M413,317 L417,321 M427,318 L423,322 M427,331 L423,327 M413,330 L417,326 " stroke-width="1"/>
</g>
<g>
<path d="M260,306 C290,265 295,263 320,263 L475,265 C490,265 495,270 500,311"/>
<path d="M271,292 C315,295 328,295 332,283 L338,268 h-45" />
<g>
<path d="M345,310 L350,278 355,273 h12 L372,279 372,311 M365,290 L370,290"/>
</g>
<rect x="385" y="278" width="11" height="11"/>
<rect x="405" y="278" width="11" height="11"/>
<rect x="425" y="278" width="11" height="11"/>
<rect x="445" y="278" width="11" height="11"/>
<rect x="465" y="278" width="11" height="11"/>
</g>
<g>
<path d="M315,263 C323,233 330,232 335,232 L455,232 C465,233 470,242 473,265"/>
<rect x="335" y="240" width="11" height="11"/>
<rect x="357" y="240" width="11" height="11"/>
<rect x="379" y="240" width="11" height="11"/>
<rect x="400" y="240" width="11" height="11"/>
<rect x="421" y="240" width="11" height="11"/>
<rect x="442" y="240" width="11" height="11"/>
</g>
<g>
<path d="M420,233 v-26 h28 v26 M420,207 v-8 h28 v8"/>
</g>
</g>
</svg>

Parthiv Butani

Parthiv Butani | Web Designer

I am a web designer and a creative artist at Yudiz Solutions Pvt. Ltd. - a leading Web and Mobile Apps development company. In my free time I like to explore creative ways of Designs and latest trends.

Custom Google Map Styling

$
0
0

Click To Download Full Source Code

Embedding normal google map in your website is quite easy, but embedding styled map makes your website look elegant and makes your google map look more presentable.

Have You Ever Been Stuck For Styling Google Map?

Here is the answer…

There are many websites/tools available for styling google map.

Some are:-

and much more…

But there is a website that can help you to create styled map easily with a little bit of geographical knowledge.

Made by Instrument and open-sourced on Github is “Google Map API Styled Map Wizard”.

The link for this is http://instrument.github.io/styled-maps-wizard/ as well as you can download locally and create your own styled map.

Image-main

Let’s consider below map example to create a styled map.

From this

Image-1

To this

Image-2

Steps to create this map

Step 1:

Open this link – http://instrument.github.io/styled-maps-wizard/

Step 2:

Locate the map area or region you want to style by entering the location in the top right corner box(Hattontown is used as an example).

Step 3:

Select feature to style from the left side panel i.e. (Selectors Panel)

  1. Select “All > Road” from Feature Type.
    1. Select “All > Geometry > Fill” from Element Type.
    2. Select “Color” from Stylers and apply (207,186,255) by using (R,G,B) range slider.
  2. Click     on “Add” button from the Map Style Panel(right-hand side) to add a new style. (Note: Always use this to apply style for new feature.But there is no need to click on “add” when you apply more than one style for the same feature selected.)
  3. Select “All > Landscape > Man made” from Feature Type.
    1. Select All > Geometry” from Element Type.
    2. Select “Visibility” from Stylers and select “off”.
  4. Select “All > Landscape > Natural” from Feature Type.
    1. Select “Saturation” from Stylers and drag it to the right side until the box shows “50”.
    2. Select“Lightness” from Stylers and drag it to the right side until the     box shows “80”.
  5. Select “All > Point of Interest > Park” from Feature Type.
    1. Select “All” from Element Type.
    2. Select “Color” from Stylers and apply (150,255,165) by using (R,G,B) range slider.
  6. Select “All” from Feature Type.
    1. Select “All” from Element Type.
    2. Tick “Invert Lightness” from Stylers.
    3. Select “Hue” from Stylers and click in “Light Blue” area until the     top right box shows “#00ddff”.
  7. Select “All” from Feature Type.
    1. Select “All > Labels > Text > Fill” from Element Type.
    2. Select “Color” from Stylers and apply (255,255,255) by using (R,G,B) range slider.

Step 4:

Click on “Edit JSON” button and copy all the styles.

Step 5:

Paste the copied styles within inverted commas into this function:

map.set(‘styles’,[“Copied styles”]);

Steps to create this map in HTML

Step 1:

Add this script and style in your head tag:

<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<style>
    html,body,#map    { height: 100%; width: auto;}
</style>

Step 2:

Add this code in your body section:

<div id="map"></div>

Step 3:

Add this script before the end of body tag:

<script type="text/javascript">
function initMap() {
var mapDiv = document.getElementById('map');
var latlng= new google.maps.LatLng(38.945000,-77.393330); //     (Latitude and Longitude of your location)
var map = new google.maps.Map(mapDiv, {
center: latlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.MAP
});
var marker = new google.maps.Marker({
position: latlng,
     title: "My Location",    // Title for your location(optional)
     icon: 'images/marker.png' // Map marker image(optional)
});
marker.setMap(map);
map.set('styles', [
{
     "featureType": "road",
     "elementType": "geometry.fill",
     "stylers": [
     { "color": "#cfbaff" }
     ]
     },{
     "featureType": "landscape.man_made",
     "elementType": "geometry",
     "stylers": [
     { "visibility": "off" }
     ]
     },{
     "featureType": "landscape.natural",
     "stylers": [
     { "saturation": 50 },
     { "lightness": 80 }
     ]
     },{
     "featureType": "poi.park",
     "stylers": [
     { "color": "#96e1a5" }
     ]
     },{
     "stylers": [
     { "invert_lightness": true },
     { "hue": "#00ddff" }
     ]
     },{
     "elementType": "labels.text.fill",
     "stylers": [
     { "color": "#ffffff" }
     ]
     }
    ]);
}
    </script>

Click To Download Full Source Code

Nilay Panchal

Nilay Panchal | Jr. Web Designer

I am a web designer who works at Yudiz Solutions Pvt Ltd - a leading Mobile Apps and Game Development company. I wrote this blog to share my knowledge and ideas to others. I am passionate about music and loves to sing.

Overview about Security and Security Testing

$
0
0

What is Security?

As we all know in general terms security means to Protect something from some unwanted actions and to do so we all take some security measures. So in technical terms security means to protect all kind of Information systems(i.e. Desktop softwares, Mobile apps , Web applications) from different types of security threats (i.e. Sql injection,hacking,virus etc.).

ezgif.com-crop

Security Testing?

To ensure that information system is secure , they must pass through every possible security checks.It is a technique to determine if your information system is secure to save data from security threats and if its functionality works even if any security threats are introduced into it.

To prevent your software against security threats you have to think and test like a hacker.

appsec-01

Security testing has 6 principles.

1) Confidentiality
It aims on protecting data from disclosure to third parties.

2) Integrity
It refers to protection of information from modifying by third parties and aims at ensuring delivery of exact information send by a sender.

3) Authentication
It is concerned with authenticity of user using the information system is the same who needs to be or the system is exact same which it was claimed to be. No third party should be able to access the system without authentication.

4) Authorization
It includes the process of verifying that the user which requests to access the system is allowed to have access over the system. Ex. Access Control

5) Availability
It is a term which is to assure that whenever user requests for information and access over system, It should be ready for authenticated user and information should be available at any time for authorized user.

6) Non-repudiation
It simply means that the message or information sent over network has been successfully sent and received by end to end users. It is a way to ensure that sender can not deny that he has sent that message and receiver can not deny that he has received message.

Techniques for Security Testing:

  • Sql Injection
  • Broken Authentication and Session.
  • XSS(Cross-Site Scripting)
  • IDOR(Insecure Direct Object References)
  • Security Misconfiguration
  • SDE(Sensitive Data Exposure)
  • Missing Access Control at Functional Level
  • CSRF(Cross-Site Request Forgery)
  • Use Components with Known Vulnerabilities
  • Unvalidated Redirect

We will see in detail about Security testing techniques in my next blog. Keep reading… :)

Khushal Parikh

Khushal Parikh | Jr. Quality Analyst

I’m working as a Jr. Quality Analyst in Yudiz Solutions pvt. Ltd - a leading mobile app, mobile games and web development company. I’m fan of technology, cricket, and programming. I’m also interested in politics and music.

A quick guide to Magento 2 basic customisation – Part 1

$
0
0

Get your Ecommerce flexibility using Magento 2

Magento 2 is the newest member of the Magento family, an open-source platform to accelerate your e-commerce goals. It has new and improved features that helps to increase user interaction and perform all business functions smoothly.

It basically integrates object-oriented programming with Relational DataBase Management System, while providing a Zend Framework in the background.

Just follow some simple steps described below to get site URL’s and all the category, products, and customers data right on your screen.

1. Programmatically Get URLs in Magento

Step 1:

The initial step is to Create scripts/magentoUrl.php file.
Now place this file in the Magento root directory and just enter the code displayed below.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); 

// For Site Base url
$baseUrl= $storeManager->getStore()->getBaseUrl();

// For Link url:
$linkUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

//For Media url:
$mediaUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

//For Static Folder url:
$staticUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);

echo “Site URL: ”.$baseUrl.”<br>”;
echo “Link url: ”.$linkUrl.”<br>”;
echo “Media URL: ”.$mediaUrl.”<br>”;
echo “Static Folder URL: ”.$staticUrl.”<br>”;

?>

2. Programmatically Get Category, Products and Customer data in Magento 2

With Magento 2 you can organise and administer your business data. Moreover its scalability feature allows you to make changes effortlessly.

Follow these simple steps given below to get data related to category, products and customers.

Step 1: First Create the scripts/abstract.php file in magento root directory. Place the following code in the file.

<?php

use \Magento\Framework\AppInterface as AppInterface;
use \Magento\Framework\App\Http as Http;

use Magento\Framework\ObjectManager\ConfigLoaderInterface;
use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList as AreaList;
use Magento\Framework\App\State as State;

abstract class AbstractApp implements AppInterface
{
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        Event\Manager $eventManager,
        AreaList $areaList,
        RequestHttp $request,
        ResponseHttp $response,
        ConfigLoaderInterface $configLoader,
        State $state,
        Filesystem $filesystem,
        \Magento\Framework\Registry $registry
    ) {
        $this->_objectManager = $objectManager;
        $this->_eventManager = $eventManager;
        $this->_areaList = $areaList;
        $this->_request = $request;
        $this->_response = $response;
        $this->_configLoader = $configLoader;
        $this->_state = $state;
        $this->_filesystem = $filesystem;
        $this->registry = $registry;
    }

    public function launch()
    {
        $this->run();
        return $this->_response;
    }

    abstract public function run();

    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
    {
        return false;
    }
}
?>

Step 2: To avail the category Data

Follow these subsequent steps

Step 2.1: Create scripts/categoryData.php file in magento root directory and place the code below to get category data.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CategoriesDataApp extends AbstractApp
{
    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $category = $this->_objectManager->create('\Magento\Catalog\Helper\Category');
        $_categories = $category->getStoreCategories();
        foreach($_categories as $cat){
            $_category = $this->_objectManager->create('\Magento\Catalog\Model\Category');
            $_category = $_category->load($cat->getId());
            $_subcategories = $_category->getChildrenCategories();
            if (count($_subcategories) > 0){
                echo $_category->getId().'=>'.$_category->getName().'
';      
                foreach($_subcategories as $_subcategory){
                     echo "sub category: ".$_subcategory->getId().'=>'.$_subcategory->getName().'
';
                }
            }
        }

        /* for load Specific category uncomment below code */

        //$_category = $this->_objectManager->create('\Magento\Catalog\Model\Category');
        //$_category = $_category->load(4); // your category Id
        //echo '

';print_r($category-&gt;getData()); // for get category data
        //$category-&gt;delete(); // for delete category
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap-&gt;createApplication('CategoriesDataApp');
$bootstrap-&gt;run($app);
?&gt;

Step 2.2: Run the command http://www.yourdomian.com/scripts/categoryData.php in your browser. This will provide you all the data related to category right on your screen.

Step 3: For Product Data

Follow the display of all information related to products follow these easy steps.

Step 3.1: Create scripts/productData.php file in Magento root directory and place the code shown below in that file.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class ProductsDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $products = $this->_objectManager->create('\Magento\Catalog\Model\Product');

        $products = $products->getCollection()
                    ->addAttributeToFilter('type_id', 'simple') // for filter simple product (remove it if want to all products)
                    ->addAttributeToSelect('*')
                    ->load();
         foreach($products as $product)
         {
            echo $product->getId().'=>'.$product->getName().'=>'.$product->getData('price').'<br/>';

            $_product = $this->_objectManager->create('\Magento\Catalog\Model\Product')->loadByAttribute('entity_id',$product->getId());

         }

    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('ProductsDataApp');
$bootstrap->run($app);
?>

Step 3.2: Run productData.php command in your browser. Your screen will be displayed with All products related data.

Step 4: For Customer Data:

Step 4.1: Create scripts/customerData.php file in magento root directory and put below code to  get all the Customer data.

&lt;?php

require dirname(__FILE__) . '/../app/bootstrap.php';

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

require dirname(__FILE__) . '/abstract.php';

class CustomersDataApp extends AbstractApp

{

public function run()

{

$this-&gt;_objectManager-&gt;get('Magento\Framework\Registry')

-&gt;register('isSecureArea', true);

$customers = $this-&gt;_objectManager-&gt;create('\Magento\Customer\Model\Customer');

$customers = $customers-&gt;getCollection();

foreach($customers as $customer)

{

//echo '&lt;pre&gt;';print_r($customer-&gt;getData());

echo $customer-&gt;getId().'=&gt;'.$customer-&gt;getName().'&lt;br/&gt;';

//$_customer = $this-&gt;_objectManager-&gt;create('\Magento\Customer\Model\Customer')-&gt;load($customer-&gt;getId()); /// Customer Object for change data or load Customer

}

}

}

/** @var \Magento\Framework\App\Http $app */

$app = $bootstrap-&gt;createApplication('CustomersDataApp');

$bootstrap-&gt;run($app);

?&gt;

Step 4.2: Run http://www.yourdomian.com/scripts/customerData.php command in your browser..All the customer data will be presented on your screen.

Hope this will help you!
Thank you.

Gordhan Chauhan

Gordhan Chauhan | Sr. Magento Developer

I work as Sr. Magento Developer in Yudiz Solutions Pvt. Ltd. -
a leading mobile apps, mobile games and web development company.
I write blogs to share my knowledge and ideas to my audience. I am passionate about exploring and develop new stuff in magento and web development.

3 Easiest ways to make equal height blocks using CSS

$
0
0

Click To Download Full Source Code

Overview

As per the current website design trends most of the designs has equal height of blocks. As a web designer it is very difficult to do so using CSS only. Following are some methods to do equal height blocks with the help of CSS in easiest way.

How to make sidebar and content blocks equal height in different ways?

Here we are going to learn how to make 2 blocks of equal height in different way.

Many designers has these type of  problems so today we are going to make it easy and make any website in short period of time.

We are  going to start with simple example using only CSS and there is no use of any Javascript. Every designer has a goal to create a design with better look and feel.

Method 1: Using margin and padding

With the use of margin and padding we can make equal height of columns. Have a look on below code of HTML. Here we have to set some values to padding and also equal value of margin but in negative numbers.

HTML code

<div class="container">
        <div class="sidebar">
            <h2>Sidebar</h2>
        </div>
        <div class="content">
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
        </div>
</div>

CSS Code

.container            { overflow: hidden;}
.content, .sidebar    { padding-bottom: 99999px; margin-bottom: -99999px;}

Result

screenshot-1

Please note that for mobile resolutions you have to set margin and padding values to “0” for better representations.

@media (max-width: 767px){
    .content, .sidebar         { padding-bottom: 0px; margin-bottom: 0px;}
}

I hope it was easy to understand. Now, let us try another way for the same.

Method 2: Using display property

Using display property we can create the same thing. It is an old way to make the solution but it is a very easy way for quick solution and fulfill our requirement. Here are the three main CSS properties to use.

  1. table
  2. table-row
  3. table-cell

HTML code

<div class="main">
   <div class="container">
       <div class="content-table">
          <div class="content-row">
              <div class="column content1">
                  <h1>Section 1</h1>
                  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
              </div>
              <div class="column sidebar">
                  <h2>Sidebar</h2>
              </div>
           </div>
        </div>
    </div>
</div>

CSS Code

.content-table         { display: table; border-collapse: separate; border-spacing: 30px 0;}
.content-row           { display: table-row;}
.column                { display: table-cell;}
.sidebar               { width: 300px;}

Result

screenshot-2

Please note that for mobile resolutions you will have to set display property’s value to “block” for better representations.

@media (max-width: 767px){
    .content-table,  
    .content-row, .column        { display: block;}
}

If this helps you to solve your problem then apply in your project.

Method 3: Using CSS Flex Box

Now a days CSS3 introduces Flexbox which helps us in very amazing and creative way. It reduces the use of floats so not to worry about clearing floats in your layouts. Let’s have look how Flexbox helps us to make equal height blocks.

Example 1:

HTML code

<div class="box">
	<div class="column"><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></div>
	<div class="column"><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></div>
	<div class="column"><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></div>
</div>

CSS Code

.box             { display: -webkit-flex; display: -ms-flexbox; display: flex; overflow: hidden;}
.box .column     { flex: 1; background: #aaa; margin-right: 10px; padding: 15px;}

Example 2:

HTML Code

<ul class="flexlist">
	<li class="flexlist-item">Lorem Ipsum is simply dummy text</li>
        <li class="flexlist-item">Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text. Lorem Ipsum is simply dummy text</li> 
</ul>

CSS Code

.flexlist         { display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; overflow: hidden;}
.flexlist-item    { width: calc(100% / 2 - 5px); float: left; display: -webkit-flex; display: -ms-flexbox; display: flex;}

Result

screenshot-3

Here are 2 different ways to use flexbox for equal height blocks.

In example 1, display: flex initiates flexbox for container block. Then you have to set flex: 1 which defines flex grow i.e it covers the whole area of flex container.

In example 2, display: flex initiates flexbox for container block. Then flex-wrap: wrap tells to wrap the child within the blocks. Last use of display: flex is for child items to fit within the block and they have equal height for all.

Click To Download Full Source Code

Nipa Khunt

Nipa Khunt | Jr. Web Designer

I am Jr. Web Designer at Yudiz Solutions Pvt. Ltd. - a leading web, mobile apps and Game development company. Designing has always been my passion which makes it obvious that I chose my career in web designing. I like to share my experiences and challenges that I face through writing blogs.

Developer’s guide to On Demand Resources

$
0
0

Click To Download Full Source Code

Now a days, App size is increased as it contains more number of images in bundle. It becomes a bad user experience while downloading a large sized app from app store. To resolve this issue, Apple introduced On Demand Response feature from iOS 9 versions.

You can download resources when you need in app.

Ex. We develop games with multiple level and on each level there are different images. Here what happens is once user reaches next level then we have to download images only for that particular level & so on.

Let’s add new asset catalogs and add some images which we will load later in app.

Step: 1

Create new file

Screen1

Step: 2

then select asset catalog

Screen2

Now we have to specify the asset which we will use as On Demand Resource in app.

  1. Select Project -> Targets -> Navigate to Resource Tags
  2. Click on + button to add assets – > give any name as it’ call “tag” to identify during downloading the assets.
    Screen3
  3. click + & adds you newly added assets catalog.
    Screen4

It will also add tags in assets’ catalogs for each image which we added in resource tags.
Screen5

Now you have to use NSDataAsset request to load assets when you need in your app.

var request: NSBundleResourceRequest!

request = NSBundleResourceRequest(tags: ["Background"])
request.loadingPriority = NSBundleResourceRequestLoadingPriorityUrgent

request.beginAccessingResourcesWithCompletionHandler { (error: NSError?) -> Void in
// Called on background thread
if error == nil {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
print("Done") //update UI
})
}else{
print(error?.description)
}
}

Let’s understand each line of code

  1. We declare NSBundleResourceRequest object global to use in class level.
  2. Create request with our tag which we given in resources tags tab.
  3. We can start downloading the asset packs for the specified tags by calling beginAccessingResourcesWithCompletionHandler(_:). This method will access all resources with the specified tags and will automatically start a download if needed.

Here we have to check whether the resources are already downloaded or not.So we have to call

conditionallyBeginAccessingResourcesWithCompletionHandler(_:)

request.conditionallyBeginAccessingResourcesWithCompletionHandler { (resourcesAvailable) in
if resourcesAvailable == true {
//Resouses available
}else{
// Resources not available
}
}

A resource request can have a “loading priority” and “preservation priority”. These are numeric priorities between 0.0 and 1.0 that give priorities to the loading of the resources and life of the stored resources.

By lowering the loading priority you can free up memory and increase app speed, thus resulting in lower download speeds. In contrast you can increase the loading priority putting more strain on the user’s device but achieving greater download speeds.

Ex.

request.loadingPriority = NSBundleResourceRequestLoadingPriorityUrgent
request.bundle.setPreservationPriority(1.0, forTags: ["Background"])

When a resource is no longer needed, it’s important to call “endAccessingResources” on the resource request to let the system know the resources can be purged from memory to free up space.

request.endAccessingResources()

To test On Demand Resources

Go to the “Debug Navigator” and tapping on “Disk”. There’s a section found towards the bottom that will list your On Demand Resources via tag and show their size and status, such as “Downloaded” or “In Use”.

Screen6

Click To Download Full Source Code

Chirag Daslaniya

Chirag Daslaniya | Mobile App Developer

Chirag Daslaniya is a passionate Mobile Application Developer, especially for iOS at Yudiz Solutions Pvt. Ltd. – a leading iPhone App Development company. He is zealous about making easy-to-use and user-friendly applications using simple yet striking interfaces.

Communication over WiFi In Android

$
0
0

What is WiFi?

WiFI or Wireless Fidelity is a technology that allows computers, smartphones or other devices to connect to the Internet or communicate with each other wirelessly within a particular area.Many facilities are provided by WiFi and hotspot is one of them.

What is Hotspot?

A hotspot is a wireless network(WLAN) that provides Internet connection and virtual private network access from particular location. For e.g. Employee connect their own company network remotely with a secure connection or group of people connected to one network for playing game,chat etc

Hotspot in Mobile Device

Mobile hotspots (portable hotspot) are portable devices or features on smartphones that provide wireless Internet access on many devices (like laptop, smartphone, tablet, portable gaming device, etc.)

Wireless chat application using portable WiFi hotspot

The Android platform provides support for the wireless network, which allows a device to wirelessly connect with other device and exchange data between them. The application framework provide wireless APIs for accessing wireless functionality. These APIs help for connecting devices wirelessly to each other, like point-to-point and point-to-multipoint communications.

This application allows two or more Android devices to communicate with each other without using any resources (like Internet ,chat servers). For communication between them we need tethering or hotspot.

Purpose of this application is making wireless communication between android devices. We need minimum two device for communication. One device enables tethering(via wifi). So we called is server and another device connect via wifi so we called client. If you want to connect more than two device. It is possible and it become group chat. To open a connection between devices, you need to make tcp/ip connection using a Socket and ServerSocket in Java.These Class are provided by java. If you want to use library for simplify coding then you can use it.

A socket is a software endpoint that establishes communication between connected nodes.

It can be two or more node(device). But primary stage one device is server that created socket which contain port for running services and ip address for connection purpose,and another device is client which connect to server.

Code Snippet and Requirements:

1) Android 2.2 or higher version(hotspot required)

2) Application Permission Require :

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

3) Create Hotspot:

// this method help to create hotspot programmatically   
        public static boolean setHotSpot(String SSID, String passWord) {   
       Method[] mMethods = wifiManager.getClass().getDeclaredMethods();

   for (Method mMethod : mMethods) {

           if (mMethod.getName().equals("setWifiApEnabled")) {
               WifiConfiguration wifiConfig = new WifiConfiguration();
               if (passWord == "") {
                   wifiConfig.SSID = SSID;
                    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                          wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                       } else {
                   wifiConfig.SSID = SSID;
                   wifiConfig.preSharedKey = passWord;
                   wifiConfig.hiddenSSID = true;
                      wifiConfig.status = WifiConfiguration.Status.ENABLED;
                   wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                   wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                   wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                   wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                  wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                   wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                   wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                      }
                   try {
                       mMethod.invoke(wifiManager, netConfig, true);
                  wifiManager.saveConfiguration();
                       return true;

                      } catch (Exception e) {

                       }
                }
               return false;
                }

4) Join Hotspot

// this method help to connect hotspot programmatically 
          public static boolean connectToHotspot(String netSSID, String netPass) {
       WifiConfiguration wifiConf = new WifiConfiguration();
      List scanResultList = wifiManager.getScanResults();
       if (wifiManager.isWifiEnabled()) {
                  for (ScanResult result : scanResultList) {
                  if (result.SSID.equals(netSSID)) {

                       removeWifiNetwork(result.SSID, wifiManager);
                        String mode = getSecurityMode(result);// get mode of hospot

                          if (mode.equalsIgnoreCase("OPEN")) {
        wifiConf.SSID = "\"" + netSSID + "\"";
                                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                                int res = wifiManager.addNetwork(wifiConf);
                                wifiManager.disconnect();
                              wifiManager.enableNetwork(res, true);
                            wifiManager.reconnect();
                         wifiManager.setWifiEnabled(true);
                       return true;
                   } else if (mode.equalsIgnoreCase("WEP")) {
                                wifiConf.SSID = "\"" + netSSID + "\"";
                              wifiConf.wepKeys[0] = "\"" + netPass + "\"";
                        wifiConf.wepTxKeyIndex = 0;
                           wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                              wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                                int res = wifiManager.addNetwork(wifiConf);
                           wifiManager.disconnect();
                               wifiManager.enableNetwork(res, true);
                               wifiManager.reconnect();
                               wifiManager.setWifiEnabled(true);
 return true;
} else {
                             wifiConf.SSID = "\"" + netSSID + "\"";
                           wifiConf.preSharedKey = "\"" + netPass + "\"";
                            wifiConf.hiddenSSID = true;
                             wifiConf.status = WifiConfiguration.Status.ENABLED;
                           wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                          wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                          wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                         wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                           wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                           wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                           wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                           int res = wifiManager.addNetwork(wifiConf);
                          wifiManager.disconnect();
                          wifiManager.enableNetwork(res, true);
                          wifiManager.reconnect();
                          wifiManager.saveConfiguration();
                          wifiManager.setWifiEnabled(true);
                     return true;
                    }
                  }
                }
              }
             return false;
         }
// get Security Mode
public static String getSecurityMode(ScanResult scanResult) {
   final String cap = scanResult.capabilities;
   final String[] modes = {"WPA", "EAP", "WEP"};
   for (int i = modes.length - 1; i >= 0; i--) {
               if (cap.contains(modes[i])) {
                       return modes[i];
               }
    }
   return "OPEN";
  }

5) Socket

i)Socket Class
Socket
ServerSocket
DatagramSocket
MulticastSocket(Required for multicast or group communication)

ii)Server Socket
The ServerSocket provide a listening TCP connection. Once a connection is requested, the ServerSocket object will return as Socket object representing the connection.

Constructors:
The ServerSocket provides four constructors. Empty construction means port number assigned by OS. With one argument port number take as argument to listen for connection requests. A constructor is provided facility of maximum time to wait for a connection as a second argument.And at last InetAdress or IP Address take as last argument.

Methods:
The most important method is accept(). It returns a Socket that is connected to the client. The close() method give idea of whether operating system to stop listening for requests on the socket.Some methods available for retrieve the hostname, port number etc.

//port number range 1024-65535
            public static final int PORT = 2024;

//Server Socket declaration 
         ServerSocket serversocket = null;
             Socket socket = null;
             System.out.println(" Waiting !! ");

try
         {
          //  Initialising the ServerSocket with input as port number
          serversocket =  new ServerSocket(PORT);

          try
          {

               // makes a socket connection for clients 
              // accept method waiting for connection(listening mode)
          socket = serversocket.accept();

          // Receive message from client
          DataInputStream dis = new                 
                DataInputStream(socket.getInputStream());

// for reading dis.readLine();

     // Send message to the client 

DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(“Hello User);
 dos.close();

    // Close the Socket connection 
                socket.close();
  }
           catch(SocketException socketexception)
        {
                System.out.println("Server problem  "+socketexception.getMessage());
           }
        catch(Exception exception)
        {    
System.out.println("Something wrong error occure” + exception.getMessage()) ;     
 }               

 //get address of socket
         System.out.println(" Connection from :  " +  socket.getInetAddress());

iii) Client  Socket(Socket)

Socket Class provides a TCP connection. When a socket is created, a connection is opened to the specified destination, it can be domain name or ip address with specific port number.

Constructors:

The Socket provides the programmer with multiple constructors.

Empty socket is system default socket with the system-default type of SocketImpl. Another two constructors is Proxy and SocketImpl as single argument. Main focus is InetAddress constructor which may be specified as a string or an InetAddress, and the port number on the host to connect to. In each case, connection type is described as connectionless or not as set false for connectionless.

Methods:

Socket provides two methods are getInputStream() and getOutputStream(), which give return type as  stream objects, which help to communicate through the socket. Object provided virtual link to the socket.The close() method give idea of whether operating system to stop listening for requests on the socket.Some methods available for retrieve information about the connection to the local host and remote port numbers and an integers representing the remote host.

// Declaration

Server.PORT=2024;

Socket socket=null;
System.out.println(" Trying to connecting server");
try
{
// to get the ip address of the  server by the name
//first way

InetAddress ip =InetAddress.getByName (“yudiz.com");

// default or second way if hotspot created by server then 192.168.43.1 (fixed)
// Connecting to the port 2024 declared in the Server class
// Creates a socket with the server bind to it.

socket= new Socket(ip,Server.PORT);

// Receive message from server

DataInputStream dis = new
DataInputStream(socket.getInputStream());
System.out.println(dis.readLine());

//output : Hello User

// Send message to the server

DataOutputStream dos = new

DataOutputStream(socket.getOutputStream());

dos.writeUTF(“Hello Server);

dos.close();
}
catch(SocketException socketexception)
{    System.out.println("Socket Exception”);
}
catch(IOException exception)
{    System.out.println("Error ocuure : io exception”);

}
// closing the socket

socket.close();

Sachin Patel

Sachin Patel | Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a mobile App Development company. I am passionate about android app development and like adopting new technologies to maximize development efficiency and produce innovative applications.

Developer’s Comprehensive guide on Area Effector in Unity3D

$
0
0

The Area Effector 2D applies powers inside a region characterized by the joined Collider 2Ds when another (objective) Collider 2D comes into contact with the Effector 2D. You can arrange the power at any point with a particular size and arbitrary minor departure from that size. You can likewise apply both direct and precise drag strengths to layback Rigidbody 2Ds.

Collider that you use with the Area Effector would ordinarily be set as triggers, so that other Collider 2Ds can cover with it to have strengths connected. Non-triggers will in any case work, however strengths may be connected when Collider 2Ds come into contact with them.

Creating Area Effector 2D:

Now we explore the Area Effector 2D component which allows you to add 2D physical forces to objects which enter a trigger volume.

1

We have got 3 images, ‘Car’, ‘Arrow’, and  ‘Path’ in my scene. In this example, first of all set the path image as a background and then create sprites of Car and Arrows, Drag Car and Arrows on Path.Finally Add AreaEffector2D and BoxCollider2D component in inspector of all Arrows sprites.

Properties of AreaEffector2D:

Collider Mask figures out what layers will be influenced when articles enter the zone. For the time being, continue Everything chose.

Force Direction decides the degree heading of the power. The quality extents from – 359.99 to 359.99, which truly just characterizes a circle moving in either a clockwise or counter-clockwise course. As the picture beneath appears, zero focuses to one side and positive qualities move counter-clockwise along the circle; negative qualities move clockwise.

2

Force Magnitude permits you to set the quality of this current territory’s power, while Force Variation gives you a chance to characterize a reach to give some randomization to the power for every crash.

The Drag and Angular Drag alternatives permit you to encourage tweak the range’s belongings. Truth be told, you could utilize just drag values and no power qualities to make a territory that moderates any articles that enter.

Force Target decides when on the article the power gets connected. At the point when set to RigidBody, powers apply to the item’s focal point of mass, while setting it to Collider applies powers at the purpose of impact.

2

Set properties of AreaEffector2D and BoxCollider2D component same as mentioned above , In BoxCollider2D properties field ‘IsTrigger’ and ‘Used By Effecter’ must be checked, because after checking “Used By Effecter” field,we will see the effect of AreaEffector2D component,also add BoxCollider2D in Car inspector but no need to check property fields of ‘IsTrigger’ and ‘Used By Effecter’.

In this Example Car runs through the AreaEffector2D and BoxCollider2D component, So surely add in all arrows above two component, The Car BoxCollider2D trigger with the arrows BoxCollider2D and then get effect of AreaEffector2D and get force through the AreaEffector2D field that is “Force Magnitude” and change angle through the use of field Drag and Angular Drag. Here, we do not need to write any types of scripts.

Here’s a .gif.

4

Hiten Dodiya

Hiten Dodiya | Unity3D Game Developer

Being Professional Unity3D Game Developer at Yudiz Solutions Pvt. Ltd., I aim of developing mobile games in all deployment platforms. I am a self-motivated individual, always strives to improve my work, readily learn more and never afraid to try new approaches.

Create your own custom fonts

$
0
0

The right typeface can communicate a lot to a reader about the “personality” of a design. But what if you can’t find the right typeface? Or what if you want your design to be different? Well, you might be surprised to learn you can make your own design with wide variety of software available for free and across different platforms.

I had found some useful pieces of information across many sources. Undoubtedly the methodologies practiced are as unique and individual as the designers practicing them.

I’ll provide a bit of guidance on getting started and address hurdles along the way, share one of the software that I tried out, and recommend resources for learning more.

image04

The idea behind MyScriptFont is that it allows you to create fonts and generate fonts from your handwriting. You can even make up a new design for every letter in the alphabet, turn that into a workable font, then use it to create all your next project. All you need is a marker or felt-tip pen and a scanner to get started.

Download Template from MyScriptFont

Browse the MyScriptFont website and download the template. The template is a set of lines you can transfer your handwriting or creations to before you turn them into fonts.

image01

Write out the alphabet and numbers in your style, use black marker or dark blue also works. It is important that you use a felt pen instead of the regular ballpoint pen, or the text would not come out clearly.

image02

Max. upload file size is 6 MB. Supported types of are jpg, png, pdf, jpeg, tiff. Max. dimension for images are 6500 x 6500 px.

Upload your New Font

Upload your scanned fonts to the MyScriptFont website.

You can name your font and set it in the format you want the font to be: TFF, OTF format. When you’re done with the settings, click ‘Start’ and let it load.

image02

After the font is converted, you’re allowed to download it to your computer.

Installing font

You need to install your font before using it.

For Windows, go to ‘Control Panel’ and search for ‘Fonts’. Just copy and paste your newly downloaded font into the ‘Fonts’ folder.

image03

Conclusion: Even with the multiple fonts are available, you may still find that none are suitable for your website or other projects. The solution is create your own. By following the steps above, you can create your own beautiful custom font with your own imagination and use it in your website, or in other projects.

Dhaval Solanki

Dhaval Solanki | Web Designer

I am a web designer at Yudiz Solutions Pvt Ltd - a leading Mobile Apps and Game Development company. I wrote this blog to share my knowledge and ideas to others. I always eager to learn latest technology and find the tricky ways to make the things easy.

TableView Optimisation

$
0
0

Introductions

Click To Download Full Source Code

We all know that what is UITableView and how its imported to iOS application development.we also know the what is cell reuse identifier and also already use that one.

But still we need to know about how to optimise tableview. i am listed below some important method and standard to tableview optimisations.

1. Reuse Cell Identifier

Reuse cell instances for specific type of cell you should have only one instance of cell.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
	let cell = tableView.dequeueReusableCell(withIdentifier: "userCell") as! UserCell
	return cell
}

2. Data Binding

But very important tableView(UITableView, cellForRowAt: IndexPath)method, which should be implemented in the dataSource of TableView, called for each cell and should work fast. So you must return reused cell instance as quickly as possible.

Don’t perform data binding at tableView(UITableView, cellForRowAt: IndexPath) method. because there’s no cell on screen yet.

Just get the reuse cell from catch or create new and return immediately. this increase calling frequency of this method

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "userCell") as! UserCell
     return cell

}

data-binding

For data binding you can use tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath)method which can be implemented in the delegate of UITableView. This method called before showing cell on screen.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

	if let userCell = cell as? UserCell {

		let dict = arrName[indexPath.row]
		userCell.lblName.text = dict["name"]
		userCell.lblPost.text = dict["post"]
		userCell.btnFollow.isSelected = dict["isFollow"] == "1"
		userCell.imgProfile.image = UIImage(named:dict["img"]!)

	}
}

data-binding

3. Height of Cell

As we know UITableView is just child of UIScrollView. So how TableView know about its contentSize?. its calculating all cell heights and summing it.

The tableView(UITableView, heightForRowAt: IndexPath) method is called for each cell even if is display or not. you need to return height very fast.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

}

Since iOS 8, we can use automatic height calculation without implementing tableView(UITableView, heightForRowAt: IndexPath) method. we can user tableView.rowHeight properly.

3.Height of Cell

4. Other Point need to Know

AutoLayout is really so slow

The reason of relative low performance of Auto-layout in constraint solving system. More subviews you have to layout and constraints you have to solve, more time you spend for returning cell to the UITableView. performing some base math calculations with small number of values.

  • Load images at background, round their corners at the same place, and then assign processed image to UIImageView.
  • Catching images to local. do not load every from network.
  • Do not load heigh resolution image. only respectively to UIImageView size.
  • Perform operations to background thread and refresh displayed content on the main thread.

Click To Download Full Source Code

Yogesh Makwana

Yogesh Makwana | iOS Developer

I am an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App development company. My life motto is 'Do my best, so that I can't blame myself for anything.' I have a deep rooted obsession for developing creative iOS apps and different aspects.

Developer’s Guide to Unity3D MMO With Node.JS Using Socket.IO

$
0
0

What is Node.js ?

Node.js is a JavaScript engine which is built on Chrome’s V8. It is network application for communicates between client and server.It uses event-driven non blocking I/O model. Node.js’s package ecosystem its called “npm”, which includes open source libraries in the world.Node is specially designed to broadly and scalable network applications for the device/computers.

What is Socket Programming ?

Sockets is the mechanism of communication between two computers or devices using TCP. A client program which is installed in device/computer which creates a socket at the end of the communication when socket connect to server. When connection is done, then server creates a its own socket object from the server side when end of the communication.

Game Architecture between Unity Engine and Server:

 

1

Goals :

  • Describe the mechanism of events works with client side and server side.
  • Unity 3d broadcasting a player’s X-Y-Z position, per frame, to other players grabbing the data via node.js.
  • Update all players position,rotation, player data etc.
  • Updating each time someone connects or disconnects with the socket.
  • Refreshing the gameobject after taken any action by the user/client.

Requirements :

  • Unity Engine
  • Any Dedicated Server

Required External Tools :

Conceptual Overview :

The object broadcasting the information of the other player like X,Y,Z coordinates of players.
Here i have demonstrated the basic game concept of moving one game object within screen, the same reaction will be affected with the other user’s screen also.
It can works for Android/iOS/Windows Mobile device, as well it can works fine with stand alone build for Windows and Mac PC also.
For the cross platform no need to do any extra stuff.

How Event Works ?

2

How to use :

Step – 1 : Import namespace

using System;
using BestHTTP;
using BestHTTP.SocketIO;

Step – 2 : Create Socket

Here we have to create socket for connecting socket of client with server.

var socketManagerRef = new SocketManager(new Uri(“http://chat.socket.io/socket.io/”));

The /socket.io/ path in the url is very important, by default the Socket.IO server will listen on this query. So don’t forget to append it to your test url too!

Example :

public void CreateSocketRef ()
    {
        TimeSpan miliSecForReconnect = TimeSpan.FromMilliseconds (1000);

        options = new SocketOptions ();
        options.ReconnectionAttempts = 3;
        options.AutoConnect = true;
        options.ReconnectionDelay = miliSecForReconnect;

        //Server URI
        socketManagerRef = new SocketManager (new Uri ("http://127.0.0.1:4001/socket.io/"), options);
    }

Step – 3 : Connecting To Namespace

By default the SocketManager will connect to the root(“/”) namespace while connecting to the server. You can access it through the SocketManager’s Socket property:

Socket root = manager.Socket;
Non-default namespaces can be accessed through the GetSocket(“/nspName”) function or through the manager’s indexer property:

Socket nsp = manager[“/customNamespace”];
// the same as this methode:
Socket nsp = manager.GetSocket(“/customNamespace”);

First access to a namespace will start the internal connection process.

Example :

public void SetNamespaceForSocket ()
    {
        namespaceForCurrentPlayer = socketNamespace;
        mySocket = socketManagerRef.GetSocket (“/Room-1);
    }

Step – 4 : Subscribing and receiving events

You can subscribe to predefined and custom events. Predefined events are “connect”, “connecting”, “event”, “disconnect”, “reconnect”, “reconnecting”, “reconnect_attempt”, “reconnect_failed”, “error”. Custom events are programmer defined events that your server will send to your client. You can subscribe to an event by calling a socket’s On function:

manager.Socket.On("login",OnLogin);
manager.Socket.On("new message", OnNewMessage);

An event handler will look like this:

void OnLogin(Socket socket, Packet packet, params object[] args) {
Debug.Log(“Login.”);
}

  • The socket parameter will be the namespace-socket object that the server sent this event.
  • The packet parameter contains the internal packet data of the event. The packet can be used to access binary data sent by the server, or to use a custom Json parser lib to decode the payload data. More on these later.
  • The args parameter is a variable length array that contains the decoded objects from the packet’s payload data. With the default Json encoder these parameters can be ‘primitive’ types(int, double, string) or list of objects(List<object>) or Dictionary<string, object> for objects.

A message emitted on the server(node.js):

// send a message to the client
socket.emit('message', ‘MyNick’, ‘Msg to the client’); can be caught by the client:

// subscribe to the "message" event                        manager.Socket.On("message", OnMessage);

// event handler

void OnMessage(Socket socket, Packet packet, params object[] args) {
// args[0] is the nick of the sender
// args[1] is the message
Debug.Log(string.Format("Message from {0}: {1}", args[0], args[1])); 
}

  • “connect”: Sent when the namespace opens.
  • “connecting”: Sent when the SocketManager start to connect to the socket.io server.
  • “event”:Sentoncustom(programmerdefined)events.
  • “disconnect”: Sent when the transport disconnects, SocketManager is closed, Socket is closed or when no Pong message received from the server in the given time specified in the handshake data.
  • “reconnect”: Sent when the plugin successfully reconnected to the socket.io server.
  • “reconnecting”: Sent when the plugin will try to reconnect to the socket.io server.
  • “reconnect_attempt”: Sent when the plugin will try to reconnect to the socket.io server.
  • “reconnect_failed”: Sent when a reconnect attempt fails to connect to the server and the ReconnectAttempt reaches the options’ ReconnectionAttempts’ value.
  • “error”: Sent on server or internal plugin errors. The event’s only argument will be a BestHTTP.SocketIO.Error object.

Example :

private void SetAllEvents ()    {     
//Connect 

mySocket.On ("connect", OnConnect); 

//Get UserAction Data From Server

mySocket.On ("action", OnGetActionData); 

//Leave Roommy

Socket.On ("leave", OnLeaveRoomData); //Disconnect mySocket.On ("disconnect", OnDisconnect);             }    

//=== On Event's Methods ===// 

//Connect To Room 
private void OnConnect (Socket socket, Packet packet, params object[] args) {
Debug.Log ("Connect...");  
}

//Get User Action Data 

private void OnGetActionData (Socket socket, Packet packet, params object[] args) { 
var res = JSON.Parse (packet.ToString ()); Debug.Log(res); //Here display response... } 

//Leave Room Data 

private void OnLeaveRoomData (Socket socket, Packet packet, params object[] args) { Debug.Log ("Leave Room"); }  

//Disconnect From Room  

private void OnDisconnect (Socket socket, Packet packet, params object[] args)  {Debug.Log ("Disconnect..."); }

Step – 5 : Sending Events

Here Emit function is for the sending event. We have to pass the event name for the primary parameter and others parameters are optionally. These all the data will encoded to json/ dictionary data and then send these data to server. Optionally all the server response set to the callback.

// Send a custom event to the server with two parameters

manager.Socket.Emit("message", "userName", "message");

// Send an event and define a callback function that will be called as an // acknowledgement of this event

manager.Socket.Emit("custom event", OnAckCallback, "param 1", "param 2");

void OnAckCallback(Socket socket, Packet originalPacket, params object[] args) { 
Debug.Log("OnAckCallback!"); 
}

Sending acknowledgement to the server

You can send back an acknowledgement to the server by calling the socket’s EmitAck function. You have to pass the original packet and any optional data:

manager["/customNamespace"].On("customEvent", (socket, packet, args) => {socket.EmitAck(packet, "Event", "Received", "Successfully"); });

You can keep a reference to the packet, and call the EmitAck from somewhere else.

Example :

//Send User Action Data
public void SendGameActionDataToServer (float objXPos, float objYPos, string senderDeviceUniqueId) {
Dictionary<string, object> gameActionData = new Dictionary<string, object> ();
gameActionData.Add ("objXPos", objXPos);
gameActionData.Add ("objYPos", objYPos);
gameActionData.Add ("senderDeviceUniqueId", senderDeviceUniqueId);
mySocket.Emit ("action", OnSendEmitDataToServerCallBack, gameActionData);
}

//Send Leave Room Data    
public void LeaveRoomFromServer (){
mySocket.Emit ("leave", OnSendEmitDataToServerCallBack);
}

Step – 6 : Sending Binary Data [Optional]

This is the most efficient way, because it will not convert the byte array to a Base64 encoded string on client side, and back to binary on server side.

byte[] data = new byte[10];manager.Socket.Emit("eventWithBinary", "textual param", data);

Step – 7 : Receiving Binary Data [Optional]

On client side these packets will be collected and will be merged into one packet. The binary data will be in the packet’s Attachments property.

Socket.On("frame", OnFrame);void OnFrame(Socket socket, Packet packet, params object[] args){texture.LoadImage(packet.Attachments[0]); }

Step – 8 : Make Game concept in Unity Engine

3

4

Step – 9 : Create and Implement Socket.IO script

Add MySocketManager script to empty gameobject.

5

MySocketManager.cs

using UnityEngine;
using System;
using BestHTTP;
using BestHTTP.SocketIO;
using SimpleJSON;
using System.Collections.Generic;

public class MySocketManager : MonoBehaviour
{
    #region PUBLIC_VARS

    //Instance
    public static MySocketManager instance;

    //Set Namespace For Current Player
    public string namespaceForCurrentPlayer;

    //SocketManager Reference
    public SocketManager socketManagerRef;

    //Socket Reference
    public Socket mySocket;

    //Options
    SocketOptions options;

    #endregion

    #region PRIVATE_VARS

    #endregion

    #region UNITY_CALLBACKS

    // Use this for initialization
    void Start ()
    {
        //Instance
        instance = this;

        //Create Socket Ref
        CreateSocketRef ();
    }

    //Leave Room After Quite The Game
    void OnApplicationQuit ()
    {
        LeaveRoomFromServer ();
        DisconnectMySocket ();
    }

    #endregion

    #region PUBLIC_METHODS

    public void CreateSocketRef ()
    {
        TimeSpan miliSecForReconnect = TimeSpan.FromMilliseconds (1000);

        options = new SocketOptions ();
        options.ReconnectionAttempts = 3;
        options.AutoConnect = true;
        options.ReconnectionDelay = miliSecForReconnect;

        //Server URI
        socketManagerRef = new SocketManager (new Uri ("http://127.0.0.1:4001/socket.io/"), options);

    }

    public void SetNamespaceForSocket (string socketNamespace)
    {
        namespaceForCurrentPlayer = socketNamespace;
        mySocket = socketManagerRef.GetSocket (namespaceForCurrentPlayer);

        //Set All Events, When Join The New Room
        SetAllEvents ();
    }

    //=== Emit Events ===//

    //Send User Action Data
    public void SendGameActionDataToServer (float objXPos, float objYPos, string senderDeviceUniqueId)
    {
        Dictionary<string, object> gameActionData = new Dictionary<string, object> ();
        gameActionData.Add ("objXPos", objXPos);
        gameActionData.Add ("objYPos", objYPos);
        gameActionData.Add ("senderDeviceUniqueId", senderDeviceUniqueId);

        mySocket.Emit ("action", OnSendEmitDataToServerCallBack, gameActionData);
    }

    //Send Leave Room Data
    public void LeaveRoomFromServer ()
    {
        mySocket.Emit ("leave", OnSendEmitDataToServerCallBack);
    }

    //Disconnect My Socket
    public void DisconnectMySocket ()
    {
        mySocket.Disconnect ();
    }

    #endregion

    #region PRIVATE_METHODS

    private void SetAllEvents ()
    {

        //Get UserAction Data From Server
        mySocket.On ("action", OnGetActionData);

        //Leave Room
        mySocket.On ("leave", OnLeaveRoomData);

        //Connect
        mySocket.On ("connect", OnConnect);

        //Re-Connect
        mySocket.On ("reconnect", OnReConnect);

        //Re-Connecting
        mySocket.On ("reconnecting", OnReConnecting);

        //Re-Connect Attempt
        mySocket.On ("reconnect_attempt", OnReConnectAttempt);

        //Re-Connect Attempt
        mySocket.On ("reconnect_failed", OnReConnectFailed);

        //Disconnect
        mySocket.On ("disconnect", OnDisconnect);

    }

    //=== On Event's Methods ===//

    private void OnConnect (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Connect...");
    }

    private void OnReConnect (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Re-Connect...");
    }

    private void OnReConnecting (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Re-Connecting...");
    }

    private void OnReConnectAttempt (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Re-Connect Attempt...");
    }

    private void OnReConnectFailed (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Re-ConnectFailed...");
    }

    //Get User Action Data
    private void OnGetActionData (Socket socket, Packet packet, params object[] args)
    {
        var res = JSON.Parse (packet.ToString ());
        GameManager.instance.RefreshGamePlayerUI (res [1]);
    }

    //Leave Room Data
    private void OnLeaveRoomData (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Leave Room");
    }

    //Disconnect From Room
    private void OnDisconnect (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Disconnect...");
    }

    //=== Emit Event's Methods ===//

    private void OnSendEmitDataToServerCallBack (Socket socket, Packet packet, params object[] args)
    {
        Debug.Log ("Send Packet Data : " + packet.ToString ());
    }

    #endregion
}

Step – 10 : Create and Implement GameManager script

6

MyDeviceUnique ID : Get device’s unique id for getting unique user for real MMO(Massively Multiplayer Online) functionality.
Main Menu Screen : Mainmenu UI Screen.
Game Play Screen : Gameplay Object Screen.
Game Play UI : Gam Play UI Screen.
Blue Obj : Reference object for display own movement.
Red Obj : Reference object for showing opponent(Red Obj)’s movement.
Movement Speed : Object movement speed.

GameManager.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using SimpleJSON;

public class GameManager : MonoBehaviour
{
    #region PUBLIC_VARS
    //Instance
    public static GameManager instance;

    //My Device Unique ID
    public string myDeviceUniqueID;

    //GameOver Screen
    public GameObject mainMenuScreen;
    public GameObject gamePlayScreen;
    public GameObject gamePlayUI;

    //Objects
    public Transform blueObj;
    public Transform redObj;

    //Movement Speed
    public float movementSpeed;
    #endregion

    #region PRIVATE_VARS
    //Store RedObj New Position
    private Vector2 newPosition;

    #endregion

    #region UNITY_CALLBACKS

    // Use this for initialization
    void Start ()
    {
        //Instance
        instance = this;

        //Set My Device Unique ID
        myDeviceUniqueID = SystemInfo.deviceUniqueIdentifier;

        //Init Thief New Position
        newPosition = new Vector2 (0, 0);
    }

    #endregion

    #region PUBLIC_METHODS

    //On Let's Play Btn Clicked
    public void OnLetsPlay ()
    {
        GetRoomData ();
    }

    //On PlayAgain Btn Clicked
    public void OnPlayAgain ()
    {
        Time.timeScale = 1;
        Application.LoadLevel (0);
    }

    //Show My Screen
    public void ShowMyScreen (GameObject myScreen)
    {
        myScreen.SetActive (true);
    }

    //Hide My Screen
    public void HideMyScreen (GameObject myScreen)
    {
        myScreen.SetActive (false);
    }

    //Move Object
    public void MoveObject (string ObjDir)
    {
        if (ObjDir == "Left") {
            blueObj.Translate (Vector3.left * movementSpeed * Time.deltaTime);
        } else if (ObjDir == "Right") {
            blueObj.Translate (Vector3.left * -movementSpeed * Time.deltaTime);
        } else if (ObjDir == "Up") {
            blueObj.Translate (Vector3.down * -movementSpeed * Time.deltaTime);
        } else if (ObjDir == "Down") {
            blueObj.Translate (Vector3.down * movementSpeed * Time.deltaTime);
        }

        //clamping
        blueObj.position = new Vector2 (Mathf.Clamp (blueObj.localPosition.x, -28, 28), Mathf.Clamp (blueObj.localPosition.y, -15, 15));

        //Send Object Position To Server
        MySocketManager.instance.SendGameActionDataToServer (blueObj.position.x, blueObj.position.y, myDeviceUniqueID);
    }

    //Refresh Game UI Data
    public void RefreshGamePlayerUI (JSONNode gameUIData)
    {
        newPosition.x = gameUIData ["objXPos"].AsFloat;
        newPosition.y = gameUIData ["objYPos"].AsFloat;

        if (gameUIData ["senderDeviceUniqueId"].Value != myDeviceUniqueID) {
            redObj.localPosition = newPosition;
        } 
    }

    #endregion

    #region PRIVATE_METHODS

    private void GetRoomData ()
    {
        //Get Room Data
        WWW getRoomData = new WWW ("http://127.0.0.1:4001/ws/getRoom");
        StartCoroutine (WaitForGetRoomDataResponse (getRoomData));
    }

    IEnumerator WaitForGetRoomDataResponse (WWW www)
    {
        yield return www;
        var res = JSON.Parse (www.text);

        if (res ["status"].Value == "true") {
            HideMyScreen (mainMenuScreen);
            ShowMyScreen (gamePlayScreen);
            ShowMyScreen (gamePlayUI);

            //=== Send Data To Server For Create Namespace ===//
            string namespaceForRoom = "/room-" + res ["data"] ["room_id"].Value;

            //Create Namespace For Current User And Send To Server
            MySocketManager.instance.SetNamespaceForSocket (namespaceForRoom);
        }
    }

    #endregion
}

Step – 11 : Build the Apk or standalone file and let’s play and enjoy the game.

Sudhir Kotila

Sudhir Kotila | Unity3D Game Developer

I'm a professional Game Developer at Yudiz Solutions Pvt. Ltd - a leading mobile game development company. I'm enjoying my work with Unity3D since last 3 years and playing with my code. I love to develop different types of addictive as well high quality games .I'm always ready to learn new gaming concepts for enhance my knowledge. I'm very passionate about my work and ready to take up challenging projects.

A Quick guide to Socket IO Communication

$
0
0

Socket.IO

Socket.IO is a JavaScript library for realtime internet applications. It permits real time, bidirectional communication between internet shoppers and servers. It has 2 parts: a client-side library that runs within the browser, and a server-side library for node.js.

It provides more options, as well as broadcasting to multiple sockets, storing information related to every client, and asynchronous I/O.

Socket.IO Features

Socket.IO provides the flexibility to implement time period analytics, binary streaming, instant electronic communication, and document collaboration.

Socket.IO handles the connection transparently. It will automatically upgrade to WebSocket if possible. This requires the programmer to only have Socket.IO knowledge.

Introduction :

The application is based on chatting using Scoket.IO .The application code will help you to use Socket.IO in your android application.

The application provides below functionalities :-

1) Sending Messages to all users.

2) Notify when the user leaves or joins the room.

3) Indicates if the user has started typing.

Adding the Dependencies :

First you need to install the Socket.IO with gradle.

Add the below line in your build.gradle file :-

dependencies {
    compile 'com.github.nkzawa:socket.io-client:0.3.0'
}

Permissions Needed :

You must give the internet permission to AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />

How to use socket in Activity and Fragment :

First, you need to create an object of the Socket object.

private Socket socket;
        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        try {
            socket = IO.socket("http://41.185.91.27:3001");
            //replace the URL
            socket.on(Socket.EVENT_CONNECT, onConnect);
            socket.on(Socket.EVENT_DISCONNECT, onDisconnect);
            socket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
            socket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
            socket.on("getActiveUsers", socketGetActiveUserListner);
            socket.on("addMeToRoom", socketAddMeToRoomListner);
            socket.on("newMessage",newMessageListner);       
            socket.connect();    //Connect socket to server
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
}

Using socket.connect() we are going to connect through server. Different type of listener is provided by the Socket.IO and we can use that using socket.on() method like above.

socket.on() method attach the listener which automatically called.

Socket.EVENT_CONNECT – Call when the connection is successfully created.
Socket.EVENT_DISCONNECT – Call when the connection is terminated.
Socket.EVENT_CONNECT_ERROR – Call when any error occur.
Socket.EVENT_CONNECT_TIMEOUT – Call if timeout occur.

You can also add custom listener like getActiveUser to get all active user and addMeToRoom to add in specific room.

Emitting events :

socket.emit() is used to send the message.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    String message = et_message.getText().tostring();
    socket.emit("newMessage",message);
}

Listener:

Create the listener to get different events callback and perform task accordingly.

private Emitter.Listener onDisconnect = new Emitter.Listener(){
    @Override
        public void call(final Object... args) {
            if (getActivity() != null)
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                           
                           //perform anything


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        }
    };

onDisconnect call if the connection is terminated.

private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            
            //perform anything


        }
};

onConnectError call if any error occur.

private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {


            if (getActivity() != null)
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       
                       //perform any task


                    }
                });
        }
};

onConnect call if the connection is successfully created.

I hope you find my article useful to implement Socket IO in your Android Application. Suggestions are welcomed, please do comment below.

Mahavir Nahta

Mahavir Nahta | Android Developer

I am an Android Developer at Yudiz Solutions Pvt. Ltd. - a Mobile App Development company. I am passionate about developing android apps and like to work with real-time data communication with hardware connectivity, to maximize development efficiency and produce innovative applications.

Developer’s guide to ECMA Script 6 – Part 1

$
0
0

ECMAScript (ES) is a trademarked scripting-language specification standardized by Ecma International in ECMA-262. It was based on JavaScript, which now tracks ECMAScript. What you know as JavaScript in browsers and Node.js is actually a superset of ECMAScript.

You’ve probably heard about ECMAScript 6 (or ES6) already. It’s the next version of JavaScript, and it has some great new features for managing large and complex codebases. The features have varying degrees of complexity and are useful in both simple scripts and complex applications. In this article, we’ll discuss a hand-picked selection of ES6 features that you can use in your everyday JavaScript coding.

Block Bindings

In most C-based languages, variables (or bindings) are created at the spot where the declaration occurs. In JavaScript, however, this is not the case. Where your variables are actually created depends on how you declare them, and ECMAScript 6 offers options to make controlling scope easier

Only one small problem remains: the front end ecosystem barely supports ES6 modules. No browser natively supports all the new features of ES6. Tools called transpilers, like Babel and Traceur, can precompile ES6 modules into valid ES5 code, which today’s browsers can process; but that ES5 has to be wrapped in an asynchronous syntax and then handled.

In my opinion, switching to ES6 is worthwhile for the syntax changes alone. You may be shaking your head, but I think things such as block scoping, arrow functions, object property and method shorthands, default parameters, and template strings can really help to streamline your code. Taking default function parameters as an example, it might only take an extra line of code to do this in ES5 but every extra line you don’t have to type makes your code more concise and more readable. You can focus on logic over boilerplate.

Var Declarations

Variable declarations using var are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occur.

Consider the following function definition:

function getValue(condition) {

    if (condition) {
        var value = "blue";

        // other code

        return value;
    } else {

        // value exists here with a value of undefined

        return null;
    }

    // value exists here with a value of undefined
}

If you are unfamiliar with JavaScript, then you might expect that variable value only created if condition satisfied. In fact, the variable value is created regardless. Behind the scenes, the JavaScript engine changes the getValue function to look like this:

function getValue(condition) {

    var value;

    if (condition) {
        value = "blue";

        // other code

        return value;
    } else {

        return null;
    }
}

That means the variable value is actually still accessible from within the else clause. If accessed from there, the variable would just have a value of undefined because it hasn’t been initialized.

It often takes new JavaScript developers some time to misunderstanding this unique behavior can end up causing bugs. For this reason, ECMAScript 6 introduces block level scoping options to make the controlling a variable’s lifecycle a little more powerful.

Block-Level Declarations

Block-level declarations are those that declare variables that are inaccessible outside of a given block scope. Block scopes, also called lexical scopes, are created:

  • Inside of a function
  • Inside of a block (indicated by the { and } characters)

Let Declarations

The let declaration syntax is the same as the syntax for var. You can basically replace var with let to declare a variable, but limit the variable’s scope to only the current code block

function getValue(condition) {

    if (condition) {
        let value = "blue";

        // other code

        return value;
    } else {

        // value doesn't exist here

        return null;
    }

    // value doesn't exist here
}

Since the variable value is declared using let instead of var, the variable value is no longer accessible once execution flows out of the if block. If condition evaluates to false, then value is never declared or initialized.

No Redeclaration

If an identifier has already been defined in a scope, then using the identifier in a let declaration inside that scope causes an error to be thrown. For example:

var count = 30;

// Syntax error
let count = 40;

On the other hand, no error is thrown if a let declaration creates a new variable with the same name as a variable in its containing scope, as demonstrated in the following code:

var count = 30;

// Does not throw an error
if (condition) {

    let count = 40;
}

This let declaration doesn’t throw an error because it creates a new variable called count within the if statement, instead of creating count in the surrounding block. Inside the if block, this new variable shadows the global count, preventing access to it until execution leaves the block.

Constant Declarations

Variables declared using const are considered constants, meaning their values cannot be changed once set. For this reason, every const variable must be initialized on declaration, as shown in this example:

const MY_CONSTANT = 1;
MY_CONSTANT = 2 // Error
const SOME_CONST; // Error

Since the variable value is declared using let instead of var, the variable value is no longer accessible once execution flows out of the if block. If condition evaluates to false, then value is never declared or initialized.

No Redeclaration

If an identifier has already been defined in a scope, then using the identifier in a let declaration inside that scope causes an error to be thrown. For example:

var count = 30;

// Syntax error
let count = 40;

Note that you can still change object properties or array members:

const MY_OBJECT = {some: 1};
MY_OBJECT.some = 'body'; // Cool

Constants, like let declarations, are block-level declarations. That means constants are no longer accessible once execution flows out of the block in which they were declared, as demonstrated in this example:

if (condition) {
const MY_CONSTANT = 1;
}

// MY_CONSTANT isn't accessible here

In another similarity to let, a const declaration throws an error when made with an identifier for an already-defined variable in the same scope. It doesn’t matter if that variable was declared using var (for global or function scope) or let (for block scope). For example, consider this code:

var message = "Hello!";
let age = 25;

// Each of these would throw an error.
const message = "Goodbye!";
const age = 30;

Declaring Objects with Const

A const declaration prevents modification of the binding and not of the value itself. That means const declarations for objects do not prevent modification of those objects. For example:

const person = {
    name: "Nicholas"
};

// works
person.name = "Greg";

// throws an error
person = {
    name: "Greg"
};

A variable declared with either let or const cannot be accessed until after the declaration. Attempting to do so results in a reference error, even when using normally safe operations such as the typeof operation in this example:

if (condition) {
    console.log(typeof value);  // ReferenceError!
    let value = "blue";
}

This is true anytime you attempt to use a variable declared with let or const before it’s been defined. As the previous example demonstrated, this even applies to the normally safe typeof operator. You can, however, use typeof on a variable outside of the block where that variable is declared, though it may not give the results you’re after. Consider this code:

console.log(typeof value);     // "undefined"

if (condition) {
    let value = "blue";
}

The typeof operation executes because it occurs outside of the block in which value is declared. That means there is no value binding, and typeof simply returns “undefined”.

Block Binding in Loops

Perhaps one area where developers most want block level scoping of variables is within for loops, where the throwaway counter variable is meant to be used only inside the loop. For instance, it’s not uncommon to see code like this in JavaScript:

for (var i = 0; i < 10; i++) {
    process(items[i]);
}

// i is still accessible here
console.log(i);                     // 10

In JavaScript, however, the variable i is still accessible after the loop is completed because the var declaration gets hoisted. Using let instead, as in the following code, should give the intended behavior:

for (let i = 0; i < 10; i++) {
    process(items[i]);
}

// i is not accessible here - throws an error
console.log(i);

In this example, the variable i only exists within the for loop. Once the loop is complete, the variable is no longer accessible elsewhere.

Functions in Loops

The characteristics of var have long made creating functions inside of loops problematic, because the loop variables are accessible from outside the scope of the loop. Consider the following code:

var funcs = [];

for (var i = 0; i < 10; i++) {
    funcs.push(function() { console.log(i); });
}

funcs.forEach(function(func) {
    func();     // outputs the number "10" ten times
});

You might ordinarily expect this code to print the numbers 0 to 9, but it outputs the number 10 ten times in a row. That’s because i is shared across each iteration of the loop, meaning the functions created inside the loop all hold a reference to the same variable. The variable i has a value of 10 once the loop completes, and so when console.log(i) is called, that value prints each time.

A let declaration simplifies loops by effectively mimicking what the IIFE does in the previous example. On each iteration, the loop creates a new variable and initializes it to the value of the variable with the same name from the previous iteration. That means you can omit the IIFE altogether and get the results you expect, like this:

var funcs = [];

for (let i = 0; i < 10; i++) {
    funcs.push(function() {
        console.log(i);
    });
}

funcs.forEach(function(func) {
    func();     // outputs 0, then 1, then 2, up to 9
})

The let declaration creates a new variable i each time through the loop, so each function created inside the loop gets its own copy of i. Each copy of i has the value it was assigned at the beginning of the loop iteration in which it was created.

Global Block Bindings

When var is used in the global scope, it creates a new global variable, which is a property on the global object (window in browsers). That means you can accidentally overwrite an existing global using var, such as:

// in a browser
var RegExp = "Hello!";
console.log(window.RegExp);     // "Hello!"

var ncz = "Hi!";
console.log(window.ncz);        // "Hi!"

Even though the RegExp global is defined on window, it is not safe from being overwritten by a var declaration.

If you instead use let or const in the global scope, a new binding is created in the global scope but no property is added to the global object. That also means you cannot overwrite a global variable using let or const, you can only shadow it. Here’s an example:

// in a browser
let RegExp = "Hello!";
console.log(RegExp);                    // "Hello!"
console.log(window.RegExp === RegExp);  // false

const ncz = "Hi!";
console.log(ncz);                       // "Hi!"
console.log("ncz" in window);           // false

Here, a new let declaration for RegExp creates a binding that shadows the global RegExp. That means window.RegExp and RegExp are not the same, so there is no disruption to the global scope.

Doli Vadiya

Doli Vadiya | Sr. PHP Developer

Doli Vadiya is a Web and Hybrid mobile app developer at Yudiz Solutions Pvt. Ltd., who has the knowledge of PHP, Angular JS, Ionic, NodeJS. Eager to explore and improve javascript development.

10 Best Tips to Swift Development from Swift expert

$
0
0

1. For Loop vs While Loop

Example: Print “Count” 5 times

// Okay Code 
var i = 0 
while 5 > i {
   print("Count :\(i)”) 
   i += 1
}

You made the variable “i” to make sure your computer doesn’t break by printing limited numbers.

Listen, more variables → more memorization → more headache → more bugs → more life problems.

Remember the Butterfly effect.

// 😍 Code

for i in 1...5 {
 print("Count  :\(i)”)
}

2. Optional Unwrapping

Example: Guard let vs if let

Let’s make a program for welcoming a new user.

var username: String?
var password: String?

// Hideous Code
func userLogIn() {
 if let uName = username {
  if let pwd = password {
   print("Welcome, \(uName)"!)
  }
 }
}

Do you see the pyramid of doom? Those are nasty nested code. Never. Destroy the bad, bring the good.

// Pretty Code

func userLogIn() {
 guard let uName = username, let pwd = password 
  else { return } 
 print("Welcome, \(uName)!") 
}

The difference is trendemous. If username or password has a nil value, the pretty code will early-exit the function by calling “return”. If not, it will print the welcoming message.

3. Extension

Example: Square a number

// Okay Version
func square(x: Int) -> Int { return x * x }
var squaredOfSix = square(x: 6)
square(x: squaredOfSix) // 625

The useless variable was created to double square 6— we need not enjoy typing.

// 😎 Version

extension Int { 
 var squared: Int { return self * self }
}

6.squared // 36
6.squared.squared // 1296

4. Generics

Example: Print all elements in an array

// 👿 Code

var arrString   = [“John Cena", “Tom Cruise", “Kristen Stewart"]
var arrInt		 = [4, 5, 6, 7, 8]
var arrDouble 	 = [6.0, 8.0, 10.0]

func printStringArray(arr: [String])
  for str in arr { 
    print(str) 
  } 
}

func printIntArray(arr: [Int]) {
  for i in arr {
    print(i)
  } 
}

func printDoubleArray(arr: [Double]) {
  for d in arr {
     print(d) 
  }
 }

Too many useless functions. Let’s create just one.

// 😍 Code

func printElementFromArray(arr: [T]) {
  for element in arr { 
    print(element)  
  } 
}

5. Functional Programming

Example: Get even numbers

// Imperative 
var arrEvens : [Int] = []
for i in 1…20 {
 if i % 2 == 0 { arrEvens.append(i) } }
print(arrEvens) // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

I don’t need to see the entire process. I am wasting my time reviewing how your for-loop looks like. Let’s make it explicit.

// Declarative 😎
var evens = Array(1…20).filter { $0 % 2 == 0 } 
print(evens) // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Functional Programming is phenomenal.
Functional Programming makes you look smart.

6. Closure vs Func

// Normal Function 
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 6, y: 8) // 14

You need not memorize the name of the function and the variable — You just need one.

// Closure
var sumUsingClosure: (Int, Int) -> (Int) = { $0 + $1 }
sumUsingClosure(6, 8) // 14

7. Computed Property vs Function

Example: finding a diameter of a circle

// 💩 Code
func getDiameter(radius: Double) -> Double { return radius * 2}
func getRadius(diameter: Double) -> Double { return diameter / 2}

getDiameter(radius: 20) // return 40

getRadius(diameter: 400) // return 200

getRadius(diameter: 800) // return 400

You created two mutually exclusive functions. Atrocious. Let’s connect the dot between radius and diameter.

// Good Code
var radius: Double = 20
var diameter: Double {
 get { return radius * 2}
 set { radius = newValue / 2} 
} 

radius // 20

diameter // 40

diameter = 8000 

radius // 4000

Now, the radius and diameter variables are interdependent of each other. More connections → less extra typing → fewer typos → fewer bugs → fewer life problems. 💅

8. Enum to Type Safe

Example: Ticket Selling

// Simply Bad

switch person {
 case "Adult": print("Pay $12”)
 case "Child": print("Pay $4”)
 case "Senior": print("Pay $8”)
 default: print("You alive, bruh?") }

“Adult”, “Child”, “Senior” → you are hard coding. You are literally typing all these string values for each case. That’s a no no. I explained what happens when you write too much. We never enjoy typing.

// 👌 Code
enum People { case adult, child, senior }
var person = People.adult
switch person {
 case .adult: print("Pay $12”)
 case .child: print("Pay $4”)
 case .senior: print("Pay $8”)
}

You will never make a typo because “.adult”, “.child”, “.senior” highlight themselves. If the switch statement encountered unknown cases beyond the scope of the designated enum, Xcode would scream with that red error (😡) on the left side. — I just couldn’t find the right emoji.

9. Nil Coalescing

Example: User choosing Twitter theme color

// Long Code
var userChosenColor: UIColor? 
var defaultColor = UIColor.red
var colorToUse = UIColor.clear
if let Color = userChosenColor { colorToUse = Color } else
 { colorToUse = defaultColor }

Too long. Let’s cut the fat.

// Concise AF
var colorToUse = userChosenColor ?? defaultColor

The code above states, if userChosenColor returns nil, choose defaultColor (red). If not, choose userChosenColor.

10. Conditional Coalescing

Example: Increase height if you have spiky hair

// Simply Verbose
var currentHeight = 160
var hasSpikyHair = true
var finalHeight = 0
if hasSpikyHair { finalHeight = currentHeight + 5} 
 else { finalHeight = currentHeight }

Too long. Let’s cut the fat.

// Lovely Code
finalHeight = currentHeight + (hasSpikyHair ? 5: 0)

The code above states, if hasSpikeHair is true, add 5 to the final height, if not add zero.

Sandeep Joshi

Sandeep Joshi | iOS Developer

I’m Sandeep Joshi - an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App Development company. I am ambitious and intensely interested in what I do. You'll quickly find that I do not merely develop software - I develop highly maintainable, elegant code that will save you enormous sums in the long run.

What is Contextual Design? And It’s Evolution

$
0
0

How the customers are experiencing your application? To me this is so important because I have personally ended up using some applications that are terrible. An appealing and magnificient application allure interactive user experience technically feasible.

Engaging user experience, user interfaces, information visualization and storytelling can be accomplished with the assistance of Contextual Design.

What is Contextual Design?

Contextual Design serve as the most applicable information or content beforehand. This way, the flow is handled, number of clicks are reduced, increasing the liveliness of an application by reducing inactive stages or screens. As the app is opened, from dashboard to every stage of an application the user should feel and understand the purpose of application. In short, contextual design fulfills the user centric design process.

Core objective of your apps can be defined with these simple questions.

  • Who are the users of your service and how they differ from others?
  • What tasks does user performs in your app? What do you offer them?
  • Is location and date providing relevant information to your app?
  • Is user participation concerned with its role for an engaging app?
  • Is your website mobile-friendly? Does your app’s features and functionalities fit into different devices? Is your app responsive?

Contextual design is Handy

Context-responsive designs are used to solve a variety of software challenges:

  • Is user guidance needed through the stages?
    The dashboard which is the first screen of any application comes with a focussed call-to-action, keeps control on further steps, put up the updation and hence, by providing such details keeps the users engaging even if they are busy in their ongoing work.
  • Is your error message annoying your user?
    Language matters ! The tone of words in error messages can upset users. Here comes the key concept of contextual design that says to be stern with politeness. User participation is the major factor for an engaging application. Provide alternatives or suggestions helping them solve and move forward using the application. Follow the 4 H’s concept of writing an error message – Human, Helpful, Humble, Humorous.
  • Is your app clear or with unusual gesture controls?
    ‘Over Designing’ your app is a big no-no. Unfamiliar interface elements and ignoring the standards or unusual gesture controls often confuse users. Apply standard patterns. Be clear with design and use standard visual controls. For example, Qtrax.

Contextual design is Data Compelling

Contextual design is a wide scope where number of considerations can be given a thought with no limitations. Some are described below as roles, task etc.

  • User/Roles – Each role of user is designated a unique UI depending on its functionalities and the type of user.The Alert ME app’s home screen contains Emergency button which sends a predefined message automatically to the person as the details mentioned already in the app. The person in an emergency just have to give a simple tap on the button located in the Home screen.
  • Location – Mapping, travel, distance, restaurants and a great number of apps depend on the location information. Healthcare app like Carepack has this outstanding feature of keeping a track on the number of steps where your help information is always under your control. Quick information can be gained using wearable device anywhere at your home or at parks using Carepack.
  • Date and time – If you are a kind of person who needs to be notified with the stream of reminders all day long, from the morning news to end of day reflections, date and time has its own stand in contextual designing. Apps like Season helps user residing in one place can get information about date and time in some other terrain.
  • Task – Qualitative data aggregation is an important factor of contextual design. Apps like Biton, a relay race format is an app where user uploads their posts in a period of time and same task is then assigned to other users in group while race was created. This way tasks gets allocated automatically to other users who grabbed the biton while the main user is benched.
  • Device – With the use of Material design and flat design trends in 2016, Responsive design will augment. Hence, device awareness is must at core level for understanding the limitations and identify the drawbacks of any application or website. Mobile- friendly websites is a must-have.

Contextual design is a Bliss

How these awesome apps are making life easier has infinite answers to it. Carrying your phone with useful apps like weather app help you get notified which users fail to care about how useful the apps have been. In making your app good to great, you need felicity as an ingredient for the “Whoa” factor. Some apps like SEASON app having charming animation represent pleasant example of knowing the current weather conditions.

1

2

3

Shivangi Parmar

Shivangi Parmar | Business Development Executive

Shivangi Parmar is a part of Business Development at Yudiz,
an iPhone App development company. She enjoys writing about Technology, marketing & industry trends. She is tech enthusiast and loves to explore new technical stuff. You can follow her @shivangip94.

5 CSS3 tricks with Pseudo Elements ::before and ::after

$
0
0

Overview

Most of the people think that there is no major difference between Pseudo Classes and Pseudo Elements, but there is one major difference that exists between these two.

Nowadays we all know that we have used these kind of classes and elements as a part of CSS3. The newly defined CSS3 presents such type of Pseudo Elements.

Difference between Pseudo Classes and Pseudo Elements

Pseudo Classes: Used as selectors that assists some selections that are not expressed by simple selectors. In a simple way we are able to do some kind of CSS effects using these types of classes that we can’t do with the particular selector.

For ex:, :hover, :active

Pseudo Elements: Used to create new elements that do not exist normally in document and they are manipulated as a normal selector.

For ex:, ::after, ::before

Here we can see there is one difference between these two and that is the use of “colon (:)”.

Yes for Pseudo Classes we have used single colon ( : ) and for Pseudo Elements we have used double colon ( :: ) which is one of the CSS3 syntax. Browsers support both types of syntax but in IE (version older than 9) do not support this double colon ( :: ) format.

The important property for Pseudo Elements is content: “ ”.

Values for content property are:

Content: ” ”
Content: ” any specific value ”

Let’s begin with some CSS tricks with Pseudo Elements:

Method 1 ) Pseudo Elements with Font Awesome

As per the latest web design trends most of the websites are now using Font Awesome to create iconic fonts rather than using images as  icons which increases the loading speed of any website.

Example:

HTML Code:

<ul>
    <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
</ul>

CSS Code:

ul li::before            { content: "\f054"; font-family: FontAwesome;}

Let’s have a look on below screen.

Result:

screenshot-1

Method 2 ) Pseudo Elements with Background

Have you ever tried to give a background image to any element using this kind of CSS? If not then just try the below code.

Example:

HTML Code:

<h2>I have the background Image</h2>

CSS Code:

h2::after     { width: 100%; height: 23px; content: ""; background: url("../images/separator.png") no-repeat center center; display: block;}

Let’s have a look on below screen.

Result:

screenshot-2

Method 3 ) Pseudo Elements with Content Property

This is the most interesting and amazing trick to do. Sometimes a situation occurs in which we have to add some text to any block and we are unable to do so. For this problem, here is the solution.

Example:

HTML Code:

<p>This is an example of Pseudo </p>

CSS Code:

p::after     { content: "Elements"; display: inline-block;}

Result:

screenshot-3

Method 4 ) Pseudo Elements with Clear floats

What happens if we forgot to clears the float of two blocks? It may display the horrible results. Some latest browsers are intelligent which ignores these type mistakes but some browsers does not. So here is the solution for clear floats but before that check the below screenshot without clearing the floats.

screenshot-4

Example:

HTML Code:

<div class=”container”>
    <div class=”left”>This is an example</div>
    <div class=”right”>This is an example</div>
</div>

CSS Code:

.container::after,
.container::before        { content: ""; display: block;}
.container::after         { clear: both;}
.left                     { margin-right: 15px; padding: 25px; width: 60%; float: left; background: #2a2a2a; color: #fff; text-align: center; min-height: 95px;}
.right                    { padding: 25px; width: 25%; float: left; background: #2a2a2a; color: #fff; text-align: center;}

And here is the final result after applying clear property using Pseudo Elements:

Result:

screenshot-5

Method 5 ) Pseudo Elements with Overlay blocks on hover

Latest graphic design market offers us to do overlay blocks as a hover effect for some block elements. For that we can also use the pseudo elements as a part of our design, not physically but visually.

Here is the screenshot how blocks appear in designs.

screenshot-6

Example:

HTML Code:

<ul>
   <li>
      <img alt="Image" src="images/thumb.jpeg">
      <p>Lorem Ipsum</p>
   </li>
   <li>
     <img alt="Image" src="images/thumb.jpeg">
     <p>Lorem Ipsum</p>
   </li>
</ul>

 

CSS Code:

ul li                { width: 49%; padding: 0 5px; display: inline-block; text-align: center; position: relative;}
ul li img            { max-width: 100%; height: auto;}
ul li p              { margin: 0; padding: 20px; background: #ffffff;}
ul li::after         { height: 100%; content: ""; background: rgba(0,0,0,0.8); position: absolute; top: 0; left: 5px; right: 5px; opacity: 0;}
ul li:hover::after,
ul li:hover::before  { opacity: 1; cursor: pointer;}
ul li::before        { content: "Hover Text"; position: absolute; top: calc(50% - 12px); left: calc(50% - 40px); color: #ffffff; opacity: 0; z-index: 10;}

Result:

screenshot-7

I hope you have enjoyed the blog and applied some magic tricks in your projects.

Hitarthi Suthar

Hitarthi Suthar | Sr. Web Designer

I am a Sr. Web Designer at Yudiz Solutions Pvt. Ltd. - a leading Web and Mobile Apps development company. I am passionate about my work as I like to explore new technologies and methods related to my profile. I am fond of craft and painting.

Magento 2 Basics Part 2

$
0
0

Read Magento 2 Basics Part 1

Get your Ecommerce flexibility using Magento 2

Magento 2 is the newest member of the Magento family, an open-source platform to accelerate your ecommerce goals. It has new and improved features that helps to increase user interaction and perform all business functions smoothly.

It basically integrates object-oriented programming with Relational DataBase Management System, while providing a Zend Framework in the background.

Just follow some simple steps described below to create category, products, and customers on your magento admin.

Programmatically Create Category, Products and Customer in Magento 2

With Magento 2 you can organise and administer your business data. Moreover its scalability feature allows you to make changes effortlessly.

Follow these simple steps given below to create category, products and customers.

Step 1: First Create the scripts/abstract.php file in magento root directory. Place the following code in the file.

<?php

use \Magento\Framework\AppInterface as AppInterface;
use \Magento\Framework\App\Http as Http;

use Magento\Framework\ObjectManager\ConfigLoaderInterface;
use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList as AreaList;
use Magento\Framework\App\State as State;

abstract class AbstractApp implements AppInterface
{
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        Event\Manager $eventManager,
        AreaList $areaList,
        RequestHttp $request,
        ResponseHttp $response,
        ConfigLoaderInterface $configLoader,
        State $state,
        Filesystem $filesystem,
        \Magento\Framework\Registry $registry
    ) {
        $this->_objectManager = $objectManager;
        $this->_eventManager = $eventManager;
        $this->_areaList = $areaList;
        $this->_request = $request;
        $this->_response = $response;
        $this->_configLoader = $configLoader;
        $this->_state = $state;
        $this->_filesystem = $filesystem;
        $this->registry = $registry;
    }

    public function launch()
    {
        $this->run();
        return $this->_response;
    }

    abstract public function run();

    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
    {
        return false;
    }
}
?>

Step 2: For Create category

Follow these subsequent steps

Step 2.1: Create scripts/createCategory.php file in magento root directory and place the code below to get category data.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CreateProductApp extends AbstractApp
{

    public function run()
    {
        try{
            $this->_objectManager->get('Magento\Framework\Registry')
                ->register('isSecureArea', true);

            $category = $this->_objectManager->create('Magento\Catalog\Model\Category', 
                ['data' =>[
                    "parent_id" => 2, // Parent Category ID For Create As Subcategory for specific Parent Category
                    "name" => "Test Category", // Category Name
                    "is_active" => true, // True/False for active or deactive category
                    "position" => 2,
                    "include_in_menu" => true // For Hide/Show category in Main Menu
                ]
            ]);

            $category->setCustomAttributes([
                "display_mode"=> "PRODUCTS", // PRODUCTS => For show only Product / PAGE => For show only specific Static Page / PRODUCTS_AND_PAGE => For both Products and Static Page
                "is_anchor"=> "1", // 1 => set as anchor / 0 => set anchor No 
                "custom_use_parent_settings"=> "0",
                "custom_apply_to_products"=> "0",
                "url_key"=> "test-category", // for category url
                "url_path"=> "test-category",
                "automatic_sorting"=> "0"
                //'new_attribute' => 'value' // <-- your attribute
            ]);

            $repository = $this->_objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
            $repository->save($category);

            if($repository)
            {
                echo "New Category Created.",'<br/>';
            }
        }
        catch(expetion $e)
        {
            echo $e;
        }
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CreateProductApp');
$bootstrap->run($app);
?>

Step 2.2: Run the command http://www.yourdomian.com/scripts/createCategory.php in your browser. This will create category.

Step 3: For Create Product (simple)

Follow these subsequent steps to create product (simple)

Step 3.1: Create scripts/createProduct.php file in magento root directory and place the code shown below in that file.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CreateProductApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', false);

        $productFactory = $this->_objectManager->create('\Magento\Catalog\Model\ProductFactory');

        // this needs to be set to avoid exception:
        // Magento\Framework\Exception\SessionException with message 'Area code not set: Area code must be set before starting a session.'
        // I don't know why ...
        $appState = $this->_objectManager->get("Magento\Framework\App\State");
        $appState->setAreaCode("en");

        $baseUrl =  $this->_storeManager->getStore()->getBaseUrl(); // for base url

        try{

            $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 

            // Get Website ID
            $websiteId  = $storeManager->getWebsite()->getWebsiteId();

            $product = $productFactory->create();
            $product->setWebsiteIds(array($websiteId)); //website ID the product is assigned to, as an array
            $product->setSku('sku-test'); // Set your sku here
            $product->setName('Simple Test Product'); // Name of Product
            $product->setShortDescription("test short description"); //product short description
            $product->setDescription("test full description"); //product full description
            $product->setAttributeSetId(4); // Attribute set id, 4 => default Attribute set
            $product->setStatus(1); // Status on product enabled/ disabled 1/0
            $product->setWeight(10); // weight of product (if setProductHasWeight(1) than set wight value)
            $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
            $product->setTaxClassId(0); // Tax class id
            $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
            $product->setCategoryIds(array(3)); // set categories to product
            $product->setPrice(100); // price of product
            $product->setStockData(
                                    array(
                                        'use_config_manage_stock' => 0,
                                        'manage_stock' => 1,
                                        'is_in_stock' => 1,
                                        'qty' => 999 // product qty
                                    )
                                );
            $repository = $this->_objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
            $product = $repository->save($product);

            $productId = $product->getId();
            $product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($productId);

            // for add product image
            $fullImagePath = "/import/1.jpg"; // put product image in root-folder/pub/media/import folder
            if (file_exists("../pub/media".$fullImagePath)) {
                try {
                    $product->addImageToMediaGallery($fullImagePath, array('image', 'small_image', 'thumbnail'), true, false);;
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            } else {
                echo 'Can not find image<br/>';
            }

            /// Custome options ///
            $sku = $product->getSku();       
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of Object manager

            $values = array(
                                array(
                                    'title'=>'Red',
                                    'price'=>10,
                                    'price_type'=>"fixed",
                                    'sku'=>"Red1",
                                    'sort_order'=>1,
                                    'is_delete'=>0,
                                    'option_type_id'=>-1,
                                ),
                                array(
                                    'title'=>'White',
                                    'price'=>10,
                                    'price_type'=>"fixed",
                                    'sku'=>"White1",
                                    'sort_order'=>1,
                                    'is_delete'=>0,
                                    'option_type_id'=>-1,
                                ),
                                array(
                                    'title'=>'Black',
                                    'price'=>10,
                                    'price_type'=>"fixed",
                                    'sku'=>"black1",
                                    'sort_order'=>1,
                                    'is_delete'=>0,
                                    'option_type_id'=>-1,
                                )
                            );

            $options = array(
                                array(
                                    "sort_order"    => 1,
                                    "title"         => "Field Option",
                                    "price_type"    => "fixed",
                                    "price"         => "",
                                    "type"          => "field",
                                    "is_require"    => 0
                                ),
                                array(
                                    "sort_order"    => 2,
                                    "title"         => "Color",
                                    "price_type"    => "fixed",
                                    "price"         => "",
                                    "type"          => "drop_down",
                                    "is_require"    => 0,
                                    "values"        => $values
                                ),
                                array(
                                    "sort_order"    => 2,
                                    "title"         => "Multiple Option",
                                    "price_type"    => "fixed",
                                    "price"         => "",
                                    "type"          => "multiple",
                                    "values"        => $values,
                                    "is_require"    => 0
                                )
                            );

                    foreach ($options as $arrayOption) {
                        $product->setHasOptions(1);
                        $product->getResource()->save($product);
                        $option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
                                ->setProductId($productId)
                                ->setStoreId($product->getStoreId())
                                ->addData($arrayOption);
                        $option->save();
                        $product->addOption($option);
                    }

            $product->save(); // save product

            echo "New Product created: ".$product->getName(); 
        }
        catch(expetion $e)
        {
            echo $e;
        }

    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CreateProductApp');
$bootstrap->run($app);
?>

Step 3.2: Run command http://www.yourdomian.com/scripts/createProduct.php in your browser. This will create simple product with image and custom options.

Step 4: For Create Customer

Follow these subsequent steps to create customer

Step 4.1: Create scripts/createCustomer.php file in magento root directory and put below code to  get all the Customer data.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CreateProductApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', false);

        try{

            $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
            // Get Website ID
            $websiteId  = $storeManager->getWebsite()->getWebsiteId();

            // Instantiate object (this is the most important part)
            $customer   = $this->_objectManager->create('\Magento\Customer\Model\Customer');
            $customer->setWebsiteId($websiteId);

            // Preparing data for new customer
            $customer->setEmail("email@domain.com"); // Customer Email
            $customer->setFirstname("First Name"); // Customer First Name
            $customer->setLastname("Last name"); // Customer Last Name
            $customer->setPassword("password"); // Customer Password

            // Save data
            $customer->save();
            //$customer->sendNewAccountEmail(); // Send Email to Customer
            echo "Create New Customer: ".$customer->getFirstname()." ".$customer->getLastname();
        }
        catch(expetion $e)
        {
            echo $e;
        }

    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CreateProductApp');
$bootstrap->run($app);
?>

Step 4.2: Run http://www.yourdomian.com/scripts/createCustomer.php  command in your browser. This will create customer in magento.

Hope this will help you!

Thank you.

Gordhan Chauhan

Gordhan Chauhan | Sr. Magento Developer

I work as Sr. Magento Developer in Yudiz Solutions Pvt. Ltd. -
a leading mobile apps, mobile games and web development company. I write blogs to share my knowledge and ideas to my audience. I am passionate about exploring and develop new stuff in magento and web development.
Viewing all 595 articles
Browse latest View live