Friday, September 28, 2012

Steps to Creating Self signed certificate for IIS7 and make websites Https


OBTAIN A CERTIFICATE

Select the server node in the treeview and double-click the Server Certificates feature in the listview:
Click Create Self-Signed Certificate... in the Actions pane.
Enter a friendly name for the new certificate and click OK.
Now you have a self-signed certificate. The certificate is marked for "Server Authentication" use; that is, it uses as a server-side certificate for HTTP SSL encryption and for authenticating the identity of the server.

CREATE AN SSL BINDING

Select a site in the tree view and click Bindings... in the Actions pane. This brings up the bindings editor that lets you create, edit, and delete bindings for your Web site. Click Add... to add your new SSL binding to the site.
The default settings for a new binding are set to HTTP on port 80. Select https in the Type drop-down list. Select the self-signed certificate you created in the previous section from the SSL Certificate drop-down list and then click OK.
Now you have a new SSL binding on your site and all that remains is to verify that it works.

VERIFY THE SSL BINDING

In the Actions pane, under Browse Web Site, click the link associated with the binding you just created.
Internet Explorere (IE) 7 and above will display an error page because the self-signed certificate was issued by your computer, not by a trusted Certificate Authority (CA). IE 7 and above will trust the certificate if you add it to the list of Trusted Root Certification Authorities in the certificates store it on the local computer, or in Group Policy for the domain.
Click Continue to this website (not recommended).

CONFIGURE SSL SETTINGS

Configure SSL settings if you want your site to require SSL, or to interact in a specific way with client certificates. Click the site node in the tree view to go back to the site's home page. Double-click the SSL Settings feature in the middle pane.

Jquery UTF8 Encode and Decode

To encode and decode using UTF8

UTF8 will encode only UTF8 characters not like base64.

No need to Include any JS file in your project, just add jquery file

Encode:

