Feeds:
Posts
Comments

datagridExample

 

Step – 1 : Create Datagrid Paging Component.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:HBox xmlns:fx=”http://ns.adobe.com/mxml/2009&#8243;
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
width=”100%” creationComplete=”onCreationComplete(event)”>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.DataGrid;
import mx.events.FlexEvent;

//———————— Private Variable ———————————–

private var originalArrayCollection:ArrayCollection;

/* Records per page */

private var currentPageIndex:uint;
private var navPage:uint;

[Bindable]
private var numberOfRecordsPerPage:uint = 10;
[Bindable]
private var totalPages:uint;
[Bindable]
private var totalRecords:uint;
[Bindable]
private var currentPage:uint;
[Bindable]
private var dgRowHeight:int = 25;

//———————— Public Variable ————————————

[Bindable]
public var myDataDataProviderData:ArrayCollection;
[Bindable]
public var dataGridforPaging:DataGrid;

//————————– Functions —————————————-

public function setDataGridValuesForPaging():void{
totalPages = 1;
totalRecords = 0;
currentPageIndex = 0;
navPage = 1;
numberOfRecordsPerPage = (dataGridforPaging.height/dataGridforPaging.rowHeight)-1;

btnFirstPage.enabled = false;
btnPreviousPage.enabled = false;

originalArrayCollection = dataGridforPaging.dataProvider as ArrayCollection;
myDataDataProviderData = originalArrayCollection;

if(originalArrayCollection.length > 0){
calculatePageStatistics();
}

refreshDataProvider(currentPageIndex);
pagenavigation();
}

/**
* Calculate And Set Page Statistics.
*/
private function calculatePageStatistics():void
{
/* Calculate number of pages according to number of records per page */
totalPages = Math.ceil(originalArrayCollection.length / numberOfRecordsPerPage);
if (totalPages <= 1)
{
btnNextPage.enabled = false;
btnLastPage.enabled = false;
}
else
{
btnNextPage.enabled = true;
btnLastPage.enabled = true;
}
/** Calculate Total Records */
totalRecords = originalArrayCollection.length;

/** Current Page */
if (totalRecords > 0) {
currentPage = currentPageIndex + 1;
}
else {
currentPage = 0;
}
}

/**
* Refresh dataprovider of current datagrid.
*/
private function refreshDataProvider(currentPageIndex:uint):void{
myDataDataProviderData = new ArrayCollection(originalArrayCollection.source.slice((currentPageIndex * numberOfRecordsPerPage), (currentPageIndex * numberOfRecordsPerPage) + numberOfRecordsPerPage));
dataGridforPaging.dataProvider = myDataDataProviderData;
}

private function pagenavigation():void{
if (totalPages <= 1 && currentPage <= 1){
btnFirstPage.enabled = false;
btnPreviousPage.enabled = false;
btnNextPage.enabled = false;
btnLastPage.enabled = false;
}else if(currentPage <= 1 && totalPages != 1){
btnFirstPage.enabled = false;
btnPreviousPage.enabled = false;
btnNextPage.enabled = true;
btnLastPage.enabled = true;
}else if((currentPage == totalPages) && (currentPage != 1)){
btnFirstPage.enabled = true;
btnPreviousPage.enabled = true;
btnNextPage.enabled = false;
btnLastPage.enabled = false;
}else{
btnFirstPage.enabled = true;
btnPreviousPage.enabled = true;
btnNextPage.enabled = true;
btnLastPage.enabled = true;
}
}

//———————— Event Handlers ————————————-

private function onCreationComplete(event:FlexEvent):void{
setDataGridValuesForPaging();
}

/** First Page Button Click */
private function firstPageButtonclick(event:MouseEvent):void
{
currentPageIndex = 0;
refreshDataProvider(currentPageIndex);
currentPage = currentPageIndex + 1;

btnFirstPage.enabled = false;
btnPreviousPage.enabled = false;
btnNextPage.enabled = true;
btnLastPage.enabled = true;
}

/** Next Page Button Click Handler */
private function nextPageButtonclick(event:MouseEvent):void
{
if (currentPage + 1 <= totalPages)
{
btnFirstPage.enabled = true;
btnPreviousPage.enabled = true;
currentPageIndex = currentPageIndex + 1;
refreshDataProvider(currentPageIndex);
currentPage = currentPageIndex + 1;

if (currentPage == totalPages){
btnNextPage.enabled = false;
btnLastPage.enabled = false;
}
}
else
{
btnNextPage.enabled = false;
btnLastPage.enabled = false;
}
}

/** Previous Page Button Click Handler */
private function previousPageButtonclick(event:MouseEvent):void
{
if (currentPage – 1 >= 1)
{
btnNextPage.enabled = true;
btnLastPage.enabled = true;
currentPageIndex = currentPageIndex – 1;
refreshDataProvider(currentPageIndex);
currentPage = currentPageIndex + 1;
if (currentPage == 1){
btnFirstPage.enabled = false;
btnPreviousPage.enabled = false;
}
}
else
{
btnFirstPage.enabled = false;
btnPreviousPage.enabled = false;
}
}

/** Last Page Button Click */
private function lastPageButtonclick(event:MouseEvent):void
{
currentPageIndex = totalPages – 1;
refreshDataProvider(currentPageIndex);
currentPage = currentPageIndex + 1;

btnFirstPage.enabled = true;
btnPreviousPage.enabled = true;
btnNextPage.enabled = false;
btnLastPage.enabled = false;
}

private function onNumberOfRecordsPerPage(event:Event):void{
var recordIndex:int = (numberOfRecordsPerPage * currentPageIndex);

numberOfRecordsPerPage = Number(txtRecordsPerPage.text);

if(numberOfRecordsPerPage > originalArrayCollection.length){
numberOfRecordsPerPage = originalArrayCollection.length;
txtRecordsPerPage.text = numberOfRecordsPerPage.toString();
}

if((numberOfRecordsPerPage <= 0) && (originalArrayCollection.length > 0)){
numberOfRecordsPerPage = 1;
txtRecordsPerPage.text = numberOfRecordsPerPage.toString();
}

currentPageIndex = (recordIndex/numberOfRecordsPerPage);
refreshDataProvider(currentPageIndex);
calculatePageStatistics();
pagenavigation();
}

