Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Monday, 16 January 2012

Count Number of Visitors in WebSite using ASP.Net and C#

Write Code in Global.asax file


<%@ Application Language="C#" %>

<script runat="server">
    public static int count = 0;
    void Application_Start(object sender, EventArgs e) 
    {
        Application["myCount"] = count; 
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
 

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e) 
    {
        count = Convert.ToInt32(Application["myCount"]); Application["myCount"] = count + 1;
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }
       
</script>

.CS Code:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Hitcounter : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int a;
         a = Convert.ToInt32((Application["myCount"]));
          Label1.Text = Convert.ToString(a);
        if (a < 10)
            Label1.Text = "000" + Label1.Text;
        else if (a < 100)
            Label1.Text = "00" + Label1.Text;
        else if (a < 1000)
            Label1.Text = "0" + Label1.Text;
    }
}

Script Used in PHP and .NET for Google Custom Search

 <!-- Google CSE Search Box Begins  -->
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form id="cref" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="http://www.guha.com/cref_cse.xml" />
  <input type="text" name="q" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cref"></script>
<!-- Google CSE Search Box Ends -->

Sunday, 15 January 2012

How to Build a Distance Finder with Google Maps API

Google Maps is a free web mapping service application provided by Google. It offers lots of cool features (showing various map types, plotting points, showing routes, geocoding addresses). You can also add all these features to your website using the Google Maps APIs provided by Google. In this tutorial I will show you how to add some of these features to your site. I will be using the Google Maps Javascript API v3(the newest version).

What are we going to build?

We’ll make a distance finder. We’ll add a Google map to our site, plot two points on it (the user will be able to choose the addresses for these points), compute the distance between them and show the quickest route between them.
You can see the demo of application here. Also, you can download the source code using this link.

Prerequisites

The first thing you need to do in order to use the API from Google is requesting an API key. You can do this here. It’s easy and free!

Creating the web form for getting the two addresses

We’ll create a simple html form for the user to write the two addresses. We’ll add two input boxes and a button to the form. When the user presses the “Show” button, the map with the two locations will be shown.
Here’s the code for this:

<table align="center" valign="center">
<tr>
   <td colspan="7" align="center"><b>Find the distance between two locations</b></td>
</tr>
<tr>
   &nbsp;
</tr>
<tr>
   <td>First address:</td>
   &nbsp;
   <input name="<span class=" type="text" />address1" id="address1" size="50"/>
   &nbsp;
   <td>Second address:</td>
   &nbsp;
   <input name="<span class=" type="text" />address2" id="address2" size="50"/>
</tr>
<tr>
   &nbsp;
</tr>
<tr>
   <td colspan="7" align="center"><input type="button" value="Show" onclick="initialize();"/></td>
</tr>
</table>
The ‘initialize’ JavaScript function will be called when pressing the button. The function will show the map. In the next section I’ll show you how.
We also need to add a div tag to our page, where the map will be shown:
<div id="map_canvas" style="width:70%; height:54%"></div>
 
<div style="width:100%; height:10%" id="distance_direct"></div>
<div style="width:100%; height:10%" id="distance_road"></div>

Showing the map

The first thing we need to do is to find the coordinates (latitude and longitude) for the two addresses. 
Luckily, Google Maps will help us! Here’s what we have to do:
We’ll use the geocoder object for this. First, we’ll have to create a new geocoder object.

geocoder = new google.maps.Geocoder();
 
address1 = document.getElementById("address1").value;
address2 = document.getElementById("address2").value;
Then, we’ll use the following code to call the geocode method on the 
geocoder object. We’ll pass it the addresses one by one and save the 
results in the variables called location1 and location2 (these will hold
the coordinates of the two addresses). 
 
if (geocoder)
{
   geocoder.geocode( { 'address': address1}, function(results, status)
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         //location of first address (latitude + longitude)
         location1 = results[0].geometry.location;
      } else
      {
         alert("Geocode was not successful for the following reason: " + status);
      }
   });
   geocoder.geocode( { 'address': address2}, function(results, status)
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         //location of second address (latitude + longitude)
         location2 = results[0].geometry.location;
         // calling the showMap() function to create and show the map
         showMap();
      } else
      {
        alert("Geocode was not successful for the following reason: " + status);
      }
   });
} 
You will notice that we’ve called the showMap() function when the coordinates for the second address are retrieved. This function will set the options for the map and show it.
We’ll now compute the coordinates for the center of the map. The center point will be between our two points.

latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
 
Next, we’ll show the map. We have to create a new map object and pass it
 some parameters (set using the mapOptions variable): the zoom level, 
the center and the type of the map. 
var mapOptions =
{
   zoom: 1,
   center: latlng,
   mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
 
The next thing we’ll do is to show the quickest route between our locations. We’ll use a DirectionsService object from google maps for this. Here’s how the code looks:

directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(
{
   suppressMarkers: true,
   suppressInfoWindows: true
});
directionsDisplay.setMap(map);
var request = {
   origin:location1,
   destination:location2,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status)
{
   if (status == google.maps.DirectionsStatus.OK)
   {
      directionsDisplay.setDirections(response);
      distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
      distance += "The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
      document.getElementById("distance_road").innerHTML = distance;
   }
});

We’ve first created the objects we need. We then set some options for displaying the route, we’ve chosen not to show markers and info boxes (we’ll create our own ones);
suppressMarkers: true,
suppressInfoWindows: true

We’ve created a request object and set the origin and destination for the route and also the travel mode:

var request = {
   origin:location1,
   destination:location2,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};
 
We’ve then called the route function and obtained a response from the 
server. Using this response we’ve plotted the route on the map and 
written some info (the total distance and aproximative driving time) in 
one of the divs we’ve created: 
directionsDisplay.setDirections(response);
distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
distance += "The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
document.getElementById("distance_road").innerHTML = distance;

 We’ll also show a line between our points and compute the distance between them (the distance on a straight line, in kilometers). To show a line we’ll use a Polyline object from google maps and set some options for it (the map it belongs to, the path, the width, the opacity and the color):
var line = new google.maps.Polyline({
   map: map,
   path: [location1, location2],
   strokeWeight: 7,
   strokeOpacity: 0.8,
   strokeColor: "#FFAA00"
}); 
We’ll now compute the distance between two points using their 
coordinates and show the result inside the other div tag we’ve created.

var R = 6371;
var dLat = toRad(location2.lat()-location1.lat());
var dLon = toRad(location2.lng()-location1.lng());
var dLat1 = toRad(location1.lat());
var dLat2 = toRad(location2.lat());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(dLat1) * Math.cos(dLat1) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

document.getElementById("distance_direct").innerHTML =
 "The distance between the two points (in a straight line) is: "+d;
The last thing we’ll do is show a marker and an info window for each location. We’ll create two marker objects (the options we’ll set are: the map it belongs to, the coordinates and a title):
var marker1 = new google.maps.Marker({
   map: map,
   position: location1,
   title: "First location"
});

var marker2 = new google.maps.Marker({
   map: map,
   position: location2,
   title: "Second location"
});
Next, we’ll create variables to hold the texts to print in the info 
windows, create two info window objects (we’ll add the texts to them 
using the content option) and we’ll add two event listeners which will 
show the appropriate info window when the user clicks on the markers:

// create the text to be shown in the infowindows

var text1 = '
<div id="content">'+</div>
  '<h1 id="firstHeading">First location'+
  '<div id="bodyContent">'+
  '<p>Coordinates: '+location1+'</p>'+
  '<p>Address: '+address1+'</p>'+
  '</div>'+
  '</div>';

var text2 = '
<div id="content">'+</div>
  '<h1 id="firstHeading">Second location'+
  '<div id="bodyContent">'+
  '<p>Coordinates: '+location2+'</p>'+
  '<p>Address: '+address2+'</p>'+
  '</div>'+
  '</div>';

// create info boxes for the two markers
var infowindow1 = new google.maps.InfoWindow({
   content: text1
});
var infowindow2 = new google.maps.InfoWindow({
   content: text2
});

// add action events so the info windows will be shown when the marker is clicked
google.maps.event.addListener(marker1, 'click', function() {
   infowindow1.open(map,marker1);
});

google.maps.event.addListener(marker2, 'click', function() {
   infowindow2.open(map,marker2);
});
 
