Monday 23 January 2012

Tag Objects In Html:-

Using jquery data function we can tag any object to the DOM elements.

<div id="main">
</div>

//user object
var user = { 'userId': 'abc123', 'userName': 'abc' };

//subject object
var subject = { 'subName': 'cs', 'subMarks': 100 };

//adding user object to div tag
$('#main').data('user', user);

//adding subject object to div tag
$('#main').data('subject', subject);

//it retrives the user and subject object from div tag
var userandsubject = $('#main').data();

//it retrives the user object from div tag
var user = $('#main').data('user');

//it retrives the subject object from div tag
var subject = $('#main').data('subject');




Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Friday 20 January 2012

Wcf REST And xmlHttpRequest:-


Using  wcf REST(Representational state transfer) services client can directly communicate with the service without creating proxy.We can get the response data either in json or xml by specifying the WebMessageFormat.Json or WebMessageFormat.Xml respectively in WebGet attribute.

Wcf Service:-
namespace RESTWcf
{
    public class ServiceRest : IRest
    {
        public Person Get(string name, string age)
        {
            //return the person object
            return new Person() { Name = name, Age = age };
        }

        public void Invoke(string value)
        {
        }
    }
}

namespace RESTWcf
{
    [ServiceContract]
    public interface IRest
    {
        [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "Get/?name={name}&age={age}")]
        [OperationContract]
        Person Get(string name, string age);

        [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "Invoke/{value}")]
        [OperationContract]
        void Invoke(string value);
    }

    [DataContract]
    public class Person
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Age { get; set; }
    }
}

<system.serviceModel>
 <services>
    <service name="RESTWcf.ServiceRest"            behaviorConfiguration="serviceBehaviour"         >
      <endpoint address="" binding="webHttpBinding"      contract="RESTWcf.IRest" behaviorConfiguration="webHttpb"></endpoint>
    </service>
 </services>

 <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpb">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="serviceBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
 </behaviors>
</system.serviceModel>


Javascript File:-
function get() {

            //XMLHttpRequest object
            var xmlHttp = new XMLHttpRequest();

            //result handler
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4) {
                    //alert the reponse
                    alert(xmlHttp.responseText);
                }
            }

            //error handler
            xmlHttp.onerror = function (e) {
                //alert error
                alert('error');
            }

            //url of the service
            var url = "http://localhost:1094/ServiceRest.svc/Get/?name=abc&age=123";

            //the method type must be GET for accessing WebGet methods
            xmlHttp.open("GET", url, true);

            //send the request
            xmlHttp.send();
        }

        function invoke() {

            //XMLHttpRequest object
            var xmlHttp = new XMLHttpRequest();

            //result handler
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4) {
                    //alert the reponse
                    alert(xmlHttp.responseText);
                }
            }

            //error handler
            xmlHttp.onerror = function (e) {
                //alert error
                alert('error');
            }

            //url of the service
            var url = "http://localhost:1094/ServiceRest.svc/Invoke/abc";

            //the method type must be POST for accessing WebInvoke methods
            xmlHttp.open("POST", url, true);

            //send the request
            xmlHttp.send();
        }


Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

JQuery Contents:-

<html>
<head>

</head>
<body>
       <div id='divcontents'>This <span>is</span><b> bold</b></div>
       
<script type="text/javascript" language="javascript">

        //contents function data
        var con = "";

        //contents function iterates through html elements and text nodes
        $('#divcontents').contents().filter(function () {
            //html element
            if (this.nodeType == 1) {
                //get the innerHtml
                con += $(this).html();
            }
            //text node
            if (this.nodeType == 3) {
                //get the text
                con += this.wholeText;
            }
        });

        //alert data
        alert(con); //displays This is bold

        //children function data
        var chi = "";

        //contents function iterates through html elements only
        $('#divcontents').children().filter(function () {
            //html element
            if (this.nodeType == 1) {
                //get the innerHtml
                chi += $(this).html();
            }
            //text node
            if (this.nodeType == 3) {
                //get the text
                chi += this.wholeText;
            }
        });

        //alert data
        alert(chi); //displays  is bold
    </script>
       
</body>
</head>



Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Thursday 19 January 2012

Javascript Prototyping:-

Prototyping Is The Great Feature In Javascript Which Is Used To Create Propertys And Methods
If We Add The Property Or Method Using Prototyping It Added To All The Objects.

var person1 = new per('abc', '123');
var person2 = new per('xyz', '456');

function per(name, id)
{
   /*Here This Is Compulsary To Represent Current Calling Object*/
   this.name = name;
   this.id = id;
 }


/*Here We Are Adding The Property Called Address Using Prototyping*/
per.prototype.address = "mumbai";