private function onNavigatePageChange(event:Event):void{
currentPage = Number(txtNavigatePage.text);

if(currentPage > totalPages){
currentPage = totalPages;
}

if(currentPage < 1){
currentPage = 1;
}

if (totalRecords > 0) {
switch(currentPage){
case (currentPage <= 1):
currentPageIndex = 0;
refreshDataProvider(currentPageIndex);
currentPage = currentPageIndex + 1;
pagenavigation();
break;
case (currentPage >= totalPages):
currentPageIndex = totalPages – 1;
refreshDataProvider(currentPageIndex);
currentPage = currentPageIndex + 1;
pagenavigation();
break;
default:
currentPageIndex = currentPage – 1;
refreshDataProvider(currentPageIndex);
pagenavigation();
break;
}
}
else {
currentPage = 0;
pagenavigation();
}
}
]]>
</fx:Script>
<mx:HBox horizontalAlign=”right”
paddingRight=”5″
width=”100%” verticalAlign=”middle”>
<mx:HBox>
<mx:LinkButton id=”btnFirstPage”
label=”&lt;&lt; First”
fontWeight=”bold”
fontSize=”11″
click=”firstPageButtonclick(event)”
enabled=”false” />
<mx:LinkButton id=”btnPreviousPage”
label=”&lt; Prev”
fontWeight=”bold”
fontSize=”11″
click=”previousPageButtonclick(event)”
enabled=”false” />
<mx:LinkButton id=”btnNextPage”
label=”Next &gt;”
fontWeight=”bold”
fontSize=”11″
click=”nextPageButtonclick(event)”
enabled=”false” />
<mx:LinkButton id=”btnLastPage”
label=”Last &gt;&gt;”
fontWeight=”bold”
fontSize=”11″
click=”lastPageButtonclick(event)”
enabled=”false” />
</mx:HBox>
<mx:VRule height=”20″ />
<s:Label text=”Page:”
verticalAlign=”middle”
height=”100%”
fontWeight=”bold”
fontSize=”11″ />
<s:TextInput id=”txtNavigatePage” width=”35″ textAlign=”left” text=”{currentPage}” restrict=”0-9″ keyDown=”onNavigatePageChange(event)” change=”onNavigatePageChange(event)” />
<s:Label id=”lblTotalPage”
text=”of {totalPages==0?1:totalPages}”
verticalAlign=”middle”
height=”100%”
fontWeight=”bold”
fontSize=”11″ />
<mx:VRule height=”20″/>
<s:Label id=”lblTotalItems”
text=”Total : {totalRecords}”
verticalAlign=”middle”
height=”100%”
fontWeight=”bold”
fontSize=”11″ />
</mx:HBox>
<mx:VRule height=”20″/>
<s:Label text=”Records/Page: ” verticalAlign=”middle” paddingTop=”5″ fontWeight=”bold”/>
<s:TextInput id=”txtRecordsPerPage” width=”35″ textAlign=”left” text=”{numberOfRecordsPerPage}” restrict=”0-9″ keyDown=”onNumberOfRecordsPerPage(event)” change=”onNumberOfRecordsPerPage(event)” />
</mx:HBox>

 

 

Step – 2  Use component in Application

 

<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009&#8243;
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:components=”components.*”
minWidth=”955″ minHeight=”600″ creationComplete=”onCreationComplete(event)”
viewSourceURL=”srcview/index.html”>
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<fx:Style>
@namespace s “library://ns.adobe.com/flex/spark”;
@namespace mx “library://ns.adobe.com/flex/mx”;
@namespace local “*”;

mx|DataGrid{
headerColors:#7ab8ef,#c6fdff;
selectionColor:#4385d9;
rollOverColor:#4385d9;
textRollOverColor:#ffffff;
textSelectedColor:#ffffff;
headerStyleName:headerStyle;
}

.headerStyle{
textAlign:center;
fontWeight:bold;
fontSize:13;
}

mx|LinkButton
{
upSkin:Embed(source=’assets/images/glass_btn_up.png’, scaleGridLeft=10, scaleGridRight=11, scaleGridTop=10,scaleGridBottom=11);
downSkin:Embed(source=’assets/images/glass_btn_over.png’, scaleGridLeft=10, scaleGridRight=11, scaleGridTop=10,scaleGridBottom=11);
overSkin:Embed(source=’assets/images/glass_btn_over.png’, scaleGridLeft=10, scaleGridRight=11, scaleGridTop=10,scaleGridBottom=11);
selectedUpSkin:Embed(source=’assets/images/glass_btn_over.png’, scaleGridLeft=10, scaleGridRight=11, scaleGridTop=10,scaleGridBottom=11);
selectedOverSkin:Embed(source=’assets/images/glass_btn_over.png’, scaleGridLeft=10, scaleGridRight=11, scaleGridTop=10,scaleGridBottom=11);
disabledSkin:Embed(source=’assets/images/glass_btn_disable.png’, scaleGridLeft=10, scaleGridRight=11, scaleGridTop=10,scaleGridBottom=11);
color:#000000;
textRollOverColor:#000000;
}
</fx:Style>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;

[Bindable]
private var arrcol:ArrayCollection = new ArrayCollection();

private function onCreationComplete(event:FlexEvent):void{
for (var i:int = 1; i < 501; i++) {
var obj:Object = new Object();

obj.name = “row” + i;
obj.address = “address” + i;
obj.city = “city” + i;
obj.active = (((i%3)== 0) ? true : false);
obj.special = (((i%3)== 0) ? false : true);
obj.systemid = “fs-922″ + i;

arrcol.addItem(obj);
}

arrcol.refresh();
testGrid.dataProvider = arrcol;

// call paging function for setting values according
// dataprovider change.
dataGridPaging.setDataGridValuesForPaging();
}

]]>
</fx:Script>

<s:Panel width=”100%” height=”500″ title=”Arcanum”
dropShadowVisible=”false”>
<mx:DataGrid id=”testGrid” width=”100%” height=”100%”
dataProvider=”{arrcol}”>
<mx:columns>
<mx:DataGridColumn headerText=”Name” width=”0.25″
dataField=”name” />
<mx:DataGridColumn headerText=”Address” width=”0.20″
dataField=”address” />
<mx:DataGridColumn headerText=”City” width=”0.18″
dataField=”city”/>
<mx:DataGridColumn headerText=”Active” width=”0.15″
dataField=”active” textAlign=”center” />
<mx:DataGridColumn headerText=”Spcial” width=”0.08″
dataField=”special” textAlign=”center” />
<mx:DataGridColumn headerText=”System Id” width=”0.16″
dataField=”systemid”/>
</mx:columns>
</mx:DataGrid>
<s:controlBarContent>
<components:DataGridPaging id=”dataGridPaging” width=”100%” height=”100%” dataGridforPaging=”{testGrid}” />
</s:controlBarContent>
</s:Panel>
</s:Application>

Advertisements

Virtualization Concepts

Basic fundamental concepts on virtualization from VMware vSphere Client help guide.

