Tuesday, December 8, 2015

Difference Between ViewData, ViewBag and TempData with Example

Introduction:
In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session. Now question is that when to use ViewData, VieBag, TempData and Session. Each of them has its own importance. This article explains the differences among ViewData, ViewBag and TempData.

Difference Between ViewData, ViewBag and TempData with Example


ViewData

    1- ViewData is used to pass data from controller to view
    2- It is derived from ViewDataDictionary class
    3- It is available for the current request only
    4- Requires typecasting for complex data type and checks for null values to avoid error
    5- If redirection occurs, then its value becomes null

Example:- 
In controller

public ActionResult Index()
{
    ViewData["Name"] = "Vepsh Tech";
    return View();
} 

In View

@ViewData["Name"]


ViewBag

    ViewBag is also used to pass data from the controller to the respective view
    ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
    It is also available for the current request only
    If redirection occurs, then its value becomes null
    Doesn’t require typecasting for complex data type

Example:-
In Controller 

public ActionResult Index()
{
    ViewBag.Name = "Vepsh Tech";
    return View();
}

In View

@ViewBag.Name 

TempData

    1- TempData is derived from TempDataDictionary class
    2- TempData is used to pass data from the current request to the next request
    3- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
    4- It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages

Example:-

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
}

Monday, December 7, 2015

Understanding jQuery Ajax - to async or not ?

Introduction:
This article explains a clear understanding on making synchronous and asynchronous ajax calls through jQuery ajax method. After going through it you can have a clear idea on how and when to do asynchronous ajax calls.

Ajax(Asynchronous Javascript + XML) is a new approach now a days very popular in web development.
Ajax taken our classic web development to a different level. It is a new approach to create
fast and dynamic web pages.It toally removed the reloading part from the classical web development.

There are many Ajax methods provided by jQuery library to accomplish ajax calls as listed below :-
get
post
getScript
getJSON
ajax

These all ajax methods can be used as per requirements you are having but, if you need extensive configurability and want to handle errors by yourself then '.ajax()' method is the best.

To work with the jQuery ajax method we need to set the options available for it properly, from which
'async' is an important setting about which we are going to discuss here as setting its value will have a major impact in getting response properly.

As async is an boolean property, we can set either TRUE or FALSE value for it.
Here i will explain various scenarios on setting each values for the particular property(async) and to help you understanding its importance and usability by situation.

Example:
Here i am explaining simple examples how and when to make your choice in between asynchronous or synchronous ajax calls using jQuery.

Both methods independent of each other :-

There will be no impact on result if both are independent whether it is a asynchronous or synchronous ajax calls :-

$(function () {
    // When both the method are independent & async=false
    // Ajax call will happen one by one
    GetData1(false); // called first
    GetData2(false); // called after GetData1 method processing finished

    // When both the method are independent & async=true
    // Call will happen simultaneously
    GetData1(true); // Both are called simultaneously in different threads
    GetData2(true); // Both are called simultaneously in different threads
});

First Method:-

