31 January, 2020

How to convert String To DateTime In Unity C#

How to fetch Day, Month or year from date time string?
How to get Hour, minute or second from a date time string?

Following snippet of code can be used to deal with most of the forms of date time string in Unity C#
Instead of having time in the form of
  "2020-1-31 12:10:15" 
you can also pass
"31/1/2020 12:10:15 PM"

and or any such case of Date time in string.
Then from this DateTime object you can fetch any particular detail like Year shown in example below.


System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
DateTime tempDate = Convert.ToDateTime("2020-5-6 12:10:15", culture);
Debug.Log("Testing date time conversion: " + tempDate.Year);



This could be used to deal with date time strings of the form 
 "dd:MM:yyyy HH:mm:ss"
"yyyy:MM:dd HH:mm:ss"

20 January, 2020

How to dynamically create object using JSON data from REST API in Unity 3D

Over the years Unity has become all very powerful and not just easy. With it's easy to use interface and handy programming language C# it is one of the best possible IDE out there to make applications and not just games.

With the help of SimpleJSON and Unity Networking class you'll see how easy it is to handle web requests in Unity.

So today we are going to fetch and display data from REST API request. By displaying data I don't just mean showing the raw output of JSON but making the objects out of the response data which could be further used as per your requirement.

Let's get started.

First you need to make an API which will return some set of data. For example returning a user's friend list data will contain name, age, joining date of all their friends.
For creating an API you may follow my NodeJS tutorial

Once you have some API let's create a simple Unity application that will make a web request on Button click.
Go to a scene in Unity > Right click in the hierarchy and create a UI > Button.



Leave this be for now and let's create a script that will carry the function of this button.

In you 'Assets' folder create a new folder by the name 'Scripts' for keeping all our scripts.
Inside this folder right click and Create > C# script. Let's name this filer 'API.cs'

Inside API.cs create a method of a name of your choice which will start a coroutine upon call.

public void OnClickSendReq()
    {
        StartCoroutine(WebRequestCoroutine("parameter"));
    }


Now before we define this coroutine we first need to add support for Unity Networking.
Add 'using UnityEngine.Networking; in the beginning of the script.

Now we define our coroutine.
 IEnumerator UpdateReferredUsersList(string userId)
    {
        WWWForm form = new WWWForm();
        form.AddField("username", userId);

        using (UnityWebRequest www = UnityWebRequest.Post(APIURL, form))
        {
yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
               
            }
            else
            {
Debug.Log(www.downloadHandler.text);
}
}
}


This coroutine requires creates a web form using WWWForm and adds a form field 'username' with a value that is passed using the variable userId.

  WWWForm form = new WWWForm();
        form.AddField("username", userId);  


Then using UnityWebRequest we make a Post request on APIURL with the form.
  using (UnityWebRequest www = UnityWebRequest.Post(APIURL, form))

Then the response is handled in the next step.
Now we need to create Unity Game Objects using the data response from the API call. For that we first need to handle the data that is coming. In my case the response data is in JSON. 
To handle JSON data we'll be using a SimpleJSON. It is recommended to get it from the official website but in case you find it uncomfortable you may use a copy I uploaded to Github.

Now create a folder by the name 'Plugins' inside the 'Assets' folder and paste SimpleJSON file in there.


Now go back to editing API.cs and add 
  using SimpleJSON;
to the beginning.

Now in order to handle/parse the JSON data coming from our API response we need to create a Request object.
For this we'll be making a custom class. Add the following code to the extreme bottom of API.cs

public class RequestStatus
{
    public string status;
    public string msg;

    public static RequestStatus CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<RequestStatus>(jsonString);


    }

}