What is Virtualization ?

  • Virtualization is an abstraction layer that breaks hard connection between physical hardware and operating system.
  • A virtual infrastructure is an enterprise-wide solution that provides fluid,powerful computing that maximize resource utilization and cost savings.
  • Virtual machines are the key element to a virtual infrastructure.
  • Virtualization allows you to run multiple virtual machines with different operating systems and applications to run in isolation,side by side on the same physical machine.
  • Using virtualization , you can dynamically move resources where they are needed and processing where it makes more sense.

What is Virtual Machine ?

  • A virtual machine is a software computer that like a physical computer, runs an operating system and applications.
  • An operating system installed on a virtual machine is called a guest operating system.
  • Every virtual machine has virtual devices that provide the same functionality as physical hardware. Virtual machine gets CPU & memory,video cards,access to storage, and network connectivity from the hosts they run on.
  • Virtual machines run on hosts and clusters. Multiple virtual machines can run on the same host and cluster at the same time.
  • Virtual machines are not emulators or simulators. They are real machines that can do the same things physical computers can do and more. Because of the flexibility of virtual machines, physical computers become less a way to provide service (applications, database and so on) and more a way to house the virtual machines that provide those services.

Benefits of virtual machines

  • Physical machines are hard to move,difficult to copy and bound to a specific set of hardware. Virtual machines are easy to copy and move because they are independent of physical hardware.
  • Virtual machines are easy to manage because they are isolated from other virtual machines running on same physical hardware and insulated from physical-hardware changes.
  • Freedom from physical hardware constraints : virtual machines allow the operations of different operating system running across different hardware.
  • Backup and Recovery with little or no down-time : You can configure virtual machines with operating systems and applications once and then clone them many times. Backing up a virtual machine is as easy as backing up few files. In this way virtual machine ensures fast deployment and reliability.
  • Greater resource utilization :  Multiple virtual machines can run on the same physical server. In addition consolidating computing power to fewer physical computers can substantially increase power savings in your enterprise.

What is Host ?

  • A host is a computer that uses virtualization software such as ESX or ESXi to run virtual machines.
  • Host provides CPU & memory resources that virtual machines use, and give virtual machines access to storage and network connectivity.
  • You can add virtual machine to a host by creating a new one or deploying a virtual appliance.
  • A virtual appliance is a pre-built virtual machine  with an operating system and software already installed.

What is Datacenter ?

  • A datacenter is a primary container of inventory objects such as hosts and virtual machines.
  • From the datacenter, you can add and organize inventory objects. Typically, you add hosts,folders, and clusters to a datacenter.
  • The vCenter Server can contain multiple datacenters. Large companies might use multiple datacenters to represent organizational units in their enterprise.
  • Inventory objects can interact within datacenters,but interaction across datacenters are limited.For example, you can move virtual machine across hosts within a datacenter but not to host in another datacenter.

virtualappliance

What is Cluster ?

  • A cluster is a group of hosts that share resources and a management interface.
  • When you add a host to a cluster,the host’s resources become part of the cluster’s resources.
  • The cluster manages the resources of all hosts within it.
  • Cluster enable the vSphere Distributed Resource Scheduler (DRS) and vSphere High Availability (HA) solutions. vSphere DRS continuously balances virtual machine workloads across your ESX/ESXi hosts. vSphere HA allows the virtual machines running on ESX/ESXi hosts to automatically recover from host failures.

What is Resource Pool ?

  • A resource pool provides a way to divide the resources of a stand-alone host or a cluster into smaller pools.
  • A resource pool is configured with a set of CPU and memory resources that the virtual machines that run in resource pool share.
  • Resource pools are self contained and isolated from other resource pools.
  • You can combine multiple physical servers into a single resource pool that aggregates CPU and memory capacity.
  • Virtual machines execute in and draw their resources from resource pools.
  • This arrangement allows virtual machine workloads to continuously balance across resource pools. When the workload increases, the vCenter Server automatically allocates additional resources and transparently migrates virtual machines between hosts in the resource pool.

Using vSphere

  • vSphere is a software solution for deploying and managing virtual machines across a datacenter.
  • VMware vSphere is a system for managing virtual infrastructure.
  • VMware vCenter server is a tool that manages multiple host servers that run multiple virtual machines.
  • With vSphere, datacenters can instantly provision servers, globally manage resources and eliminate scheduled downtime for hardware maintenance.

virtual_architeracture

What is vCenter Server ?

  • VMware vCenter Server provides a convenient single point of control to the datacenter.
  • It runs on top of windows server to centrally manage your vmware ESX/ESXi hosts and provides essential datacenter services such as access control,performance monitoring and configuration.
  • vCenter server brings resources together from individual hosts to be shared among virtual machines in the entire datacenter.
  • It accomplishes this by managing the assignment of virtual machines to the hosts and the assignment of resources to the virtual machines within a given host based on the policies that the system administrator sets.
  • vCenter Server allows the use of advanced vSphere features such as vSphere DRS, vSphere HA, and vMotion.
  • With vCenter Server, we can quickly provision new server virtual machines and create a library of standardized virtual machine templates so your newly provisioned systems always conform to your datacenter requirements.
  • vCenter Server lets us migrate running virtual machines between host servers so that you can perform hardware maintainance with minimal downtime.
  • vCenter Server allows us to balance virtual machine workloads across hosts and manage virtual machines for high availability and disaster recovery.

What is vSphere Client ?

  • The vSphere Client is a primary interface for creating, managing and monitoring virtual machines,their resources and their hosts.
  • It also provides console access to virtual machines.
  • The vSphere Client is installed on a windows machine with network access to your vCenter Server or your ESX/ESXi host.
  • The interface displays different options depending on which type of server you are connected to.
  • Although vCenter Server performs all vSphere activities,you use the vSphere Client to monitor,manage and control vSphere server.
  • A single vCenter Server or ESX/ESXi host can support multiple,simulteneously connected vSphere Clients.

What is virtual hardware?

  • Just as a physical computer has hardware devices such as CPU and memory, a virtual machine has virtual hardware devices.
  • If we look at a virtual machine’s configuration, we find virtual CPU, memory, hard disks, CD/DVD drives, floppy drives,Ethernet adapters, sound cards, and so on.
  • Each virtual device performs the same function for the virtual machine as does the hardware on a physical computer.
  • Virtual hardware lets the virtual machine divide up the physical hardware as needed. For example, we can run many virtual machines on a single physical CPU, each appearing to have its own virtual CPU.
  • We can move a virtual machine from one host to another and the mappings between the virtual and physical devices change automatically, while the virtual devices remain unchanged.
  • Virtual hardware, virtual machines are insulated from the details of physical hardware.