function GetData1(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData1",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second Method:-


function GetData2(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData2",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second method dependent on first one :-

But when second method is dependent on result supplied from first method it will definitely have impact

$(function(){
// When second method depends on result of the first method & async=false
// If it is a synchronous call then you can get 
the result from first method before the second method call
    var result = GetData3(false); 
// As second method will be called after first method execution completed 
// so proper result can be found in above method
    GetData4(false, result);

// When second method depends on result of the first method & async=true
// If it is an asynchronous call then both the calls will 
happen asynchrously/simultaneously and 
    // you will not get the result from first method before call of 
second method as happens in below example
    var result = GetData3(true); 
// As both the methods will be called simultaneously second method will be called 
// before first method returning the result and here it will get NULL value in result.
    GetData4(true, result);
});

First Method:-

function GetData3(isAsync) {
    var result = null;
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData3",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
    return result;
}

Second Method : Takes an extra argument which is the result of first method.

function GetData4(isAsync, result) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData4",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            if (result.id == 1) {
                var result = JSON.parse(response.d);
                // do your operation here
            }
            else alert('No operation required..');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Note-

This will definitely of help to the developers who started working on jQuery Ajax method. There are many scenarios and requirements, we need to understand the fundamentals so that we can make right choice one at right place.

How to find second highest or maximum salary of Employee in SQL - Interview question

Introduction:
In this section we will write SQL query to get second highest salary of Employee. Before writing query its good to be familiar with schema as well as data in table. Here is the Employee table we will be using this SQL example:

SQL query to find second maximum salary of Employee

How to find second highest or maximum salary of Employee in SQL - Interview question
If you look data, you will find that second maximum salary in this case is 6000 and employee name is Henry. Now let’s see some SQL example to find out this second maximum salary.

Second maximum salary using sub query and IN clause:
Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and then another maximum excluding result of subquery.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is another SQL query to find second highest salary using subquery and < operator instead of IN clause:
How to find second highest or maximum salary of Employee in SQL - Interview question
Both of above SQL example will work on all database including Oracle, MySQL, Sybase and SQL Server as they are written using standard SQL keywords. But sometime you can also use database specific features like TOP keyword of SQL Server or Sybase database to find out second highest salary of Employee.

Second highest salary using TOP keyword of Sybase or SQL Server database:
TOP keyword of Sybase and SQL Server database is used to select top record or row of any result set, by carefully using TOP keyword you can find out second maximum or Nth maximum salary as shown below.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is what this SQL query is doing : First find out top 2 salary from Employee  table and list them in descending order, Now second highest salary of employee is at top so just take that value. Though you need to keep in mind of using distinct keyword if there are more than one employee with top salary, because in that case same salary will be repeated and TOP 2 may list same salary twice.

Second maximum salary using LIMIT keyword of MYSQL database:
LIMIT keyword of MySQL database is little bit similar with TOP keyword of SQL Server database and allows to take only certain rows from result set. If you look at below SQL example, its very much similar to SQL Server TOP keyword example.
How to find second highest or maximum salary of Employee in SQL - Interview question
That’s on How to find second highest salary of Employee using SQL query.



Friday, December 4, 2015

Basic SQL Query that Frequently asked in Interview Questions

Introduction:
In this article, I am giving some examples of SQL queries which is frequently asked when you go for a programming interview, having one or two year experience on this field.

These queries test your SQL skill on Joins, both INNER and OUTER join, filtering records by using WHERE and HAVING clause, grouping records using GROUP BY clause, calculating sum, average and counting records using aggregate function like AVG(), SUM() and COUNT(), searching records using wildcards in LIKE operator, searching records in a bound using BETWEEN and IN clause, DATE and TIME queries etc. If you have faced any interesting SQL query or you have any problem and searching for the solution, you can post it here for everyone's benefit.

SQL Query Interview Questions and Answers

Question 1: SQL Query to find second highest salary of Employee
Answer: There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery:

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Emp

Question 2: SQL Query to find Max Salary from each department.
Answer: You can find the maximum salary for each department by grouping all records by DeptId and then using MAX() function to calculate maximum salary in each group or each department.

SELECT DeptID, MAX(Salary) FROM Employee  GROUP BY DeptID.

These questions become more interesting if Interviewer will ask you to print department name instead of department id, in that case, you need to join Employee table with Department using foreign key DeptID, make sure you do LEFT or RIGHT OUTER JOIN to include departments without any employee as well.  Here is the query

SELECT DeptName, MAX(Salary) FROM Employee e 
RIGHT JOIN Department d ON e.DeptId = d.DeptID GROUP BY DeptName;

In this query, we have used RIGHT OUTER JOIN because we need the name of the department from Department table which is on the right side of JOIN clause, even if there is no reference of dept_id on Employee table.

Question 3: Write SQL Query to display the current date.
Answer: SQL has built-in function called GetDate() which returns the current timestamp. This will work in Microsoft SQL Server, other vendors like Oracle and MySQL also has equivalent functions.

SELECT GetDate();

Question 4: Write an SQL Query to check whether date passed to Query is the date of given format or not.
Answer: SQL has IsDate() function which is used to check passed value is a date or not of specified format, it returns 1(true) or 0(false) accordingly. Remember ISDATE() is an MSSQL function and it may not work on Oracle, MySQL or any other database but there would be something similar.

SELECT  ISDATE('1/08/13') AS "MM/DD/YY"; 

It will return 0 because passed date is not in correct format. 

Question 5: Write an SQL Query to print the name of the distinct employee whose DOB is between 01/01/1960 to 31/12/1975.
Answer: This SQL query is tricky, but you can use BETWEEN clause to get all records whose date fall between two dates.

SELECT DISTINCT EmpName FROM Employees 
WHERE DOB  BETWEEN 01/01/1960 AND 31/12/1975;

Question 6: Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to 31/12/1975.
Answer :

SELECT COUNT(*), sex from Employees  
WHERE  DOB BETWEEN '01/01/1960' AND '31/12/1975' GROUP BY sex;

Question 7: Write an SQL Query to find an employee whose Salary is equal or greater than 10000.
Answer :

SELECT EmpName FROM  Employees WHERE  Salary>=10000;

Question 8: Write an SQL Query to find name of employee whose name Start with ‘M’
Answer :

SELECT * FROM Employees WHERE EmpName like 'M%';

Question 9: find all Employee records containing the word "Joe", regardless of whether it was stored as JOE, Joe, or joe.
Answer :

SELECT * from Employees  WHERE  UPPER(EmpName) like '%JOE%';

Question 10: Write an SQL Query to find  the year from date.
Answer:  Here is how you can find Year from a Date in SQL Server 2008

SELECT YEAR(GETDATE()) as "Year";





Wednesday, December 2, 2015

Is MVC a design pattern or an architectural pattern?

Is MVC a design pattern or an architectural pattern?
Introduction:
MVC which stands for Model-View-Controller describes a software pattern that you can use in interactive computer systems. To understand if it is a design pattern or an architectural pattern, let's look at what these two are:

Architectural pattern: Concerned with the subsystems of an application with their relationships and collaborations with each other.
Design pattern: Concerned with the (further small) components of a subsystem with their relationships and collaborations with each other.

MVC is a pattern that you can use in both ways (as architectural or design) and ample amounts of real world cases where the pattern is used in both these worlds can be found.

MVC as an architectural pattern
Here the core functionality and data of an application are abstracted as the model. You have one or more views and one or more controllers collectively representing the user interface. A view is responsible for displaying information to the user. A controller is responsible for accepting user inputs, interpret them to understand what should be done and act accordingly (for example update data or invoke a functionality of the model).

A real world example is the implementation of a web application that follows the MVC architectural pattern. Many such web application frameworks exists. The key is that an application is broken down into components (call them subsystems) by the MVC pattern.

MVC as an architectural pattern
MVC architectural of a web application

MVC as a design pattern
Consider the many UI widget libraries available out there where MVC is used as a design pattern to implement widgets. Take for example the JSlider class (in Java Swing library). A JSlider instance represents a slider widget where a user can move the knob of the slider to change its position. JSlider is implemented as follows:

MVC as a design pattern
MVC design pattern

Note that in Java Swing library the xxxUI classes capture both the view and controller aspects of a widget. It's slightly different from MVC and Swing creators call this “separable model architecture”. For the purpose of this discussion, just don't care about this difference.

Here the model (BoundedRangeModel) doesn't represent the core functionality or data of the application. It's limited to represent the data (state) of the slider widget (Models of complex widgets may implement some amount of model specific functionality.). SliderUI's view related code is responsible for painting the slider (the background, knob,...). SliderUI's controller is responsible for interpreting a mouse click-and-drag as a semantic event that represents a slider position change. Accordingly the controller related code goes about updating the model. And then the view goes about painting the knob at a different position.

The scope of the MVC pattern here is just limited to implementing a slider widget. Would you call it architectural? I would not since I cannot consider the slider a collection of subsystems of an application. With the frame or reference set to a typical application, you wouldn't even recognize it as a top level subsystem. It's more appropriate to consider it a low level subsystem or a component and hence the MVC manifests as a design pattern in this context (Read initial paragraphs - What is considered a design pattern?).

Confusion:
Why is that the Swing creators gave the name “separable model architecture” to their widget design pattern? Probably because what is considered architectural itself is a question that leads to multiple explanations.

One such explanation is that if something (a quality, design aspect,.. ) is found spread throughout a system, it's considered architectural. That's a different way to think about architecture which is not the same as what I mentioned at the beginning of this article (See the description of a architectural pattern). Probably that's one reason why Swing creators used “architecture” in their pattern since it's found throughout the Swing library.

Yet another reason that I can think of is that they just focused on the UI “system”.

Fair  enough. Let's not argue. We understand what is what. Based on the first given description, this widget design pattern cannot be considered an architectural pattern.

Conclusion:

MVC can either be used as an architectural pattern or a design pattern.

Thursday, August 27, 2015

Read and Parse JSON String using ParseJSON Method with jQuery

Read and Parse JSON String using ParseJSON Method with jQuery
Introduction:
This article explains how to read and Parse JSON string in jQuery using ParseJSON method in JavaScript, asp.net and get string value from JSON string in jQuery.

To implement this functionality we need to write the code like as shown below

HTML Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Read and Parse Data using ParseJSON method</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
var name = '';
var jsonstr = '[{"UserName":"Ashwani","UserID":"1"},{"UserName":"VepshTech","UserID":"2"}]';
var obj = $.parseJSON(jsonstr);
$.each(obj, function() {
name += this['UserName'] + "<br/>";
});
$('#divjson').html(name); ;
})
</script>
</head>
<body>
<div id="divjson">
</div>
</body>
</html>