And we’re done! We now have a distance finder! Let me know if you have any questions!
 
 


Google Maps is a free web mapping service application provided by Google. It offers lots of cool features (showing various map types, plotting points, showing routes, geocoding addresses). You can also add all these features to your website using the Google Maps APIs provided by Google. In this tutorial I will show you how to add some of these features to your site. I will be using the Google Maps Javascript API v3(the newest version).

What are we going to build?

We’ll make a distance finder. We’ll add a Google map to our site, plot two points on it (the user will be able to choose the addresses for these points), compute the distance between them and show the quickest route between them.
You can see the demo of application here. Also, you can download the source code using this link.

Prerequisites

The first thing you need to do in order to use the API from Google is requesting an API key. You can do this here. It’s easy and free!

Creating the web form for getting the two addresses

We’ll create a simple html form for the user to write the two addresses. We’ll add two input boxes and a button to the form. When the user presses the “Show” button, the map with the two locations will be shown.
Here’s the code for this:

<table align="center" valign="center">
<tr>
   <td colspan="7" align="center"><b>Find the distance between two locations</b></td>
</tr>
<tr>
   &nbsp;
</tr>
<tr>
   <td>First address:</td>
   &nbsp;
   <input name="<span class=" type="text" />address1" id="address1" size="50"/>
   &nbsp;
   <td>Second address:</td>
   &nbsp;
   <input name="<span class=" type="text" />address2" id="address2" size="50"/>
</tr>
<tr>
   &nbsp;
</tr>
<tr>
   <td colspan="7" align="center"><input type="button" value="Show" onclick="initialize();"/></td>
</tr>
</table>
The ‘initialize’ JavaScript function will be called when pressing the  button. The function will show the map. In the next section I’ll show  you how.
We also need to add a div tag to our page, where the map will be shown:
<div id="map_canvas" style="width:70%; height:54%"></div>
 
<div style="width:100%; height:10%" id="distance_direct"></div>
<div style="width:100%; height:10%" id="distance_road"></div>

Showing the map

The first thing we need to do is to find the coordinates (latitude and longitude) for the two addresses. Luckily, Google Maps will help us! Here’s what we have to do:
We’ll use the geocoder object for this. First, we’ll have to create a new geocoder object.

geocoder = new google.maps.Geocoder();
 
address1 = document.getElementById("address1").value;
address2 = document.getElementById("address2").value;
Then, we’ll use the following code to call the geocode method on the 
geocoder object. We’ll pass it the addresses one by one and save the 
results in the variables called location1 and location2 (these will hold
the coordinates of the two addresses). 
 
if (geocoder)
{
   geocoder.geocode( { 'address': address1}, function(results, status)
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         //location of first address (latitude + longitude)
         location1 = results[0].geometry.location;
      } else
      {
         alert("Geocode was not successful for the following reason: " + status);
      }
   });
   geocoder.geocode( { 'address': address2}, function(results, status)
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         //location of second address (latitude + longitude)
         location2 = results[0].geometry.location;
         // calling the showMap() function to create and show the map
         showMap();
      } else
      {
        alert("Geocode was not successful for the following reason: " + status);
      }
   });
} 
You will notice that we’ve called the showMap() function when the  coordinates for the second address are retrieved. This function will set  the options for the map and show it.
We’ll now compute the coordinates for the center of the map. The center point will be between our two points.

latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
 
Next, we’ll show the map. We have to create a new map object and pass it
 some parameters (set using the mapOptions variable): the zoom level, 
the center and the type of the map. 
var mapOptions =
{
   zoom: 1,
   center: latlng,
   mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
 
The next thing we’ll do is to show the quickest route between our locations. We’ll use a DirectionsService object from google maps for this. Here’s how the code looks:

directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(
{
   suppressMarkers: true,
   suppressInfoWindows: true
});
directionsDisplay.setMap(map);
var request = {
   origin:location1,
   destination:location2,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status)
{
   if (status == google.maps.DirectionsStatus.OK)
   {
      directionsDisplay.setDirections(response);
      distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
      distance += "The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
      document.getElementById("distance_road").innerHTML = distance;
   }
});