Inventory views in vSphere Client

  • Inventory view provides views of all objects that the vCenter Server manages, such as datacenters, resource pools, clusters, networks, datastores, datastore clusters, templates, hosts and virtual machines.
  • The four inventory views are :
    • Hosts and Clusters : Displays the inventory hierarchy of all inventory objects except templates, networks, and datastores.
    • Virtual machines & Templates : Displays the list of virtual machines and templates.
    • Networks : Displays the list of networks.
    • Datastores & Datastore Clusters : Displays the list of datastores and datastore clusters.

Storage in vSphere

  • Every virtual machine uses a virtual hard disk to store its operating system, program files, and other data associated with its activities.
  • A virtual disk is a large physical file, or a set of files, that can be copied, moved, archived, and backed up as easily as any other file.
  • Virtual disk files are stored on dedicated storage space on a variety of physical storage systems, including internal and external devices of a host, or networked storage, dedicated to the specific tasks of storing and protecting data.
  • A host can discover storage devices to which it has access and format them as datastores.
  • The datastore is a special logical container, analogous to a file system on a logical volume, where hosts place virtual disk files and other files that encapsulate essential components of a virtual machine.
  • Datastores can hide specifics of different storage products and provide a uniform model for storing virtual machine files.

What is Datastore ?

  • A datastore is a logical container that holds virtual machine files and other files necessary for virtual machine operations.
  • Datastores can exist on different types of physical storage, including local storage, iSCSI (internet Small Computer System Interface), Fibre Channel SAN (Storage Area Network), or NFS.
  • A datastore can be VMFS-based (Virtual Machine File System) or NFS-based (Network File System).

datastore

What is Datastore Cluster ?

  • A datastore cluster is a collection of datastores that share resources and a management interface.
  • When you add a datastore to a datastore cluster, the cluster’s resources become part of the datastore cluster’s resources.
  • You use datastore clusters to aggregate storage resources, which enables you to support resource allocation policies at the datastore cluster level.
  • When you create a datastore cluster, you can use Storage DRS to manage storage resources. The I/O load balancing functionality available with Storage DRS is available only when all hosts connected to the datastores in the datastore cluster.

datastoreCluster

What is Networks view ?

  • This view displays the set of networking objects available on vCenter.
  • Using the Networking view, you can create and manage networking with vSphere Distirbuted Switches and networking with Standard Switches configuration.
  • vSphere Distributed Switches manages virtual machines and host networking at datacenter level.
  • vSphere Standard Switches manages virtual machines and host networking at host level.

Setting up vSphere Distributed Switch Architeracture (In vSphere Client)

distswitcharc

  • The first step in setting up a networking environment using vSphere Distributed Switches is to create a vSphere Distributed Switch in the Networking inventory view of the vSphere Client.
  • vSphere Distributed Switches are created at the datacenter level in the Networks view of the vSphere Client.
  • After a vSphere Distributed Switch is created, hosts and distributed port groups can be added to it.
  • Host networking options are configured through the individual host networking configuration page or using host profiles.
  • Finally, virtual machine NICs are connected to the distributed port groups. Connect virtual machine NICs through individual virtual machine NIC configuration or by migrating virtual machine networking from the vSphere Distributed Switch itself.

Setting up vSphere Standard Switch architecture

stdswitcharc

  • Switches can be done from the Configuration tab of the host view.
  • Port groups for virtual machine networking or networking services, such as service console networking, vMotion, and iSCSI networking, are configured using the Add Networking Wizard.
  • New Standard Switches can be created during the port group creation process, or you can connect your new port group to an already existing Standard Switch.
  • A virtual machine is connected to a virtual network by assigning the virtual machine’s NIC to that network’s port group.

Purpose : Check the application is on line or off line. If application is off line then save the data into the sqlite database. And when application is online then save the sqlite data into sqlserver first and delete from sqlite data.

Steps :

Step1: Create Html Page.

<!DOCTYPE html PUBLIC >
<html>
<head>
<title>Exercise 3</title>
<link rel="Stylesheet"  href="../Styles/ExercisePage3StyleSheet.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

<body>
<h1>CONTACT FORM</h1>
<form id="mycontact">
<fieldset>
<legend>Your details</legend>

<ol>

<li>

<label for="username">Name</label>

<input id="username" type="text" placeholder="First and last name" required  autofocus pattern=" ">

<input type="hidden" id="id"/>

</li>

<li>

<label for="useremail">Email</label>

<input id="useremail" type="text" placeholder="example@domain.com" required pattern=" ">

</li>

</ol>

</fieldset>

<button id="btnReset" type=submit>Reset</button>

<button id="submitButton" type="submit">SAVE</button>

<button id="btnUpdate" type=submit>UPDATE</button>

<button id="btnDrop" type=submit>DROP</button>

</form>

<br />

<div id="results"></div>

</body>

<script type="text/javascript" src="../Scripts/ExercisePage3JS.js"> </script>

</html>

 

Step 2 : Mank a Style in CSS.


html, body, h1, form, fieldset, legend, ol, li

{

margin: 0;

padding: 0;

}

body

{

background: #ffffff;

color: #111111;

font-family: Georgia, "Times New Roman", Times, serif;

padding : 20px;

}

form#mycontact

{

background: #9cbc2c;

-moz-border-radius: 5px;

-webkit-border-radius: 5px;

padding: 20px;

width: 400px;

height: 150px;

}

form#mycontact fieldset

{

border: none;

margin-bottom: 10px;

}

form#mycontact fieldset:last-of-type

{

margin-bottom: 0;

}

form#mycontact legend

{

color: #384313;

font-size: 16px;

font-weight: bold;

padding-bottom: 10px;

}

form#mycontact > fieldset > legend:before

{

content: "Step " counter(fieldsets) ": ";

counter-increment: fieldsets;

}

form#mycontact fieldset fieldset legend

{

color: #111111;

font-size: 13px;

font-weight: normal;

padding-bottom: 0;

}

form#mycontact ol li

{

background: #b9cf6a;

background: rgba(255,255,255,.3);

border-color: #e3ebc3;

border-color: rgba(255,255,255,.6);

border-style: solid;

border-width: 2px;

-moz-border-radius: 5px;

-webkit-border-radius: 5px;

line-height: 30px;

list-style: none;

padding: 5px 10px;

margin-bottom: 2px;

}

form#mycontact ol ol li

{

background: none;

border: none;

float: left;

}

form#mycontact label

{

float: left;

font-size: 13px;

width: 110px;

}

form#mycontact fieldset fieldset label

{

background:none no-repeat left 50%;

line-height: 20px;

padding: 0 0 0 30px;

width: auto;

}

form#mycontact fieldset fieldset label:hover

{

cursor: pointer;

}

form#mycontact textarea

{

background: #ffffff;

border: none;

-moz-border-radius: 3px;

-webkit-border-radius: 3px;

-khtml-border-radius: 3px;

font: italic 13px Georgia, "Times New Roman", Times, serif;

outline: none;

padding: 5px;

width: 200px;

}