Now back to our coroutine inside the else block web request error checking add 

                int i = 0;
                while (i >= 0)
                {
                    string userExists= JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value;

                    if (
userExists  != "")
                    {
                                                   ListUserData(JSON.Parse(www.downloadHandler.text)["data"][i]["first_name"].Value,
                            JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value,
                            JSON.Parse(www.downloadHandler.text)["data"][i]["email"].Value
                        i++;
                    }
                    else
                    {
                        i = -1;
                    }
                }

This block of code will loop through all the data under 'data'  you might have to modify 
  JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value; 
according to the response of you API.

Now to create objects using the response data we called a method with the values of individual set of data.
In this method ListUserData we will instantiate a prefab that will hold the data of individual set.

Create a new method within the else block

                void ListUserData(string username, string email)
                {
                    Debug.Log("Listing users data by instantiating prefab!");
                    GameObject listingObject= Instantiate(userlistPrefab, userlistContainer);
                    UserListing userListing= 
listingObject.GetComponent<UserListing>();
                    userListing.PopulateUserData(username, email);

                }


Now this method will instantiate a prefab 'userlistPrefab' as a child object of 'userlistContainer'. 
We don't just want to instantiate an object but want the data to be displayed on this object. For this we will create a new class 'UserListing' which defines the listing object structure and will have a method 'PopulateUserData' for updating the values of the object.

Head back to Unity and inside Assets > Scripts > Create a new C# script UserListing.

Now inside UserListing 

using UnityEngine.UI;
public class UserListing : MonoBehaviour
{
    [SerializeField]  private Text username;
private string email;

public void PopulateUserData(string usernameInput, string emailInput)
    {
        username.text = usernameInput;
        email = emailInput;
    }
}


Now let's create our userListingPrefab to which UserListing class will be applied to.
To create a prefab head back to the scene in Unity and create an Empty GameObject 'UserScrollRect' inside the Panel.
There must a Panel under the Canvas already if you created a button in the very beginning of this tutorial.
If it is not there create a button now and redo the above step.
In the Inspector tab of UsersScrollRect click Add Component and add a Scroll Rect(script).
Uncheck Horizontal.



Now create a child object to UsersScrollRect by the name UserDataContainer which will hold all the prefab object we'll create next. Stretch and set position UserScrollRect according to your need. 
Add Vertical Layout Group (Script) to UserDataContainer.


Under UserDataContainer create a child object, preferably a UI > Image
Stretch it according to your need and Add a UI > Text Object to it. This will be carrying the username from the script.
Add UserListing script to UserListing Object.


Drag and drop Username text object in the blank field against Username in the script properties. In my case it says Name Text as this screenshot was taken later. So I hope this will not confuse anyone.

Once added drag and drop the UserListing object from Hierarchy to Prefabs folder in Project tab.

Create a new Empty Game Object, let's name it 'WWW' and attach API.cs we created above.
Add 
    [SerializeField] private GameObject userListingPrefab;
    [SerializeField] private GameObject UserInformationPanel;


to API.cs and drag and attach the prefab we created.
For the UserInformationPanel game object we have to add UserDataContainer we created above.

Open the inspector tab of our button and add  OnClickSendReq to be executed on click.


You might have to set up the objects hierarchy according to your need. I'll leave that to you.

Feel free to leave a comment if you need any help with this.








18 January, 2020

[FIXED]Google Chrome all Black after Windows Update

If you're having an issue with your Google Chrome where everything is turned black. The following fix will solve your problem in a matter of seconds.

What does it look like?
I've added a screenshot of what happened to my Google Chrome after the update.


Follow the following steps to fix the problem.
  1. Right click on Chrome shortcut and click properties.
  2. Inside properties, under Compatibility tab choose to Run this program in compatibility mode for Windows Vista. Any variant would do. If one doesn't work try other.

    and your Google Chrome should be up and running but if you'll restart it the problem will persist. To fix it permanently we need to tweak some settings.
  3. With the Chrome running Go to Settings and under Advanced Settings

    Disable 'User hardware acceleration when available'


Relaunch Chrome and it should be working fine now.
This post was updated from Google Chrome, so I know it works. ;)

3 Ways to Open Task Manager on a Laptop PC: Windows 7/8/10

Nowadays the use of electronic devices such as computers is increasing and has a very important role. This has a lot of impact especially on office workers who need computers to do some of their work in the office. The computer itself has a lot of fungi and can simplify the work of its users. To control the overall performance of a computer, a computer is usually equipped with a default application that allows users to see and control the activities that run on that computer. 
For example on computers with Windows operating systems, they are equipped with a default application from Microsoft called Task Manager. 
Task Manager has quite a lot of functions in a computer. Some functions of the task manager are to be able to see users or users who are online (with the notes the user must be in the same network), can sort and manage active application windows, can send short messages to fellow users on a local network, see applications that are failing consumes a lot of CPU, limiting certain applications in using and so on.

How to Open a Task Manager on a Laptop PC 
Tutorial to open this task manager you can use on your computer with Windows 7, 8 and 10 operating systems.

Opening Task Manager Through the Taskbar 
  1. Please first turn on your computer or laptop and let your computer run until all startup programs.
  2. Then move the mouse cursor to the taskbar panel at the bottom of your computer screen. 
  3. If the cursor is already on the taskbar, please proceed with right-clicking on your mouse, then after that select Task Manager. 
  4. After that you will be directed to the Task Manager application that you have successfully opened. 
  5. Now you can begin to control and monitor all applications and processes that run on your computer or laptop.