function encode_utf8(s) { 

 return unescape(encodeURIComponent(s)); 


Decode:

  function decode_utf8(s) { 

     return decodeURIComponent(escape(s)); 

 }



Ex:  alert(encode_utf8("Text�‡‰™©"))

Jquery Base64 Encode and Decode

To encode and decode using base64

Include "jquery.base64.js" file mentioned below in your project and jquery file

Encode:

function encode_base64(s)
{
  return $.base64.encode(s);
}

Decode:


function decode_base64(s)
{
  return $.base64.decode(s);
}


Create and add the following code in "jquery.base64.js" file


        /*jslint adsafe: false, bitwise: true, browser: true, cap: false, css: false,
        debug: false, devel: true, eqeqeq: true, es5: false, evil: false,
        forin: false, fragment: false, immed: true, laxbreak: false, newcap: true,
        nomen: false, on: false, onevar: true, passfail: false, plusplus: true,
        regexp: false, rhino: true, safe: false, strict: false, sub: false,
        undef: true, white: false, widget: false, windows: false */
        /*global jQuery: false, window: false */
        "use strict";

        /*
        * Original code (c) 2010 Nick Galbreath
        * http://code.google.com/p/stringencoders/source/browse/#svn/trunk/javascript
        *
        * jQuery port (c) 2010 Carlo Zottmann
        * http://github.com/carlo/jquery-base64
        *
        * Permission is hereby granted, free of charge, to any person
        * obtaining a copy of this software and associated documentation
        * files (the "Software"), to deal in the Software without
        * restriction, including without limitation the rights to use,
        * copy, modify, merge, publish, distribute, sublicense, and/or sell
        * copies of the Software, and to permit persons to whom the
        * Software is furnished to do so, subject to the following
        * conditions:
        *
        * The above copyright notice and this permission notice shall be
        * included in all copies or substantial portions of the Software.
        *
        * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
        * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
        * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
        * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
        * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
        * OTHER DEALINGS IN THE SOFTWARE.
        */

        /* base64 encode/decode compatible with window.btoa/atob
        *
        * window.atob/btoa is a Firefox extension to convert binary data (the "b")
        * to base64 (ascii, the "a").
        *
        * It is also found in Safari and Chrome.  It is not available in IE.
        *
        * if (!window.btoa) window.btoa = $.base64.encode
        * if (!window.atob) window.atob = $.base64.decode
        *
        * The original spec's for atob/btoa are a bit lacking
        * https://developer.mozilla.org/en/DOM/window.atob
        * https://developer.mozilla.org/en/DOM/window.btoa
        *
        * window.btoa and $.base64.encode takes a string where charCodeAt is [0,255]
        * If any character is not [0,255], then an exception is thrown.
        *
        * window.atob and $.base64.decode take a base64-encoded string
        * If the input length is not a multiple of 4, or contains invalid characters
        *   then an exception is thrown.
        */

        jQuery.base64 = (function ($) {

            var _PADCHAR = "=",
    _ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    _VERSION = "1.0";


            function _getbyte64(s, i) {
                // This is oddly fast, except on Chrome/V8.
                // Minimal or no improvement in performance by using a
                // object with properties mapping chars to value (eg. 'A': 0)

                var idx = _ALPHA.indexOf(s.charAt(i));

                if (idx === -1) {
                    throw "Cannot decode base64";
                }

                return idx;
            }


            function _decode(s) {
                var pads = 0,
      i,
      b10,
      imax = s.length,
      x = [];

                s = String(s);

                if (imax === 0) {
                    return s;
                }

                if (imax % 4 !== 0) {
                    throw "Cannot decode base64";
                }

                if (s.charAt(imax - 1) === _PADCHAR) {
                    pads = 1;

                    if (s.charAt(imax - 2) === _PADCHAR) {
                        pads = 2;
                    }

                    // either way, we want to ignore this last block
                    imax -= 4;
                }

                for (i = 0; i < imax; i += 4) {
                    b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12) | (_getbyte64(s, i + 2) << 6) | _getbyte64(s, i + 3);
                    x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff, b10 & 0xff));
                }

                switch (pads) {
                    case 1:
                        b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12) | (_getbyte64(s, i + 2) << 6);
                        x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff));
                        break;

                    case 2:
                        b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12);
                        x.push(String.fromCharCode(b10 >> 16));
                        break;
                }

                return x.join("");
            }


            function _getbyte(s, i) {
                var x = s.charCodeAt(i);

                if (x > 255) {
                    throw "INVALID_CHARACTER_ERR: DOM Exception 5";
                }

                return x;
            }


            function _encode(s) {
                if (arguments.length !== 1) {
                    throw "SyntaxError: exactly one argument required";
                }

                s = String(s);

                var i,
      b10,
      x = [],
      imax = s.length - s.length % 3;

                if (s.length === 0) {
                    return s;
                }

                for (i = 0; i < imax; i += 3) {
                    b10 = (_getbyte(s, i) << 16) | (_getbyte(s, i + 1) << 8) | _getbyte(s, i + 2);
                    x.push(_ALPHA.charAt(b10 >> 18));
                    x.push(_ALPHA.charAt((b10 >> 12) & 0x3F));
                    x.push(_ALPHA.charAt((b10 >> 6) & 0x3f));
                    x.push(_ALPHA.charAt(b10 & 0x3f));
                }

                switch (s.length - imax) {
                    case 1:
                        b10 = _getbyte(s, i) << 16;
                        x.push(_ALPHA.charAt(b10 >> 18) + _ALPHA.charAt((b10 >> 12) & 0x3F) + _PADCHAR + _PADCHAR);
                        break;

                    case 2:
                        b10 = (_getbyte(s, i) << 16) | (_getbyte(s, i + 1) << 8);
                        x.push(_ALPHA.charAt(b10 >> 18) + _ALPHA.charAt((b10 >> 12) & 0x3F) + _ALPHA.charAt((b10 >> 6) & 0x3f) + _PADCHAR);
                        break;
                }

                return x.join("");
            }


            return {
                decode: _decode,
                encode: _encode,
                VERSION: _VERSION
            };

        } (jQuery));



Thursday, September 27, 2012

Break for Jquery each function


var myarray = new Array();
myarray[0] = "balaji";
myarray[1] = "prasad";
myarray[2] = "cbe";
myarray[3] = "coimbatore";
myarray[4] = "done";

arraycount = 0;

try {
    $.each(myarray, function () {
        alert(arraycount);
        if (myarray[arraycount] == "cbe") {
            alert(myarray[arraycount]);
            throw 'loop done';
        }

        arraycount = arraycount + 1;
    });
}
catch (e) { }

Monday, September 24, 2012

Cross-domain JSONP with jQuery call step-by-step guide


What we want to accomplish?

Simple way to communicate cross-domain with ASMX .NET 3.5 Web Service

How can we do it?