form#mycontact input:not([type=submit]):focus,

form#mycontact textarea:focus

{

background: #eaeaea;

}

form#mycontact button

{

background: #384313;

border: none;

float:left;

-moz-border-radius: 20px;

-webkit-border-radius: 20px;

-khtml-border-radius: 20px;

border-radius: 20px;

color: #ffffff;

display: block;

font: 14px Georgia, "Times New Roman", Times, serif;

letter-spacing: 1px;

margin: 7px 0 0 5px;

padding: 7px 20px;

text-shadow: 0 1px 1px #000000;

text-transform: uppercase;

}

form#mycontact button:hover

{

background: #1e2506;

cursor: pointer;

}

Step 3 :  Write the JQuery Code.


// Query for SQLite

var createStatement = "CREATE TABLE IF NOT EXISTS Contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, useremail TEXT)";

var selectAllStatement = "SELECT * FROM Contacts";

var insertStatement = "INSERT INTO Contacts (username, useremail) VALUES (?, ?)";

var db = openDatabase("AddressBook", "1.0", "Address Book", 200000);  // Open the SQLite database

var dataset;

var DataType;

function initDatabase()

{

try {

if (!window.openDatabase)  // Check Browser Support SQLite Database or Not.

{

alert('Databases are not supported in this browser.');

}

else {

createTable();

}

}

catch (e) {

if (e == 2) {

// Version number mismatch.

console.log("Invalid database version.");

} else {

console.log("Unknown error " + e + ".");

}

return;

}

}

function createTable() {

db.transaction(function (tx) { tx.executeSql(createStatement, [], showRecords, onError); });

}

function insertRecord() {
if (navigator.onLine) // Check internet is online or Off-line.

{

db.transaction(function (tx)

{

tx.executeSql(selectAllStatement, [], function (tx, result)  // Fetch records from SQLite

{

dataset = result.rows;

for (var i = 0, item = null; i < dataset.length; i++) {

item = dataset.item(i);

var useridinsert = item['id'];

var usernameinsert = item['username'];

var useremailinsert = item['useremail'];

InsertRecordOnServerFunction(useridinsert, usernameinsert, useremailinsert);      // Call Function for insert Record into SQl Server through WCF service.

}

});

});

var usernametemp = $('input:text[id=username]').val();

var useremailtemp = $('input:text[id=useremail]').val();

var useridtemp = 0;

InsertRecordOnServerFunction(useridtemp, usernametemp, useremailtemp);

}

else

{

var usernametemp = $('input:text[id=username]').val();

var useremailtemp = $('input:text[id=useremail]').val();

db.transaction(function (tx) { tx.executeSql(insertStatement, [usernametemp, useremailtemp], loadAndReset, onError); }); // If Off-line, then insert into SQLite.

}

}

function InsertRecordOnServerFunction(useridinsert, usernameinsert, useremailinsert)  // Function for insert Record into SQl Server through WCF service.

{

var userinsertinfo = { UserInformation: { userId: useridinsert, userName: usernameinsert, userEmail: useremailinsert} };

var jsondata = JSON.stringify(userinsertinfo);   // Convert String into JSON format.

$.ajax({

type: "POST",

url: "http://localhost/HTML5Service/LoginService.svc/AddUser",

data: jsondata,

contentType: "application/json; charset=utf-8",

dataType: "json",

processdata: true,

success: function (msg)

{

//On Successfull service call

InsertServiceSucceeded(msg);

},

error: function (msg) {

alert("Error In Service");

}

});

}

function InsertServiceSucceeded(result) // Sucess Handler Function..

{

resultObject = result.InsertUserInformationResult;

if (resultObject)

{

alert("User Id for Deleted :   " + resultObject.ErrorDesc);

var inserteduserid = Number(resultObject.userId);

db.transaction(function (tx) { tx.executeSql(deleteStatement, [inserteduserid], showRecords, onError); alert("Delete User :  " + resultObject.userName + " Sucessfully"); });

}

else

{

alert("User Not Deleted");

$('#txtUserName').val("");

$('#txtPassword').val("");

$("#id").val("");

}

}

$(document).ready(function () // Function call when document is ready...

{
$("body").fadeIn(2000);
initDatabase();
$("#submitButton").click(insertRecord);
});

ASP.NET 4.0  Side

 

Step 4 : Write a WCF Service

 


private void AddUser(UserInformation userInformation)

{

try

{

SqlConnection con = new SqlConnection("Data Source=SG-IND-J-212;Initial Catalog=Employee;Persist Security Info=True;User ID=sa;Password=sa");

SqlCommand cmd = new SqlCommand("InserUpdateUser", con);
cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = userInformation.userName;
cmd.Parameters.Add("@UserPassword", SqlDbType.VarChar).Value = userInformation.passWord;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = userInformation.firstName;
cmd.Parameters.Add("@MiddleName", SqlDbType.VarChar).Value = userInformation.middleName;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = userInformation.lastName;
cmd.Parameters.Add("@UserEmail", SqlDbType.VarChar).Value = userInformation.userEmail;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
userInformation.ErrorDesc = "Success";
}

catch (Exception ex)
{
userInformation.ErrorDesc = ex.Message;
}

}

}

[DataContract]

public class UserInformation : ErrorInfo

{

[DataMember]

public int userId;

[DataMember]

public string passWord;

[DataMember]

public string firstName;

[DataMember]

public string lastName;

[DataMember]

public string middleName;

[DataMember]

public string userName;

[DataMember]

public string userEmail;

}

[DataContract]

public class ErrorInfo

{

[DataMember]

public string ErrorDesc;

}

Step 5 : Define the Interface for Operation Contract.


namespace SampleService

{

[ServiceContract]

public interface ILoginService

{

[OperationContract]

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat =                                    WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

void AddUser(UserInformation userInformation);

}

}

Step 6 : Set Header Response in Globel.asmx


protected void Application_BeginRequest(object sender, EventArgs e)

{

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

HttpContext.Current.Response.Cache.SetNoStore();

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")

{

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");

HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

HttpContext.Current.Response.End();

}

}

Step7 : Set Web.config file


<?xml version="1.0" encoding="UTF-8"?>

<configuration>

<system.web>

<compilation debug="true" />

<identity impersonate="false" />

</system.web>

<system.serviceModel>

<behaviors>

<endpointBehaviors>

<behavior name="EndpBehavior">

<webHttp />

</behavior>

</endpointBehaviors>

<serviceBehaviors>

<behavior name="ServiceBehavior">

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="true" />

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<services>

<service behaviorConfiguration="ServiceBehavior" name="SampleService.Service1">