Open the Task Manager with Shortcuts on the Keyboard 
  1. As usual, please turn on your computer or laptop first and wait until all programs run. 
  2. After that, please press 3 key keys at the same time: CTRL + SHIFT + ESC. 
  3. After that you will be directed to the Task Manager application that you have successfully opened. 
  4. Now you can control and monitor all activities that run on your computer or laptop easily and more freely. 
  5. In addition to controlling, with this task manager you can also monitor and supervise various activities of various processes and applications running on your computer. 
  6. With this application you can also find suspicious applications and processes running on your computer and can stop the application or process before causing your computer problems.
How to open Taskmgr via Run 
  1. The first step you need to type WIN + R. 
  2. After that, type taskmgr and click OK 
  3. Then the taskmanager will open and you can use it. 


Task manager is one of the important things and is often opened on laptops so if you are expected to be able to open it. If there are ways that are still confused or there are things you want to ask, please ask in the comment column you want to ask.


14 January, 2020

Publish to Blogspot in 3 clicks using Chrome

BlogThis! for Blogger/Blogspot was discontinued. 
BlogThis! was a Chrome Extension that lets you quickly publish a blog post. 
BlogThis would allow the users to just click on the extension icon and write the post. Now that it is discontinued I managed to make a work around for it.
I'm using a simple email shortcut extension called Send Link by Email or Gmail.

Once installed just click on the extension icon and Gmail's Compose tool opens up

Now you can compose a mail as a Blog post. Now head over to your Blogger settings and setup publishing via email.

See image for reference. Send your composed email to the email you just set up. And voila. Now you can publish a post in just few clicks. Only drawback though is, you cannot set a category of your blog post.

13 January, 2020

How to upload your project to Github

So you're writing all kind of codes now and you want to collaborate with other developers in your team or just simply want to back up your precious code.

There are a number of ways to do it. You could simply just a make a zip out of your project and upload it to one of the cloud storage you got. Or you could do use something that is meant for storing codes. One such service is all popular Github.

I'll leave the explanation of Github for some other day and get into business right away.

What we want to do?
We want to upload our project to a repository on Github so that anyone else or just ourselves could download it later on, or sync with our different computers.

How?
Following steps will guide you through it.

Step 1. First we need a Github account.
Go sign up here https://github.com/ and come back for more.

Step 2. We need to setup our computer such that we don't have to provide our username password every time we sync our project.
This is done using Secure Server Host(SSH)
We generate a SSH key and pass it to Settings > SSH Keys > Add Key on Github.

Before we generate SSH key let's first check if we don't already have one. Download and install GitBash if not done already.

Enter

$ ls -al ~/.ssh

to list all the keys. Source: https://help.github.com/en/github/authenticating-to-github/checking-for-existing-ssh-keys

if you see any key listed like

$ github_rsa github_rsa.pub id_rsa  id_rsa.pub known_hosts

That means you already have a ssh key. If this is your case skip to next step.
If you don't have a key, let us generate one.

You'll need a program called SSH-Keygen or OpenSSH.
Once downloaded and installed open CMD and run the following command.

$ ssh-keygen -t rsa -b 4096 -C "[email protected]"

After this you'll see something like this

Generating public/private rsa key pair.
$ Enter file in which to save the key (/home/username/.ssh/id_rsa):[Enter Name or leave blank]

You may enter a name for your SSH key or leave it blank for the default.
You may add a passphrase to this key if you want. I left it blank for a sake of easiness.

You'll see something like this after this step

Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
The key fingerprint is: /////something here/////
[email protected]

You've successfully generated you SSH key.
Source: https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Step 3. Now we need to copy this key and provide it to our Github Settings.
To copy your key run following command in CMD

$ pbcopy < ~/.ssh/id_rsa.pub

Where 'id_rsa.pub' is the name of the SSH key. In case you changed it in Step 2. you'll have to change it here as well.

Step 4. No head over to https://github.com/login
 Click on your profile picture on top-right and go to Settings.
 Under settings you'll find SSH and GPG keys, click that.
 Then in the next page that loads click "New SSH key" paste your key and save.

Step 5. Open Gitbash in the project folder you want to create a repository of.

> enter
$ git init

> enter
$ git all --all

> enter
$ git commit -m "Pushing to Git Repo"

Step 6. Now head over to Github and create a new repository.
https://github.com/new
Enter name of you repository, set private or public and click "Create Repository"
Copy the repository address and head back to GitBash we left in Step 5.