/*Here We Are Adding The Property Called PinCode Using NormalWay */
person1.pinCode = 507164;

/*The Difference Between Above Two Is The Address Is Added To All The Objects(To The person1 & person2 Objects) And PinCode Is Added To Only To That person1 Object.(Not To The person2 Object)*/

/*HasOwnProperty Is Used To Know Either The Property Belongs To That Object Or Not*/
person1.hasOwnProperty('name'); /*true*/
person1.hasOwnProperty('id'); /*true*/
person1.hasOwnProperty('address'); /*false becuase it added using prototyping*/
person1.hasOwnProperty('pinCode'); /*true*/

/*Here We Are Adding The Method Called getNameLength Using Prototyping*/
per.prototype.getNameLength = function () {
return this.name.length;
};

/*Calling The Function Which Is Added By Using The Prototyping*/
var len = person1.getNameLength(); 




Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Javascript Functions:-

A JavaScript function is really an object. As objects, functions can also be assigned to variables, passed as arguments to other functions, returned as the values of other functions, stored as properties of objects or elements of arrays, and so on.

function fun1(x) {
alert(x);
}

fun1("fun1");
fun1['userId'] = '123';// functions can also be assigned to variables

alert(fun1.userId);//displays 123


//(or)

var fun2 = function (x) {
alert(x);
};

fun2("fun2");

//(or)

var fun3 = new Function("x,y", "alert(y);");

fun3("1", "2");

//(or)

var arr = [];

arr[0] = function (x) { return x * x; };

alert(arr[0](2)); //displays 4

//(or)
var obj = { "append": function (x) { return x + 'b'; }, "username": 'abc' };

alert(obj.append('a')); //displays ab


// passing  function as an argument to another function
function square(x) {
return x * x;
}

function calc(num, func) {
return func(num);
}

alert(calc(2, square)); //displays 4

//functions as return values
function add() {
return function (x, y) {
return x + y;
};

}
var res = add();

alert(res(1, 2)); // displays 3


//Remember, a function in JavaScript is an object. Every function object has a method named //call, which calls the function as a method of the first argument. That is, whichever object we //pass into call as its first argument will become the value of "this" in the function invocation.
function displayname() {
alert(this.userId);
}

var userObject = { 'userId': '123', 'userName': 'abc' };

displayname.call(userObject); // displays 123

//Constructor functions
function userObject(name) {
this.name = name;
}
var user = new userObject("abc"); //var user = {};, userObject.call(user, "abc");




Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Javascript Objects:-


In javascript we can create objects in  different ways.

var userObject = {};

userObject['userName'] = 'abc'(or) userObject.userName = 'abc';

(or)

var userObject = new Object();

userObject['userName'] = 'abc'(or) userObject.userName = 'abc';


(or)

var userObject = Object.create(null);

userObject['userName'] = 'abc'(or) userObject.userName = 'abc';




Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Wcf webHttpBinding And Sending Objects:-

While using webHttpBinding in wcf service we have to send json data.Wcf internally uses the DataContractSerializer to convert json data into objects.

WcfService:-
namespace WebHttpBindingXmlHttpRequestWcf
{
  [ServiceContract]
  public interface IService
  {
    [OperationContract]
          Person GetData(Person objPerson);
   }

  [DataContract]
  public class Person
  {
   [DataMember]
   public string Name { get; set; }

   [DataMember]
   public string Age { get; set; }

  }
 }    

namespace WebHttpBindingXmlHttpRequestWcf
{ 
   public class Service : IService
    {  
     public Person GetData(Person objPerson)
          
{
  
       return objPerson;
          
}
      
}
}

<system.serviceModel>
   <services>
     <service name="WebHttpBindingXmlHttpRequestWcf.Service">
       <endpoint address="webHttpBinding" 
binding="webHttpBinding" 
contract="WebHttpBindingXmlHttpRequestWcf.IService"
behaviorConfiguration="webHttpBindingEndpointBehavior">
       </endpoint>
     </service>
   </services>
    <behaviors>
       <endpointBehaviors>
         <behavior name="webHttpBindingEndpointBehavior">
           <enableWebScript/>
         </behavior>
       </endpointBehaviors>
   </behaviors>
 </system.serviceModel>

Javascript File:-

//call the wcf service
function callservice(objPerson)
{
      //url of the service
      var url=’’;

       //here the name(objPerson) must match with the name in the operation contract
       var data = '{"objPerson":' + $.toJSON(objPerson) + '}';

//jquery ajax function to call wcf service
$.ajax({ type: 'POST',
        async: true,
        url: url,
        contentType: 'application/json; charset=utf-8',
        data: data,
        success: function (res) { alert(‘success...’); },
        error: function (err) { alert(‘error occurred...’); }
    });
}



Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com