<endpoint address="" behaviorConfiguration="EndpBehavior" binding="webHttpBinding" contract="SampleService.IService1" />

</service>

<service behaviorConfiguration="ServiceBehavior" name="SampleService.LoginService">

<endpoint address="" behaviorConfiguration="EndpBehavior" binding="webHttpBinding" contract="SampleService.ILoginService" />

</service>

</services>

<standardEndpoints>

<webHttpEndpoint>

<!-- Use this element to configure the endpoint -->

<standardEndpoint name="" />

</webHttpEndpoint>

</standardEndpoints>

</system.serviceModel>

</configuration>

Step 8 : Create a Store Procedure in MS Sql Server 2008


USE [Employee]

GO

/****** Object:  StoredProcedure [dbo].[InserUpdateUser]    Script Date: 12/30/2011 14:48:48 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:        tejas patel

-- Create date: <Create Date,,>

-- Description:   Employee Data

-- =============================================

ALTER PROCEDURE [dbo].[InserUpdateUser]

-- Add the parameters for the stored procedure here

@UserId int = 0,

@UserName varchar(100) = NULL,

@UserPassword varchar(100) = NULL,

@FirstName varchar(100) = NULL,

@MiddleName varchar(100) = NULL,

@LastName varchar(100) = NULL,

@UserEmail varchar(200) = NULL

AS

BEGIN tran

BEGIN

IF NOT EXISTS (SELECT * FROM UserProfile WHERE UserId = @UserId ) OR @UserId = 0

BEGIN

-- INSERT

INSERT INTO UserProfile

VALUES (@UserName,@UserPassword,@FirstName,@MiddleName,@LastName,@UserEmail)

END

ELSE

BEGIN

-- UPDATE

UPDATE UserProfile

SET

UserName = @UserName,

UserPassword = @UserPassword,

FirstName = @FirstName,

MiddleName = @MiddleName,

LastName = @LastName,

UserEmail = @UserEmail

WHERE UserId = @UserId

END

--IF @@error<>0

--BEGIN

--    ROLLBACK

--END

COMMIT tran

END

Purpose :  Create SQLite Off-Line Database and Insert,Update,Delete,Drop Operations  in SQLite using JQuery ,HTML5 Inputs.

Example : 

 

Steps :

Step 1 : Create HTML Page.


<!DOCTYPE html PUBLIC>

 <html>

<head>

    <title>Exercise 3</title>

    <link rel="Stylesheet"  href="../Styles/ExercisePage3StyleSheet.css"/>

     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

<body>

<h1>CONTACT FORM</h1>

              <form id="mycontact">

                     <fieldset>

                           <legend>Your details</legend>

                           <ol>

                                  <li>

                                         <label for="username">Name</label>

                                         <input id="username" type="text" placeholder="First and last name" required autofocus pattern=" ">

                        <input type="hidden" id="id"/>

                                  </li>

                                  <li>

                                         <label for="useremail">Email</label>

                                         <input id="useremail" type="text" placeholder="example@domain.com" required pattern=" ">

                                  </li>

                           </ol>

                     </fieldset>

                <button id="btnReset" type=submit>Reset</button>

                     <button id="submitButton" type="submit">SAVE</button>

                <button id="btnUpdate" type=submit>UPDATE</button>

                <button id="btnDrop" type=submit>DROP</button>

              </form><br />

        <div id="results"></div>

</body>

 <script type="text/javascript" src="../Scripts/ExercisePage3JS.js"> </script>

</html>

<span style="font-family: Calibri; font-size: small;"> 

Step 2 : Make a Style to a Contact Form in CSS file ( Ex. ExercisePage3StyleSheet.css)


html, body, h1, form, fieldset, legend, ol, li

{

    margin: 0;

    padding: 0;

}

body

{

    background: #ffffff;

    color: #111111;

    font-family: Georgia, "Times New Roman", Times, serif;

    padding : 20px;

}

form#mycontact

{

    background: #9cbc2c;

    -moz-border-radius: 5px;

    -webkit-border-radius: 5px;

    padding: 20px;

    width: 400px;

    height: 150px;

}

form#mycontact fieldset

{

    border: none;

    margin-bottom: 10px;

}

form#mycontact fieldset:last-of-type

{

    margin-bottom: 0;

}

form#mycontact legend

{

    color: #384313;

    font-size: 16px;

    font-weight: bold;

    padding-bottom: 10px;

}

form#mycontact > fieldset > legend:before

{

    content: "Step " counter(fieldsets) ": ";

    counter-increment: fieldsets;

}

form#mycontact fieldset fieldset legend

{

    color: #111111;

    font-size: 13px;

    font-weight: normal;

    padding-bottom: 0;

}

form#mycontact ol li

{

    background: #b9cf6a;

    background: rgba(255,255,255,.3);

    border-color: #e3ebc3;

    border-color: rgba(255,255,255,.6);

    border-style: solid;

    border-width: 2px;

    -moz-border-radius: 5px;

    -webkit-border-radius: 5px;

    line-height: 30px;

    list-style: none;

    padding: 5px 10px;

    margin-bottom: 2px;

}

form#mycontact ol ol li

{

    background: none;

    border: none;

    float: left;

}

form#mycontact label

{

    float: left;

    font-size: 13px;

    width: 110px;

}

form#mycontact fieldset fieldset label

{

    background:none no-repeat left 50%;

    line-height: 20px;

    padding: 0 0 0 30px;

    width: auto;

}

form#mycontact fieldset fieldset label:hover

{

    cursor: pointer;

}

form#mycontact textarea

{

    background: #ffffff;

    border: none;

    -moz-border-radius: 3px;

    -webkit-border-radius: 3px;

    -khtml-border-radius: 3px;

    font: italic 13px Georgia, "Times New Roman", Times, serif;

    outline: none;

    padding: 5px;

    width: 200px;

}

form#mycontact input:not([type=submit]):focus,

form#mycontact textarea:focus

{

    background: #eaeaea;

}

form#mycontact button

{

    background: #384313;

    border: none;

    float:left;

    -moz-border-radius: 20px;

    -webkit-border-radius: 20px;

    -khtml-border-radius: 20px;

    border-radius: 20px;

    color: #ffffff;

    display: block;

    font: 14px Georgia, "Times New Roman", Times, serif;

    letter-spacing: 1px;

    margin: 7px 0 0 5px;

    padding: 7px 20px;

    text-shadow: 0 1px 1px #000000;

    text-transform: uppercase;

}

form#mycontact button:hover

{

    background: #1e2506;

    cursor: pointer;

}

 

Step 3 : Write the code in JS File.


//  Declare SQL Query for SQLite

var createStatement = "CREATE TABLE IF NOT EXISTS Contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, useremail TEXT)";

var selectAllStatement = "SELECT * FROM Contacts";

var insertStatement = "INSERT INTO Contacts (username, useremail) VALUES (?, ?)";

var updateStatement = "UPDATE Contacts SET username = ?, useremail = ? WHERE id=?";

var deleteStatement = "DELETE FROM Contacts WHERE id=?";

var dropStatement = "DROP TABLE Contacts";

 var db = openDatabase("AddressBook", "1.0", "Address Book", 200000);  // Open SQLite Database

var dataset;

var DataType;

 function initDatabase()  // Function Call When Page is ready.

{

    try {

        if (!window.openDatabase)  // Check browser is supported SQLite or not.

        {

            alert('Databases are not supported in this browser.');

        }

        else {

            createTable();  // If supported then call Function for create table in SQLite

        }

    }

    catch (e) {

        if (e == 2) {

            // Version number mismatch. 

            console.log("Invalid database version.");

        } else {

            console.log("Unknown error " + e + ".");

        }

        return;

    }

}

function createTable()  // Function for Create Table in SQLite.

{

    db.transaction(function (tx) { tx.executeSql(createStatement, [], showRecords, onError); });

}

function insertRecord() // Get value from Input and insert record . Function Call when Save/Submit Button Click..

{

        var usernametemp = $('input:text[id=username]').val();

        var useremailtemp = $('input:text[id=useremail]').val();
        db.transaction(function (tx) { tx.executeSql(insertStatement, [usernametemp, useremailtemp], loadAndReset, onError); });

        //tx.executeSql(SQL Query Statement,[ Parameters ] , Sucess Result Handler Function, Error Result Handler Function );

}

function deleteRecord(id) // Get id of record . Function Call when Delete Button Click..

{

    var iddelete = id.toString();

    db.transaction(function (tx) { tx.executeSql(deleteStatement, [id], showRecords, onError); alert("Delete Sucessfully"); });

    resetForm();

}

function updateRecord() // Get id of record . Function Call when Delete Button Click..

{

    var usernameupdate = $('input:text[id=username]').val().toString();

    var useremailupdate = $('input:text[id=useremail]').val().toString();

    var useridupdate = $("#id").val();

    db.transaction(function (tx) { tx.executeSql(updateStatement, [usernameupdate, useremailupdate, Number(useridupdate)], loadAndReset, onError); });

}

function dropTable() // Function Call when Drop Button Click.. Talbe will be dropped from database.

{

    db.transaction(function (tx) { tx.executeSql(dropStatement, [], showRecords, onError); });

    resetForm();

    initDatabase();

}

function loadRecord(i) // Function for display records which are retrived from database.

{

    var item = dataset.item(i);

    $("#username").val((item['username']).toString());

    $("#useremail").val((item['useremail']).toString());

    $("#id").val((item['id']).toString());

}

function resetForm() // Function for reset form input values.

{

    $("#username").val("");

    $("#useremail").val("");

    $("#id").val("");

}

function loadAndReset() //Function for Load and Reset...

{

    resetForm();

    showRecords()

}

function onError(tx, error) // Function for Hendeling Error...

{

    alert(error.message);

}

function showRecords() // Function For Retrive data from Database Display records as list

{

    $("#results").html('')

    db.transaction(function (tx) {

        tx.executeSql(selectAllStatement, [], function (tx, result) {

            dataset = result.rows;

            for (var i = 0, item = null; i < dataset.length; i++) {

                item = dataset.item(i);

                var linkeditdelete = '<li>' + item['username'] + ' , ' + item['useremail'] + '    ' + '<a href="#" onclick="loadRecord(' + i + ');">edit</a>' + '    ' +

                                            '<a href="#" onclick="deleteRecord(' + item['id'] + ');">delete</a></li>';

                $("#results").append(linkeditdelete);

            }

        });

    });

}

$(document).ready(function () // Call function when page is ready for load..

{
;

    $("body").fadeIn(2000); // Fede In Effect when Page Load..

    initDatabase();

    $("#submitButton").click(insertRecord);  // Register Event Listener when button click.

    $("#btnUpdate").click(updateRecord);

    $("#btnReset").click(resetForm);

    $("#btnDrop").click(dropTable);

});

 

Step 4 : Run application into the browser..

SQLite Database look like,

Purpose :    Call WCF Service form HTML5 page through JQuery using  Json and AJAX  POST Method.

Example :  Login Page using HTML5 + JQUERY + WCF SERVICE

STEPS :

STEP1 : Make HTML page format.


<!DOCTYPE html>

&nbsp;

<html>

<head>

<title>Login Page</title>

<LINK REL="STYLESHEET" HREF="../STYLES/LOGINFORMSTYLE.CSS" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

<script type="text/javascript" src="../Scripts/LoginScript.js">

</script>

</head>

<body>

<div id="registration">

<h2>Login Account</h2>

<form id="registerUserForm">

<fieldset>

<p>

<input id="txtUserName" type="text" required="required" autofocus="true" placeholder="User Name"  />

</p>

<p>

<input id="txtPassword"  type="password"  required="required" placeholder="Password" />

</p>

<p>

<input type="button" id="submitForm" autofocus="false" />

</p>

</fieldset>

</form>

</div>

</body>

</html>

STEP 2 : Write JQuery Code for Lognin Using JSon

//  Declare Varibales which are using in AJAX method.

var Type;

var Url;

var Data;

var ContentType;

var DataType;

var ProcessData;

//Generic function to call AXMX/WCF  Service

function CallLoginService()

{

$.ajax({

type: Type, //GET or POST or PUT or DELETE verb

url: Url, // Location of the service

data: Data, //Data sent to server

contentType: ContentType, // content type sent to server

dataType: DataType, //Expected data format from server

processdata: ProcessData, //True or False

crossDomain: true,

success: function (msg)

{

//On Successfull service call

ServiceSucceeded(msg);

},

error: ServiceFailed  // When Service call fails

});

}

function ServiceSucceeded(result) {

if (DataType == "json")

{

resultObject = result.VelidateUserResult;

if (resultObject)

{

var userdata = JSON.stringify(resultObject);

sessionStorage.userInforamtion = userdata;

window.location = "ExercisePage2.htm";

}

else

{

alert("Invalid User");

$('#txtUserName').val("");

$('#txtPassword').val("");

}

}

else {

alert("Result Data type is not JSON");

}

}

function ServiceFailed(result) {

alert('Service call failed: ' + result.status + '' + result.statusText);

Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;

}

function VelidateUser() {

var request = { userProfile: { userId: $('#txtUserName').val(),passWord: $('#txtPassword').val()} };

var jsondata = JSON.stringify(request);

Type = "POST";

Url = "http://localhost/HTML5Service/LoginService.svc/VelidateUser";

Data = jsondata;

ContentType = "application/json; charset=utf-8";

DataType = "json";

ProcessData = true;

// Call the Web Service....

CallLoginService();

}

$(document).ready

(

function ()

{

$('#submitForm').click

(

function (event)

{

event.preventDefault();

VelidateUser();

}

);

}

);

 STEP 3 :  Code for CSS Style


html, body, h1, form, fieldset, input {

margin: 0;

padding: 0;

border: none;

}

body { font-family: Helvetica, Arial, sans-serif; font-size: 12px; }

#registration {

color: #fff;

background: #2d2d2d;

background: -webkit-gradient(

linear,

left bottom,

left top,

color-stop(0, rgb(60,60,60)),

color-stop(0.74, rgb(43,43,43)),

color-stop(1, rgb(60,60,60))

);

background: -moz-linear-gradient(

center bottom,

rgb(60,60,60) 0%,

rgb(43,43,43) 74%,

rgb(60,60,60) 100%

);

-moz-border-radius: 10px;

-webkit-border-radius: 10px;

border-radius: 10px;

margin: 10px;

width: 430px;

position: absolute;

left: 50%;

top: 50%;

margin-left: -200px;

margin-top: -150px;

}

#registration a {

color: #8c910b;

text-shadow: 0px -1px 0px #000;

}

#registration fieldset {

padding: 20px;

}

input::-webkit-input-placeholder

{

color: #303030;

}

input.text {

-webkit-border-radius: 15px;

-moz-border-radius: 15px;

border-radius: 15px;

border:solid 1px #444;

font-size: 14px;

width: 90%;

padding: 7px 8px 7px 30px;

-moz-box-shadow: 0px 1px 0px #777;

-webkit-box-shadow: 0px 1px 0px #777;

background: #ddd url('../images/LoginFormImg/inputSprite.png') no-repeat 4px 5px;

background: url('../images/LoginFormImg/inputSprite.png') no-repeat 4px 5px, -moz-linear-gradient(

center bottom,

rgb(225,225,225) 0%,

rgb(215,215,215) 54%,

rgb(173,173,173) 100%

);

background:  url('../images/LoginFormImg/inputSprite.png') no-repeat 4px 5px, -webkit-gradient(

linear,

left bottom,

left top,

color-stop(0, rgb(225,225,225)),

color-stop(0.54, rgb(215,215,215)),

color-stop(1, rgb(173,173,173))

);

color:#333;

text-shadow:0px 1px 0px #FFF;

}

input#email {

background-position: 4px 5px;

background-position: 4px 5px, 0px 0px;

}

input#txtPassword {

background-position: 4px -20px;

background-position: 4px -20px, 0px 0px;

}

input#txtUserName {

background-position: 4px -46px;

background-position: 4px -46px, 0px 0px;

}

input#tel {

background-position: 4px -76px;

background-position: 4px -76px, 0px 0px;

}

#registration h2 {

color: #fff;

text-shadow: 0px -1px 0px #000;

border-bottom: solid #181818 1px;

-moz-box-shadow: 0px 1px 0px #3a3a3a;

text-align: center;

padding: 18px;

margin: 0px;

font-weight: normal;

font-size: 24px;

font-family: Lucida Grande, Helvetica, Arial, sans-serif;

}

#submitForm {

width: 203px;

height: 40px;

border: none;

text-indent: -9999px;

background: url('../images/LoginFormImg/createAccountButton.png') no-repeat;

cursor: pointer;

float: right;

}

#submitForm:hover { background-position: 0px -41px; }

#submitForm:active { background-position: 0px -82px; }

#registration p {

position: relative;

}

fieldset label.infield /* .infield label added by JS */ {

color: #333;

text-shadow: 0px 1px 0px #fff;

position: absolute;

text-align: left;

top: 3px !important;

left: 35px !important;

line-height: 29px;

}