Step 7. We have our Git Repository address copied to our clipboard.

> enter
$ git remote add origin

> right click
$ git remote add origin [email protected]:userName/projectTitle.git

> enter
git push origin master

That's it. Now head over to your Github profile and check out your newly created repository.





09 January, 2020

How to make NodeJS MongoDB REST APIs for CRUD operations


We'll use NodeJS Express framework for developing the web-interaction part and Mongoose for saving data to MongoDB. We'll be saving just two details name, and email of a user. Since I'll be logging in users with their email id only which is validated by Facebook in Facebook Social Login.

Install NodeJS and make a folder where your application will run from. This folder is production NodeJS server equivalent on Windows PC.

Step 1: Having installed NodeJS now open Command Prompt Window in the folder.

Quick Shortcut > Open the folder and click and type 'CMD' or 'cmd' in address bar.

Step 2: Initialize the application with a package.json file.
Run following command in the command prompt window,
$ npm init

name: (userdb)
version:
description: enter description
entry point: server.js
test command:
git repository:
keywords:
author: Your Name
license: 

Check details and type 'yes' to proceed.

Now our package.json is initialized and can be found in our project folder.

Note that we defined the entry point of our application as server.js so we'll make a file with the name 'server.js' had we left that blank the default name would have been 'index.js'

Create new file next to package.json by the name 'server.js', leave it blank for now we'll come back to it later.

Step 3: Installing dependencies
Now we'll install support for Express, body-parser and Mongoose for application to use it.
Run folowing commands in CMD
$ npm install express body-parser mongoose --save

Using '--save' at the end saves all the dependencies in the package.json file.

Now if you'll take a look at our project folder you'll see another folder by the name 'node_modules'.

Now let us setup our web server by editing the 'server.js' we created in Step 2.

Step 3: Open 'server.js' and define the main entry point to our application.

server.js

const express = require('express');
const bodyParser = require('body-parser');

// constant app will represent our application
// since app is based on express
const app = express();

//parses requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}))

//parses requests of content-type -application/json
app.use(bodyParser.json())

//defining a route to our application
app.get('/', (req, res) => {
res.json({
"message": "Nothing here, try making some API request."
});
});

//listening to requests
app.listen(3000, () => {
console.log("Server running at port 3000!")
});

Here, Express is a web framework that we are using to build REST APIs and body-parser is a module that parses the requests and creates req.body object that we can use in out routes.

Then we define a route to our application that addresses get request to the naked url and responds with a message. We'll alter this message with more helpful data later.

Finally we listen on port 3000 for incoming connection requests.

Let's fire up out server by calling

$ node server.js

You may visit http://localhost:3000/ to check whether it is running or not.

Step 4: Now let us configure our database.
Let's create new folder 'config' in out apps root folder where we'll be keeping all our configuration information separate.
Inside the 'config' folder create a new file 'db.config.js' with following contents-

module.exports = {
url: 'mongodb://localhost:27017/db0'
}

Now to import this 'db.config.js' file in 'server.js' and use it with 'mongoose'

//database congiguration
const dbConfig = require('./config/db.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

//connection to database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log('Connected to database');
}).catch(err => {
console.log('database connection failed...');
process.exit();
});

Re-run the server to check if the database is being connected.

$ node server.js

To remove the deprecation warning
"(node:8076) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor."

Just add ', useUnifiedTopology: true' after 'useNewUrlParser: true' so our 'server.js' is now

server.js

const express = require('express');
const bodyParser = require('body-parser');

//database congiguration
const dbConfig = require('./config/db.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

//connection to database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true, useUnifiedTopology: true
}).then(() => {
console.log('Connected to database');
}).catch(err => {
console.log('database connection failed...');
process.exit();
});

// constant app will represent our application
// app is based on express
const app = express();

//parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}))

//parse requests of content-type -application/json
app.use(bodyParser.json())

//defining a route to our application
app.get('/', (req, res) => {
res.json({
"message": "Nothing here, try making some API request."
});
});

//listening to requests

app.listen(3000, () => {
console.log("Server running at port 3000!")
});

Re-run the server warning should be gone now.

Quick Tip: The MongoDB database we just created can be viewed using MongoDB Atlas Applcation and passing the address 'mongodb://localhost:27017/db0' which we defined in 'db.config.js' file.

Step 5: Now we have our NodeJS application running with database connected. To save data to our MongoDB we will define a structure that will be followed for the data. We call this model. You can define more that a single type of model.