We’ve first created the objects we need. We then set some options for displaying the route, we’ve chosen not to show markers and info boxes (we’ll create our own ones);
suppressMarkers: true,
suppressInfoWindows: true

We’ve created a request object and set the origin and destination for the route and also the travel mode:

var request = {
   origin:location1,
   destination:location2,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};
 
We’ve then called the route function and obtained a response from the 
server. Using this response we’ve plotted the route on the map and 
written some info (the total distance and aproximative driving time) in 
one of the divs we’ve created: 
directionsDisplay.setDirections(response);
distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
distance += "The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
document.getElementById("distance_road").innerHTML = distance;

 We’ll also show a line between our points and compute the distance between them (the distance on a straight line, in kilometers). To show a line we’ll use a Polyline object from google maps and set some options for it (the map it belongs to, the path, the width, the opacity and the color):
var line = new google.maps.Polyline({
   map: map,
   path: [location1, location2],
   strokeWeight: 7,
   strokeOpacity: 0.8,
   strokeColor: "#FFAA00"
}); 
We’ll now compute the distance between two points using their 
coordinates and show the result inside the other div tag we’ve created.

var R = 6371;
var dLat = toRad(location2.lat()-location1.lat());
var dLon = toRad(location2.lng()-location1.lng());
var dLat1 = toRad(location1.lat());
var dLat2 = toRad(location2.lat());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(dLat1) * Math.cos(dLat1) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

document.getElementById("distance_direct").innerHTML = "The distance between the two points (in a straight line) is: "+d;
The last thing we’ll do is show a marker and an info window for each  location. We’ll create two marker objects (the options we’ll set are:  the map it belongs to, the coordinates and a title): 
var marker1 = new google.maps.Marker({
   map: map,
   position: location1,
   title: "First location"
});

var marker2 = new google.maps.Marker({
   map: map,
   position: location2,
   title: "Second location"
});
Next, we’ll create variables to hold the texts to print in the info 
windows, create two info window objects (we’ll add the texts to them 
using the content option) and we’ll add two event listeners which will 
show the appropriate info window when the user clicks on the markers:

// create the text to be shown in the infowindows

var text1 = '
<div id="content">'+</div>
  '<h1 id="firstHeading">First location'+
  '<div id="bodyContent">'+
  '<p>Coordinates: '+location1+'</p>'+
  '<p>Address: '+address1+'</p>'+
  '</div>'+
  '</div>';

var text2 = '
<div id="content">'+</div>
  '<h1 id="firstHeading">Second location'+
  '<div id="bodyContent">'+
  '<p>Coordinates: '+location2+'</p>'+
  '<p>Address: '+address2+'</p>'+
  '</div>'+
  '</div>';

// create info boxes for the two markers
var infowindow1 = new google.maps.InfoWindow({
   content: text1
});
var infowindow2 = new google.maps.InfoWindow({
   content: text2
});

// add action events so the info windows will be shown when the marker is clicked
google.maps.event.addListener(marker1, 'click', function() {
   infowindow1.open(map,marker1);
});

google.maps.event.addListener(marker2, 'click', function() {
   infowindow2.open(map,marker2);
});
 
And we’re done! We now have a distance finder! Let me know if you have any questions!
 
 


How to make a Web Browser in C # 2010

Drag the following controls to the form:
A webbrowser, a textbox, and 6 buttons:
Organize the controls on the form like shown in the picture below.
Now we will add the codes to the buttons: Double click on each button before adding the code for each of them:
Go Button: double click then add the following highlighted code:
private void button1_Click(object sender, EventArgs e)
{
//navigate the webbrower to the url typed in textBox1
webBrowser1.Navigate(textBox1.Text);
}

Home Button: double click then add the following highlighted code:
private void button4_Click(object sender, EventArgs e)
{
//Navigate the browser to the home page - in this case it is google.com
webBrowser1.Navigate("www.google.com");
}

Refresh Button: double click then add the following highlighted code:
private void button2_Click(object sender, EventArgs e)
{
//Refreshes the page
webBrowser1.Refresh();
}

Stop Button: double click then add the following highlighted code:
private void button3_Click(object sender, EventArgs e)
{
// Stops the browser navigating
webBrowser1.Stop();
}