In above code we used parseJSON method to read formatted JSON string

Output:

Read and Parse JSON String using ParseJSON Method with jQuery


Convert JSON String to JSON Object with JavaScript

Introduction:
This article explains
This article explains how to convert JSON string to JSON object in JavaScript. To convert JSON string to JSON object in JavaScript we need to write the code as shown below.




Code-

 var str = '[{"title":"Chennai","lat":12.897400},
{"title":"Hyderabad","lat":17.266700},{"title":"Bangalore","lat":12.897400}]';
var obj=JSON.parse(str);

By using above code we can convert JSON string to JSON object in JavaScript

jQuery Convert JSON Data to HTML Table using jQuery Row Append Properties

Introduction:
This article explains how to convert JSON data to html table using jQuery or convert JSON data into html table using jQuery or jQuery convert JSON data into html table or jQuery create html table using JSON data.

To convert JSON data to html table using jQuery we need to write the code like as shown below


HTML Code-

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>convert json data to html table using jquery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
var myList = [{ "Name": "Ashwani", "Education": "B.Tech", "Location": "Lucknow" },
{ "Name": "Vin", "Education": "BMSC", "Location": "Guntur" },
{ "Name": "Ash", "Education": "Msc", "Location": "Nagpur" },
{ "Name": "Tom", "Education": "MBBS", "Location": "Nagpur" },
{ "Name": "Jack", "Education": "B.Tech", "Location": "Kakinada" },
{ "Name": "Mack", "Education": "MD", "Location": "Vizag" },
{ "Name": "Anu", "Education": "B.Tech", "Location": "Delhi" }]
Bindhtmltable(myList);
})
function Bindhtmltable(list) {
var cols = addheadercols(list);
for (var i = 0; i < list.length; i++) {
var row = $('<tr/>');
for (var colIndex = 0; colIndex < cols.length; colIndex++) {
var cellValue = list[i][cols[colIndex]];
if (cellValue == null) { cellValue = ""; }
row.append($('<td/>').html(cellValue));
}
$("#htmltable").append(row);
}
}