Create a new folder in the root directory of our application as 'app' and another folder inside 'app' as 'models'. Inside 'models' create a file by the name 'user.model.js'
Now we define what our user's properties are. Inside 'user.model.js' enter content-

user.model.js

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
name: String,
email: String
}, {
timestamps: true
});

module.exports = mongoose.model('User', UserSchema);


Since I'll be logging and registering users using their Facebook login I defined only two string fields 'name' and 'email' which can be easily requested from Facebook login.

Also adding 'timestamps: true' will add two field 'createdAt' and 'updatedAt' which can be useful in their own way if required.

Step 6: Now we will define various routes for the APIs.
Create a new folder inside 'app' by the name 'routes'. Inside this folder we'll create a file 'user.route.js' with the content-

user.route.js

module.exports = (app) => {
var controller = "../controllers/user.controller.js";
const users = require(controller);

//create a new user
app.post('/registeruser', users.create);

//get all users' information
app.get('/allusers', users.listAll);

//get single user with userId
app.get('/users/:userId', users.findOne);

//update a user with userId
app.put('/users/:userId', users.update);

//delete a User with userId
app.delete('/users/:userId', users.delete);

}

Note that we have defined a variable controller which points to an address of 'user.controller.js' file which we will define in next step.
Before that let's first include 'user.route.js' in our 'server.js' file.
Add the following lines of code before 'app.listen()' method inside 'server.js'

//require Users routes
require('./app/routes/user.route.js')(app);


Step 7: Now let's define our 'user.controller.js' that our 'user.route.js' depends on.
Create a new folder by the name 'controllers' inside 'app' folder. Inside this create a new file 'user.controller.js' with following contents.

user.controller.js

const User = require('../models/user.model.js');

//register a new user
exports.create = (req, res) => {

};

//get all users' data
exports.listAll = (req, res) => {

};

//find single user with userId
exports.findOne = (req, res) => {

};

//update a user's information base on userId
exports.update = (req, res) => {

};

//delete user with userId
exports.delete = (req, res) => {

};

Now we will implement these individual methods

For registering a new user

//register a new user
exports.create = (req, res) => {

//validate the request
if (!req.body.email) {
return res.status(400).send({
message: "User email id cannot be empty"
});
}

//register a user
const user = new User({
name: req.body.name || "not defined",
email: req.body.email
});

//save the user information in database
user.save().then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Something went wrong while registering new user.."
});
});
};


For getting all users' data

//get all users' data
exports.listAll = (req, res) => {
User.find().then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Something went wrong while getting all information"
});
});
};

For getting single user's information

//find single user with userId
exports.findOne = (req, res) => {
User.findById(req.params.userId).then(user => {
if (!user) {
return res.status(404).send({
message: "user not found with id " + req.params.userId
});
}
res.send(user);
}).catch(err => {
if (err.kind === 'ObjectId') {
return res.status(404).send({
message: "User not found with id " + req.params.userId
});
}
return res.status(500).send({
message: "Error getting user data with userId: " + req.params.userId
});
});

};

Updating a user's information

//update a user's information base on userId
exports.update = (req, res) => {
//validate request
if (!req.body.email) {
return res.status(400).send({
message: "Email ID cannot be left blank"
});
}
//find user by userId and update its name and email
User.findByIdAndUpdate(req.params.userId, {
name: req.body.name || "not defined",
email: req.body.email
}, {
new: true
}).then(user => {
if (!user) {
return res.status(404).send({
message: "User not found with userId " + req.params.userId
});
}
res.send(user);
}).catch(err => {
if (!user) {
return res.status(404).send({
message: "Error updating user with id " + req.params.userId
});
}
return res.status(500).send({
message: "Error updating user with id " + req.params.userId
});
});
};


Deleting a user based on userId

//delete user with userId
exports.delete = (req, res) => {
User.findByIdAndRemove(req.params.userId).then(user => {
if (!user) {
return res.status(404).send({
message: "User not found with id " + req.params.userId
});
}
res.send({
message: "User deleted successfully!"
}).catch(err => {
if (err.kind === 'ObjectId' || err.name === 'Not Found') {
return res.status(404).send({
message: "User not found with id " + req.params.userId
});
}
return res.status(500).send({
message: "Could not delete user with id " + req.params.userId
});
});
});


In order to test you API you can use Postman. Screenshot attached below for registering a new user.



http://localhost:3000/allusers will retrieve all the data from database.

In the next part I'll be making a login and registering pages and push the database and server to production.

You can find the whole project on GitHub
https://github.com/ixabhay/ludoDB
This also contains lots of content that is up there in the post including a way to register a user and check their information for login.
Hope it helps.