1. Implement a web service method like the following

   [ScriptService]
   public class JSONP_EndPoint : System.Web.Services.WebService
   {
       [WebMethod]
       [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
       public string Sum(string x,string y)
       {
           return x + y;
       }
   }

2. Add New class library with a name ContentTypeHttpModule

The reason for this is no matter how you specify the content-type of your ajax call ASP.NET send the request with Content-Type text/xml; charset=utf-8 this is security feature explained here by ScottGu 

3. Add the following code to your Class 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace ContentTypeHttpModule
{
    public class ContentTypeHttpModule : IHttpModule
    {
        private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8";

        #region IHttpModule Members
        public void Dispose()
        {
        }

        public void Init(HttpApplication app)
        {
            app.BeginRequest += OnBeginRequest;
            app.ReleaseRequestState += OnReleaseRequestState;
        }
        #endregion

        public void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest resquest = app.Request;
            if (!resquest.Url.AbsolutePath.Contains("JSONP-EndPoint.asmx")) return;

            if (string.IsNullOrEmpty(app.Context.Request.ContentType))
            {
                app.Context.Request.ContentType = JSON_CONTENT_TYPE;
            }
        }

        public void OnReleaseRequestState(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpResponse response = app.Response;
            if (app.Context.Request.ContentType != JSON_CONTENT_TYPE) return;

            response.Filter = new JsonResponseFilter(response.Filter);
        }
    }

    public class JsonResponseFilter : Stream
    {
        private readonly Stream _responseStream;
        private long _position;

        public JsonResponseFilter(Stream responseStream)
        {
            _responseStream = responseStream;
        }

        public override bool CanRead { get { return true; } }

        public override bool CanSeek { get { return true; } }

        public override bool CanWrite { get { return true; } }

        public override long Length { get { return 0; } }

        public override long Position { get { return _position; } set { _position = value; } }

        public override void Write(byte[] buffer, int offset, int count)
        {
            string strBuffer = Encoding.UTF8.GetString(buffer, offset, count);
            strBuffer = AppendJsonpCallback(strBuffer, HttpContext.Current.Request);
            byte[] data = Encoding.UTF8.GetBytes(strBuffer);
            _responseStream.Write(data, 0, data.Length);
        }

        private string AppendJsonpCallback(string strBuffer, HttpRequest request)
        {
            return request.Params["callback"] +"(" + strBuffer + ");";
        }

        public override void Close()
        {
            _responseStream.Close();
        }

        public override void Flush()
        {
            _responseStream.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _responseStream.Seek(offset, origin);
        }

        public override void SetLength(long length)
        {
            _responseStream.SetLength(length);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _responseStream.Read(buffer, offset, count);
        }
    }
}

4. Register the HttpModule in the service project

4.1 Add referance to the HttpModule assembly to the service project
4.2 Add this code to web.config to register the module
<add name="ContentTypeHttpModule"
                    type="ContentTypeHttpModule.ContentTypeHttpModule, ContentTypeHttpModule" />
This goes under system.web / httpmodules section

5. Add a web project for testing the application

5.1 add the following libs
jquery-1.3.1.js
json2.js
5.2 add new script file caller.js
function test() {
    $.ajax({ url: "http://localhost:1690/JSONP-EndPoint.asmx/Sum",
    data: { x: JSON.stringify("Now i am getting jsop string"), y: JSON.stringify("2nd param") },
        dataType: "jsonp",
        success: function(json) {
            alert(json.d);
        },
        error: function() {
            alert("Hit error fn!");
        }
    });
}
5.3 Add referances to jquery-1.3.1.js and json2.js
5.4 Add Default.aspx page with input button that has onclick=”return test();”

6. Remarks

6.1 I use the JSON.stringify function to serialize the string data parameters.
6.2 .d is a security features on ASP.NET 3.5

Cross-domain AJAX with JSONP



Anyone who develops Javascript long enough undoubtedly runs into difficulties involving the various security features all browser vendors implement. These security features are a good thing -- they protect us from malicious users hijacking our browsing experience. But they can certainly cause some headaches. The security feature that presents the most difficulty for us as developers is the same origin policy.
In a nutshell, this policy prevents pages from two different domains from modifying each others properties, using XMLHttpRequest, setting cookies etc. For instance, Example.com and OtherExample.com can't get references to each others document properties and can't set cookies on each other. Additionally, Example.com can't use XMLHttpRequest (aka AJAX) to load a resource from OtherExample.com. This last bit is probably the biggest issue for developers today -- in todays world of open web services and mashups. How do you consume a web service with Javascript if you can't load the data properly?

Solution 1: Use a server-side proxy

The first way around this problem is to use a very simple server-side script that acts as a proxy to the web service. So instead of requesting AJAX from the remote site, you request it locally on your own domain through the proxy. The proxy itself has it's programming logic to send your request off to the remote site, gather the data, and then serve it back to you.
.________________________.
| Client on YourSite.com |
'-\/---------/\----------'
  ||         ||
  ||_________||__.
  | AJAX Request |
  '---\/-----/\--'
      ||     ||
      ||_____||______________.
      | YourSite.com         |
      | (Ex. ajax_proxy.php) |
      '---\/-----/\----------'
          ||     ||
          ||_____||__________.
          | OtherSite.com    |
          '------------------'