function addheadercols(list) {
var colset = [];
var headerTr = $('<tr/>');
for (var i = 0; i < list.length; i++) {
var rows = list[i];
for (var key in rows) {
if ($.inArray(key, colset) == -1) {
colset.push(key);
headerTr.append($('<th/>').html(key));
}
}
}
$("#htmltable").append(headerTr);
return colset;
}
</script>
</head>
<body>
<form id="form1" >
<div>
<table id="htmltable" border="1" cellpadding="5" style="border-collapse: collapse;">
</table>
</div>
</form>
</body>
</html>

Output-
Check below table it’s build by using above JSON data

Filter JSON Object to Show / Hide / Update Elements based on Conditions in Angularjs

Introduction:
This article explains how to use AngularJS to filter JSON object to show or hide or update elements with example or AngularJS filter json object in controller with example. By using filter option in ng-repeat we can enable/disable or show/hide required elements from JSON object.

To show or hide values based on JSON object in AngularJS we need to write the code like as shown below

 $scope.checkvalues = function (user) {
return user.id != "5";
}

If you want to check it in complete example you need to write the code like as shown below

HTML Code-

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>angularjs filter json object to show/hide or update elements</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js">
</script>
<script type="text/javascript">
var app = angular.module('sampleapp', [])
app.controller('samplecontrol', function ($scope) {
$scope.sample = [{
id: '1',
name: 'Vepsh Tecck'
}, {
id: '2',
name: 'India'
}, {
id: '3',
name: 'UK'
}, {
id: '4',
name: 'USA'
}, {
id: '5',
name: 'China'
}, {
id: '6',
name: 'Rusia'
}];

$scope.checkvalues = function (user) {
return user.id != "5";
}
});
</script>
</head>
<body data-ng-app="sampleapp" data-ng-controller="samplecontrol">
<form id="form1">
<div ng-repeat="user in sample | filter:checkvalues">
{{user.name}} <br/>
</div>
</form>
</body>
</html>

Output-

If you check below output it will display all values except id = 5

How to change maxJsonLength property in web.config

How to change maxJsonLength property in web.config
Introduction:
This article explains how to solve the problem of “Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.” in asp.net using c#.

Generally this problem occur whenever our json result set length exceeds default json MaxJsonLength property value. By default MaxJsonLength property will allow 102400 (100k) in case our string exceeding this length we will get JavaScriptSerializer error.