Code For WCF Service

STEP 4: Write the Interface (ILoginService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Web.Script.Services;

using System.ServiceModel.Web;

using System.Collections.Specialized;

using System.ServiceModel.Activation;
namespace SampleService

{

[ServiceContract]

public interface ILoginService

{

[OperationContract]

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

UserProfile VelidateUser(UserProfile userProfile);

}

[DataContract]

public class UserProfile

{

[DataMember]

public string userId;

[DataMember]

public string passWord;

[DataMember]

public string firstName;

[DataMember]

public string lastName;

[DataMember]

public string middleName;

[DataMember]

public string userName;

[DataMember]

public string userEmail;

}

}

STEP 5 : Write WCF Service for validating user. (LoginService.svc.cs)


public UserProfile VelidateUser(UserProfile userProfile)

{

if (userProfile == null)

{

return null;

}

else

{

if ((userProfile.userId.ToLower() == "admin") && (userProfile.passWord.ToLower() == "admin"))

{

UserProfile currentuser = new UserProfile();

currentuser = userProfile;

currentuser.firstName = "TEJAS";

currentuser.middleName = "RAJENDRABHAI";

currentuser.lastName = "PATEL";

return userProfile;

}

else

{

return null;

}

}

}

STEP 6 : Setting in web.conig file


<?xml version="1.0" encoding="UTF-8"?>

<configuration>

<system.web>

<compilation debug="true" />

<identity impersonate="false" />

</system.web>

<system.serviceModel>

<behaviors>

<endpointBehaviors>

<behavior name="EndpBehavior">

<webHttp />

</behavior>

<!--<behavior name="SampleService.LoginServiceAspNetAjaxBehavior">

<enableWebScript />

</behavior>-->

</endpointBehaviors>

<serviceBehaviors>

<behavior name="ServiceBehavior">

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="true" />

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<services>

<service behaviorConfiguration="ServiceBehavior" name="SampleService.Service1">

<endpoint address="" behaviorConfiguration="EndpBehavior" binding="webHttpBinding" contract="SampleService.IService1" />

</service>

<service behaviorConfiguration="ServiceBehavior" name="SampleService.LoginService">

<endpoint address="" behaviorConfiguration="EndpBehavior" binding="webHttpBinding" contract="SampleService.ILoginService" />

</service>

</services>

<standardEndpoints>

<webHttpEndpoint>

<!-- Use this element to configure the endpoint -->

<standardEndpoint name="" />

</webHttpEndpoint>

</standardEndpoints>

</system.serviceModel>
</configuration>

STEP 7 : Write Application_BeginRequest Method in Global.asax Service

protected void Application_BeginRequest(object sender, EventArgs e)

{

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

HttpContext.Current.Response.Cache.SetNoStore();

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")

{

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");

HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

HttpContext.Current.Response.End();

}

}

STEP 8 : Configuration Service in IIS.

Set Advance Setting and Application Pool

Set Authentication

STEP : 9   Run page in browser