Back Button: double click then add the following highlighted code:
private void button5_Click(object sender, EventArgs e)
{
//The browser will go back to the last navigated page if Avalaible
webBrowser1.GoBack();
}

Forward Button: double click then add the following highlighted code:
private void button6_Click(object sender, EventArgs e)
{
webBrowser1.GoForward();
}

We will now add the last piece of code to the project, the following code will return the page url to the text box after navigating is completed.
Document Completed event: add the following hightlighted code
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
textBox1.Text = webBrowser1.Url.ToString();
}

How To Implement Captcha in Asp.Net


How To Implement Captcha in Asp.Net

Key features of Captcha ASP.NET 4.0 Server Control:

* Ability to set any size for your captcha

* Set alphabet and string length

* Set the level of noise and line noise

* Timer to make your captcha obsolete after specified period of time

* Set various fonts for your captcha


Planned enhancements:

* Create "math" captchas, which offers users to solve simple formulas (like "15 + 23 =") instead of random string.
(function already implemented in beta release)
* Return error codes for various reasons of user input rejection
* Case sensitive captcha (see voting for this feature)


Installation instruction:

1. Unzip the downloaded file.

2. Copy MSCaptcha.dll and MSCaptcha.xml files to your /bin application directory.

3. In your application, add reference to mscaptcha.dll file.

4. Modify your web.config file, by adding this line to section:
<<span style="color: #A31515; font-size: small;">add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>

5. Add MSCaptcha control to your Visual Studio toolbox (optional)

6. That's it!


Example of use:

1. Add line to your .aspx file:
<%<span style="color: #0000ff; font-size: small;">@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" %>

2. Where needed, add the control itself:
<<span style="color: #A31515; font-size: small;">cc1:CaptchaControl ID="ccJoin" runat="server" CaptchaBackgroundNoise="none" CaptchaLength="5" CaptchaHeight="60" CaptchaWidth="200" CaptchaLineNoise="None" CaptchaMinTimeout="5" CaptchaMaxTimeout="240" />

3. Put a textbox somewhere in your page where your user must enter what he sees in your captcha. Put this code (this example is in C#) to validate user input:

ccJoin.ValidateCaptcha(txtCap.Text);
if (!ccJoin.UserValidated)
{
//Inform user that his input was wrong ...
return;
}

In this particular example the ccJoin is the name of the Captcha control, the txtCap is the textbox where user entered what he sees in Captcha.


Essential parameters:

* CaptchaBackgroundNoise - either "none", "low", "medium", "high" or "extreme" - the amount of noise to add to the picture to make it harder for OCR ("optical character recognition") software to recognize. Beware that this also affects how your users will be able to read and understand its content. So our recommendation is to set it to "none" and only increase the level if you'll notice the presence of automatically registered bots on your site.

* CaptchaLength - how many symbols captcha will contain. The recommended value is around 4-5, and you should increase it only if have a real problem with spammers.

* CaptchaHeight and CaptchaWidth - the height and width (in pixels) of the generated image.

* CaptchaLineNoise - adds lines to your image to further harden the OCR software work. The recommended starting value is "None", although you can increase it later.

* CaptchaMaximeout - timeout in seconds, after which your current captcha will become invalid. It is recommended to keep this value relatively high and refresh (using AJAX, for example) your captcha when it is about to become invalid.

* CaptchaMinTimeout - minimal time period in seconds for filling the captcha response. This means - if you set the CaptchaLength to 5 seconds, any input entered in first 5 seconds after Captcha's generation will be rejected.

* CaptchaChars - the string of characters to be used for Captcha generation. The default is "ABCDEFGHJKLMNPQRSTUVWXYZ23456789". We recommend to avoid using chars like O, 0, 1 and I because using different fonts they may confuse your users.

Sunday, 25 December 2011

Data Types in .Net

Value Types
Reference Types
allocated on stack
allocated on heap
a value type variable contains the data itself
reference type variable contains the address of memory location where data is actually stored.
when you copy a value type variable to another one, the actual data is copied and each variable can be independently manipulated.
when copying a reference type variable to another variable, only the memory address is copied. Both variables will still point to the same memory location, which means, if you change one variable, the value will be changed for the other variable too.
integer, float, boolean, double,struct etc are value types.
string and object,class are reference types.