To solve this problem we need to set MaxJsonLength property value in web.config file like as shown below

<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="3000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>

Once we add above code snippet in web.config file automatically our problem will get solve.

Wednesday, August 26, 2015

CSS Font Properties with HTML

Font Size
In CSS, Font size is given using property "Font-size". We can give value of Font-size using 4 different units.
  • Pixels (px)
  • Em(em)
  • Points (pt)
  • percentage (%)
Others units are pc (picas), cm (centimetres), mm (millimetres) and in (inches).
For a p tag,
16px= 1em=100%=12pt

HTML Code-

<p style="font-size:16px"> Font size 16px </p>

<p style="font-size:1em"> Font size 1em </p>

<p style="font-size:12pt"> Font size 12pt </p>

<p style="font-size:100%"> Font size 100% </p>

Output-
Font size 16px
Font size 1em
Font size 12pt
Font size 100%

Font Weight
In CSS, Font weight is used to create a text Bold. Various value of font-weight are
  • Bold
  • Bolder
  • Normal
  • Value between 100-900
Basiclly we use only Bold and Normal as other browsers does'nt make any difference between and understand bold and normal.

HTML Code-

<p style="font-weight:bold"> Font weight bold </p>

<p style="font-weight:bolder"> Font weight bolder  </p>

<p style="font-weight:normal"> Font weight normal </p>

<p style="font-weight:100"> Font weight 100 </p>

<p style="font-weight:500"> Font weight 500 </p>

<p style="font-weight:900"> Font weight 900 </p>

Output-
Font weight bold
Font weight bolder
Font weight normal
Font weight 100
Font weight 500
Font weight 900

Font Style
In CSS, Font style is used to create a text italic. Various value of font-style are
  • Italic
  • Normal
HTML Code-

<p style="font-style:normal"> Font style normal </p>

<p style="font-style:italic"> Font style italic </p>

Output-
Font style normal
Font style italic

Font Family
In CSS, Font family specify the font we are using. It can be
  • Arial
  • helvetica
  • Times new roman
  • Georgia
  • Serif
We can also write two different font together. This tell the browser that if one font is unavailable, use another one.

HTML Code-

<p style="font-family:arial"> Font family Arial  </p>

<p style="font-family:helvetica"> Font family Helvetica  </p>

<p style="font-family:"times new roman""> Font family Roman </p>

<p style="font-family:georgia"> Font family Georgia </p>

<p style="font-family:arial, helvetica "> Font family Arial and helvetica </p>

Output-
Font family Arial
Font family Helvetica
Font family Roman
Font family Georgia
Font family Arial and helvetica

HTML & CSS Color Code

CSS HTML Color
In CSS, font color is given by using css "color" Property.
The value of color is written in these three forms.
  • Color Name
  • Hexadecimal Color code
  • RGB Colors
Color Name
CSS include total 16,777,216 ( 1 Crore 67 Lakhs ) colours. However 17 colors are known by their by name. These colors are
aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow. Transparent is also a valid value. 

HTML Code-

<p style="color:red"> Color Red </p>
<p style="color:blue"> Color Blue </p>
<p style="color:green"> Color Green </p>
<p style="color:yellow"> Color Yellow </p> 

Output-
Color Red
Color Blue
Color Green
Color Yellow

Hexadecimal Color Code
We can also write color's value using HEXADECIMAL COLOR CODES.
Hexadecimal is basicly a 16 base number system where we use 16 different value and combine them to write a color.
In Hexadecimal color coding, our use: 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f.
Minimun value is 0, and maximum is f.
Way to write a color in Hexadecimal Color Code: #------;
There are total six digits. First two represent red, next two represents green and last two blue.
Black #000000;
White #ffffff;
Red #ff0000;
Green #00ff00;
Blue #0000ff;
Rest all color are mixture of above values;

HTML Code-

<p style="color:#ff0000"> Color Red </p>
<p style="color:#0000ff"> Color Blue </p>
<p style="color:#00ff00"> Color Green </p>
<p style="color:#000000"> Color Black </p>

Output-
Color Red
Color Blue
Color Green
Color Black

RGB Color Code
We can also write a color value using RGB( Red, Green, Blue) color value.
In RGB, we write a color using its value which lies in-between 0 and 255.
0 is minimum value and 255 is maximum.

HTML Code-

<p style="color:rgb(255,0,0)"> Color Red </p>
<p style="color:rgb(0,255,0)"> Color Green </p>
<p style="color:rgb(0,0,255)"> Color Blue </p>

Output-
Color Red
Color Green
Color Blue