Monday, 21 January 2013

Final version of jQuery with IE 6, 7 and 8 support released

Final version of jQuery with IE 6, 7 and 8 support released

The final version of jQuery with support for Internet Explorer 6, 7 and 8 has been released as the development team move towards a smaller codebase for version 2.0.

jQuery 1.9 will be the last version of the popular JavaScript framework to support these browsers, referred to collectively in jQuery blog posts as ‘oldIE’.

The change was announced in June in an attempt to reduce the size of jQuery’s codebase, which has gradually increased in size over time and is now considered by some to be too large.

Removing oldIE support in the first beta of jQuery 2.0 has seen a 10% reduction in the size of its footprint, and Dave Methvin, president of the jQuery foundation, claimed that the work was “nowhere near done” in a blog post. Strangely, neither this release nor a blog post entitled “The State of jQuery 2013” make any reference to modularisation introduced in jQuery 1.8.

jQuery has long been praised for its support for older (and current) browsers with patchy implementation of vanilla JavaScript. However, this has become increasingly unimportant as oldIE’s market share continues to dwindle.

Though their numbers are undoubtedly falling, it’s difficult to say how much of the market will now be left unsupported by jQuery 2.0. NetMarketShare estimates that IE6,7 and 8 together retain a 32.88% market share, while StatCounter reports a meagre 12.29% share.

It’s far from a sudden transition, however: jQuery’s developers have pledged to support version 1.9 “as long as oldIE is a significant factor on the web”. In addition, jQuery 1.9 and 2.0 utilise an identical API, so the latter can be exchanged for the former on oldIE using conditional comments.

Though jQuery 2.1 may introduce new features incompatible with 1.9, it’s unlikely to come out before 2014 - by which point oldIE will have (hopefully) disappeared from the market. Before then, the official jQuery migrate plugin can be used to detect deprecated APIs, features or functionality still referenced within your code.

Source:Elliot Bentley

Saturday, 19 January 2013

How to use Google+ APIs from ASP.NET


Samples and source code:

Are you trying to integrate Google+ with your .NET applications? Google+ provides some APIs, but the output is in JSON format. Download the .NET client library for Google+ APIs and see our examples to find out how to use them.



The data retrieved using the Google+ APIs are not strongly typed as I would expect in .NET. Instead, Google+ APIs return data in JSON format, which is a structured form of data, but not strongly typed like .NET types.

 tried couple of Google+ APIs. After couple of trial and error,  was able to call some Google+ APIs, using the WebRequest class in .NET.

Here is the code I used to call Google+ API:

    string requestString = "https://www.googleapis.com/plus/v1/people/" + _profileId + "?key=" + _apiKey;
    WebRequest objWebRequest = WebRequest.Create(requestString);
    WebResponse objWebResponse = objWebRequest.GetResponse();

    Stream objWebStream = objWebResponse.GetResponseStream();

    using (StreamReader objStreamReader = new StreamReader(objWebStream))
    {
        string result = objStreamReader.ReadToEnd();

        return result;
    }

In the above code, _profileId represents a valid Google+ profile. It does not need to be any valid profile id. This API returns only public information from any profile and so no authentication is required to call this. However, you need to pass an API Key before you can call the Google+ APIs. That is what I used in the variable _apiKey. You can get a Google+ API Key from here.

The above code returns some text data in JSON format, which is structured data.

We need to convert the data in to valid .NET types. The JavaScriptSerializer class comes in handy here. We can use this class to convert the JSON data structure to corresponding C# or VB.NET class.

Example:


JavaScriptSerializer js = new JavaScriptSerializer();
string requestString = "https://www.googleapis.com/plus/v1/people/"
                  + _profileId + "?key=" + _apiKey;
string result = GetWebData(requestString);
GPlusPerson activity = js.Deserialize(result);

GPlusActivity is a custom class created that matches its properties with the keys in the JSON structured returned by the Google+ API. Each property in the class must match with the key names in the data structure returned by the API. The JavaScriptSerializer DeSerialize call will convert the data structure in to corresponding .NET object.

example, the above API call returns the following JSON data:


{
"kind": "plus#person",
"id": "102428175534077457150",
"displayName": "Tony John",
"tagline": "Microsoft MVP, Founder of dotnetspider.com",
"gender": "male",
"aboutMe": "",
"url": "https://plus.google.com/102428175534077457150",
"image": {  "url": "https://lh3.googleusercontent.com/-wDpbQaFJFKg/
        AAAAAAAAAAI/AAAAAAAAAAA/ZQ8VOHPB1Is/photo.jpg?sz=50" },
"urls": [  {   "value": "http://www.thoughtsfromgeeks.com/member/manjaly.aspx"  }, 
       {   "value": "http://www.indiastudychannel.com/member/manjaly.aspx"  }, 
       {   "value": "http://www.dotnetspider.com/member/manjaly.aspx"  } ],
"organizations": [ {   "name": "LoneStar Informatics LLP",  
                       "title": "Owner",   "type": "work"  } ],
"placesLived": [  {  "value": "Bangalore, India"  } ]
}


Now, to match the JSON structure,  have defined the .NET class like this:

public class GPlusPerson
{
    public string kind { get; set; }
    public string id { get; set; }
    public string displayName { get; set; }
    public string tagline { get; set; }
    public string birthday { get; set; }
    public string gender { get; set; }
    public string aboutMe { get; set; }
    public string url { get; set; }
    public GImage image { get; set; }
    public Url[] urls { get; set; }
    public Organization[] organizations { get; set; }
    public PlaceLived[] placesLived { get; set; }
}

You can see that each of the key in the JSON structure has a corresponding property in the .NET class. the DeSerialize method of the JavaScriptSerializer class will map the JSON key-value pair to the corresponding .NET property.

You may notice that some of the items in JSON structure is an array of data by itself. Examples: Image, Organizations, PlacesLived. I have defined each of them as separate types (classes).

You can download the full set of classes to map each of the JSON structure for all the Google+ APIs released in October 2011 (version 1). I have included some samples and basic documentation on how to call each of the Google+ APIs.

Friday, 18 January 2013

Implement Impersonation in ASP.NET

Introduction

One of our websites uses Impersonation and a specific user account with special permissions to access certain system resources. The first step in enabling impersonation is setting up the correct attributes in the web.config file:

<system.web>
<identity impersonate="true" password="xxxxxx" userName="xxxxxxx" />   

By using the attribute impersonate="true", you are telling IIS that this website will be impersonating the configured user account.
Configure the website to use a specific user account

The next step is you need to go to IIS Manager and configure the user account you want to impersonate by this website.
Steps

Open IIS Manager.
Expand computer name.
Expand websites.
Click on the specific website for which you want to use impersonation.
On the right panel, under the heading "IIS", double click "Authentication".
Right click on "ASP.NET Impersonation" and select "Edit".
Choose "Specific User".
Click the SET button to provide the specific user name and password.
Press OK at the popup dialog to complete this step on enabling impersonation for website in IIS 7.0.

How to choose process identity for Application Pool in IIS 7.0

To set the correct user identity for the application pool, follow the steps below:

Open IIS Manager.
Click on "Application Pools" under the computer name.
On the right panel, right click on the application pool name (your website’s relevant application pool).
Select "Advanced properties".
Select "Identity" under "Process Model".
Click on the button to set the user account.
Select "Custom account".
Click on the button to specify the user account and password.
Press "OK".

Recycle the app pool by right clicking on the application pool name and selecting "Recycle" on the right click context menu to ensure all configuration changes have taken place.

You are all set to use your application with the impersonated user account.
Source:The Code Project Open License (CPOL)

Thursday, 17 January 2013

Scraping JavaScript based web pages with Chickenfoot


The data from most webpages can be scraped by simply downloading the HTML and then parsing out the desired content. However some webpages load their content dynamically with JavaScript after the page loads so that the desired data is not found in the original HTML. This is usually done for legitimate reasons such as loading the page faster, but in some cases is designed solely to inhibit scrapers.
This can make scraping a little tougher, but not impossible.

The easiest case is where the content is stored in JavaScript structures which are then inserted into the DOM at page load. This means the content is still embedded in the HTML but needs to instead be scraped from the JavaScript code rather than the HTML tags.

A more tricky case is where websites encode their content in the HTML and then use JavaScript to decode it on page load. It is possible to convert such functions into Python and then run them over the downloaded HTML, but often an easier and quicker alternative is to execute the original JavaScript. One such tool to do this is the Firefox Chickenfoot extension. Chickenfoot consists of a Firefox panel where you can execute arbitrary JavaScript code within a webpage and across multiple webpages. It also comes with a number of high level functions to make interaction and navigation easier.

To get a feel for Chickenfoot here is an example to crawl a website:
Collapse | Copy Code

// crawl given website url recursively to given depth 
function crawl(website, max_depth, links) { 
  if(!links) { 
    links = {}; 
    go(website); 
    links[website] = 1; 
  } 
 
  // TODO: insert code to act on current webpage here
  if(max_depth > 0) { 
    // iterate links 
    for(var link=find("link"); link.hasMatch; link=link.next) {   
      url = link.element.href; 
      if(!links[url]) { 
        if(url.indexOf(website) == 0) { 
          // same domain 
          go(url); 
          links[url] = 1; 
          crawl(website, max_depth - 1, links); 
        } 
      } 
    } 
  } 
  back(); wait(); 
}

This is part of a script I built on my Linux machine for a client on Windows and it worked fine for both of us. To find out more about Chickenfoot check out their video.

Chickenfoot is a useful weapon in my web scraping arsenal, particularly for quick jobs with a low to medium amount of data. For larger websites there is a more suitable alternative.

Source:The Code Project Open License (CPOL)

Wednesday, 16 January 2013

Create Page Hit Counter in Asp.Net

   
Create Page Hit Counter in Asp.Net

Create table Query for Hit Counter

CREATE TABLE [dbo].[hits](
    [i_autoid] [int] IDENTITY(1,1) NOT NULL,
    [hits] [float] NULL,
    [cratedate] [datetime] NULL CONSTRAINT [DF_hits_cratedate]  DEFAULT (getdate())
)

C# Code For Hit Counter

public partial class _Default : System.Web.UI.Page
    {

        dataclass dc = new dataclass();

        protected void Page_Load(object sender, EventArgs e)
        {
            // select max hits from table
            string query = "select max(hits) as hits from hits";
            DataSet ds = new DataSet();
            ds = dc.connection(query);
            float hit = float.Parse(ds.Tables[0].Rows[0]["hits"].ToString());
            //increment hit counter with 1
            float hitsnew =    hit+1;
            // update hit counter table
            string query1 = "UPDATE  hits SET  hits = '"+hitsnew+"'";
            dc.execquery(query1);
        }
    }

We are using just simple steps.on pageload we select data from table and update counter after increment, when pageload this will increment the counter and you can show it in label ttextbox or any where..
DC is the object of Class where we perform sql related task like create connection etc.
executequery method execute query to sql server.you can use your way to execute queries.

Saturday, 12 January 2013

D3 crash course

D3 crash course

Introduction

Data-Driven Documents (D3) is a javascript library that offers an interesting approach to visualization for the web. D3 enables direct inspection and manipulation of the standard document object model (DOM). With D3 we can selectively bind input data to document elements and define dynamic transforms that both generate and modify the content of the DOM.

D3’s primary authors Michael Bostock, Vadim Ogievetsky and Jeffrey Heer have created a library that uses representational transparency to improve expressiveness and provide natural integration with developer tools. It’s quite different from other visualization libraries since it focuses on direct inspection and manipulation of the document object model.

The functionality of D3 can broadly be separated into four categories:

    Loading data
    Binding data to elements
    Transforming elements by inspecting the bound data, and updating the bound properties of the elements
    Transitioning elements in response to user interaction

The transformation of elements based on bound data is the most important category and D3 provides the structure for performing these transformations, while we define how we want those transformations carried out – leaving us in full control of the final output.

D3 is not a traditional visualization framework. Instead of introducing a new graphical grammar, D3’s authors choose to solve a different, smaller problem: the manipulation of documents based on data.

Basically D3 can be thought of as a visualization “kernel” rather than a framework, somewhat resembling other document transformers such as jQuery, CSS and XSLT. These libraries share a common concept of a selection: A set of elements is selected matching the given criteria before applying a set of operations that transforms the selected elements. JavaScript-based selections provide flexibility on top of CSS, since styles can be altered dynamically in response to user interaction and changes to the data.

The designers of D3 choose to adopt the W3C Selectors API for selection; a mini-language consisting of predicates that filter elements by tag (“tag”), class (“.class”), unique identifier (“#id”), attribute (“[name=value]”), containment (“parent child”), adjacency (“before ~ after”), and other facets. Since predicates can be intersected (“.a.b”) and unioned (“.a, .b”) we have a rich and concise method for selection.

D3’s operates on set of elements queried from the current document. Data joins bind data to elements, enabling functional operations that depend on data, and produce enter and exit sub-selections that enables creation and destruction of elements in correspondence with data. Operations are, by default, applied instantaneously, while animated transitions interpolate attributes and styles smoothly over time. The library facilitates event handlers that respond to user input and enable interaction. D3 also provides a number of helper modules that simplify common visualization tasks, such as layout and scales.

For More Information Log on To http://www.codeproject.com/Articles/523444/D3-crash-course

Friday, 11 January 2013

Creating a Pinterest Like Layout in ASP.NET


Pinterest is currently the world’s fastest growing social networking site and famous for the best functioning visual design. Do you love the look and feel of Pinterest? This post explains how to implement the same masonry dynamic layout with infinite scroll in ASP.NET.

Here are the steps to implement it:

1. Download and add jQuery Masonry plugin. It is a dynamic grid layout plugin which arranges elements vertically, positioning each element in the next open spot in the grid and minimizes vertical gaps between elements of varying height.

2. We are going to display product with description in each tile. Here is the structure of Product and ProductRepository class.
   
public class Product {
    public string Url { get; set; }
    public string Description { get; set; }
}

public static class ProductRepository
{
    static List<Product> objList;
    public static IEnumerable<Product> GetData(int pageIndex, int pageSize)
    {
       int startAt = (pageIndex-1) * pageSize;
        objList =new List<Product>();
        Product obj;
        Random r = new Random();
        int n = r.Next(1, 7);  
        for (int i = startAt; i < startAt + pageSize; i++)
        {
            n = r.Next(1, 7);
            obj = new Product();
            obj.Url = String.Format("http://dummyimage.com/150x{1}/{0}{0}{0}/fff.png&text={2}", n, n * 50,i+1);
            obj.Description = "Description of product " + (i+1).ToString();
            objList.Add(obj);
        }
        return objList;
    }
}

In ProductRepository, GetData method takes pageIndex and pageSize parameters and generates dummy data and images of random heights.
HTML Structure:

3. In the aspx page, the head tag structure is as follows:

<head id="Head1" runat="server">
    <title>Pinterest Like Layout</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
    <style type="text/css">
        body
        {
            background-color:#EEEEEE;
        }
        #imgLoad
        {
            position:fixed;
            bottom:0; 
            left:40%;
            display:none;
        }
        .box
        {
            margin: 5px;
            padding: 10px;
            background-color:#FFFFFF;
            box-shadow: 0 1px 3px rgba(34, 25, 25, 0.4);
        }
    </style>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.masonry.min.js" type="text/javascript"></script>
</head>

4. To display products, we use Repeater control:
   
<div id="container" class="transitions-enabled infinite-scroll clearfix">
       <asp:Repeater ID="Repeater1" runat="server">
           <ItemTemplate>
               <div class="box">
                   <img src="<%# Eval("Url") %>" />
                   <p><%# Eval("Description") %></p>
               </div>
           </ItemTemplate>
       </asp:Repeater>
   </div>
   <div id="imgLoad">
       <img src="http://i.imgur.com/6RMhx.gif" />
   </div>
Dynamic Grid Layout:

5. To bind repeater on Page_Load:

Repeater1.DataSource = ProductRepository.GetData(1, 25);
Repeater1.DataBind();

Now, the product is displayed in normal order. If there is variance in each tile height then there is unnecessary blank space between rows. For dynamic grid layout, the following javascript code is used:
   
var $container = $('#container');

$container.imagesLoaded(function () {
    $container.masonry({
        itemSelector: '.box',
        columnWidth: 100,
        isAnimated: true
    });
});

You can see the products are reordered to minimize vertical spacing.
Infinite Scrolling:

6. To implement infinite scrolling, lets create a webmethod on aspx side:
   
[WebMethod]
   public static IEnumerable<Product> GetData(int pageNo, int pageSize)
   {
      
       return ProductRepository.GetData(pageNo, pageSize);
   }

We call this method using jQuery ajax on scrolling, add products dynamically and reorder products
   
var pageNo = 1,pageSize = 25;
 $(window).scroll(function () {
               if ($(window).scrollTop() == $(document).height() - $(window).height() && !($('#imgLoad').is(':visible'))) {
                   loadMore();
               }
           });

           function loadMore() {
               $('#imgLoad').show();
               $.ajax({
                   type: "POST",
                   url: "Default.aspx/GetData",
                   data: JSON.stringify({ pageNo: pageNo + 1, pageSize: pageSize }),
                   dataType: "json",
                   contentType: "application/json",
                   complete: function (response) {                     
                       $('#imgLoad').hide();
                   },
                   success: function (response) {
                       if (response.d.length > 0) {
                           var ctrls = [];
                           for (var i = 0; i < response.d.length; i++) {
                               ctrls.push('<div class="box"> <img src="' + response.d[i].Url + '" /><p>' + response.d[i].Description + '</p></div>');
                           }
                           var $newElems = $(ctrls.join(''));
                           $container.append($newElems);
                           $newElems.css({ opacity: 0 });
                           $newElems.imagesLoaded(function () {
                               // show elems now they're ready
                               $newElems.css({ opacity: 1 });
                               $container.masonry('appended', $newElems, true);
                           });
                           pageNo++;
                       }
                   }
               });