Since your server-side script has no qualms about fetching data from another domain, you can successfully proxy all AJAX like this without running into any trouble. And then since the client browser is fetching the data from the local domain (even though you're making another request behind the scenes), it doesn't violate the same origin policy.
An example proxy script might look something like this (maybe a little more complex if you're handling POST data too):
  1. $url = 'http://othersite.com/someservice?' . http_build_query($_GET);
Remember, the sole purpose of the proxy is just so the client browser can load the data locally on the same domain so the same origin policy isn't violated.

Drawbacks

This method works well but has two obvious drawbacks. First is of course that you need a server-side script at all. Especially if you are providing a service, this raises the barrier for entry and makes it harder for "noobs" to use your widget -- it's not a simple "paste this code into your footer" instruction; you also need to explain how to install the proxy service.
The second drawback is that your own servers are making these requests which makes the whole process slower, but also eats up your resources -- both your processing power and even just simple bandwidth.

Solution 2: JSONP

The second solution is to use JSONP -- "JSON with Padding." This is a technique that lets you get around the same origin policy. In order to use JSONP, the service you are requesting needs to support it.
So in the last solution, the consumer (the user using the service) required an ajax_proxy.php or whatever server-side proxy script. In this solution, the provider (Digg, Amazon, Yahoo -- whatever) needs to support JSONP themselves. Thankfully, these days the idea is catching on and it's likely JSONP is an option. And if you're a service provider, then you'll want to build it in to your service for sure.

How it works

A normal JSON request is sent using XMLHttpRequest and the reply looks something like this:
Plain TextJAVASCRIPT:
  1. {'uid'23'username''Chroder''name''Christopher Nadeau'}

Now the truth is, JSONP isn't AJAX at all technically speaking because it does not use XMLHttpRequest. JSONP requests are made by dynamically inserting a <script> tag into the DOM. For example, you'd insert this:
  1. <script type="text/javascript" src="http://othersite.com/service?all=your&params=as&usual=gohere"></script>

Then that remote Javascript file is loaded and contains an actual Javascript function call. For example:
Plain TextJAVASCRIPT:
  1. handleJsonReply({'uid'23'username''Chroder''name''Christopher Nadeau'});

In other words, instead of reading AJAX data directly into a variable in Javascript, you define a callback function that is called when the data arrives, and the first parameter is the data itself as an object literal. If you were a provider implementing JSON on your service you might have something like:
  1. // A service provider accepts a 'callback' parameter
  2. // that it uses to wrap an AJAX reply
  3.  
  4. // Imagine we did some work here
  5. $json = json_encode($mydata);
  6.  
  7. // Using JSONP
  8. if ($_GET['callback']) {
  9.     echo $_GET['callback'] . "($json);"// somefunction({data here});
  10.    
  11. // Normal JSON
  12. } else {
  13.     echo $json;
  14. }

The Javascript source code result of that request is nothing but a real executable function call with a Javascript object literal. It's as if you added the tag yourself and it called some functions -- the difference being that the JS is written by the producer on-the-fly and embeds the data you want right in the code. This is why it all works; it's not actually AJAX at all, it's just loading a remote Javascript file that happens to have some useful data in it.
Using a library like jQuery that supports JSONP, these details of inserting the special script tag and creating the special callback function are all taken care of automatically. Using a JS library, usually the only difference between JSONP and real AJAX is that you enable a 'jsonp' option.

Drawbacks

The first limitation to this method is that you have to rely on the provider to implement JSONP. The provider needs to actually support JSONP -- they need to wrap their JSON data with that callback function name.
Then the next limitation -- and this is a big one -- is that JSONP doesn't support POST requests. Since all data is passed in the query string as GET data, you are severely limited if your services require the passing of long data (for example, forum posts or comments or articles). But for the majority of consumer services that fetch more data than they push, this isn't such a big problem.

JSONP with jQuery

Step 1: Make sure the provider supports JSONP.
Step 2: Set the dataType option to jsonp, and if the provider uses a different GET param other than 'callback', specify the jsonp option to that parameter name.
Plain TextJAVASCRIPT:
  1. $.ajax({
  2.     // ... Use the AJAX utility as you normally would
  3.     dataType: 'jsonp',
  4.     // ...
  5. });

jQuery will generate a unique callback name for this request (something like json1268267816). Thus, the reply from a web service would be something like:
Plain TextJAVASCRIPT:
  1. json1268267816({'uid'23'username''Chroder''name''Christopher Nadeau'});
But jQuery handles it all seamlessly, so you as the developer just handle it like a normal AJAX request using the same jQuery success/failure/complete callback hooks.