Wednesday, 16 July 2014

Get the Current Goe Location using Google API in HTML

                     In this article we are going to see how to get the current geo location code , using the google API, For this we have to enable the Google GeoCode API service , then click the enable button when the first time browser raises a pop up to show map, To build a map like below one, we have to do the following steps. Use the mouse to zoom in and out

Start wirh HTML and then Javascript,
   <form id="mapform" runat="server">
        <div id="mapcanvas" style="width: 500px; height: 400px"></div>


Create a Div element to place the map.

Next to get the google maps , we need a server call api key from google, for this do the simple three steps.
Go to the

  1. Visit the APIs console at and log in with your Google Account.
  2. Click the Services link from the left-hand menu in the APIs Console, then activate the Geocoding API service.
  3. Once the service has been activated, your API key is available from the API Access page, in the Simple API Access section. Geocoding API applications use the Key for server apps.
Then Use that key in the script call. like below.

<script type="text/javascript" 

    <script type="text/javascript" src=""></script>

Then create a JavaScript to get the current location.
First check whether the Geo location is supported in browser,  for this we can test in navigator.geolocation.
Once it is passed, then bind a callback function, which have a position as input paramter. From the position we can get the coordinates.

Now the Next thing is Draw the map using the Geocodes, so to do this we have to create a Google.Maps.Map instance and Marker.

First pass the latitude and longitude as parameter to a instance. then pass that instance to a options parameter center:, Next get the element tag where to show the map, along with options in Map instance. now use the marker instance to set the map.Next create a infowindow with a content parameter.

 <script type="text/javascript">
        if (navigator.geolocation) {
        else {
            alert("GeoLocation is not supported in your browser");

        function success(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var city = position.coords.locality;
            var myLatlng = new google.maps.LatLng(latitude, longitude);
            var myOptions = {
                center: myLatlng,
                zoom: 12,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "lat: " + latitude + " long: " + longitude

            var infowindow = new google.maps.InfoWindow({ content: "<b>Address</b><br/>                Latitude:" + latitude + "<br /> Longitude:" + longitude + "" });
  , marker);


 From this post you can learn how to get the location of current place using google GeoCode api.

Sunday, 13 July 2014

Validate the User Exist in the ActiveDirectory along with credentials and get the user info using LDAP Connection

In this article we are going to see how to find out whether a user is valid user along with password and get the user information using LDAP Connection, for this First we have to check before whether user in LDAP server.

Many of the configuration details should be needed and need to be understand before given as input.

Name *        :      LDAP
Host *          : {or}
Port *           :    389 { for SSL 636}
Account        :    cn=Manager,dc=example,dc=com
Password     :    secret
Base DN *   :    dc=example,dc=com
Login *         :    uid
LoginPass *  :    UserPassword

From the above input the mandatory fields are metion in * symbol Account is corresponds to the LDAP Account and Password is used to access the LDAP server, First we have to connect the LDAP server using that credentials, then iterate the users present in the server or select the particular user and get there LDAP user distinguished name to get the information of user as attributes.

Some of the LDAP Attributes and there Examples with explanation

CN - Common Name
CN=Jhon Filder.  Actually, this LDAP attribute can be made up from givenName joined to SN.
 'Name' in the LDAP provider.
CN is a mandatory property. 
displayName = Jhon Filder
Get the mail id of the user
DN - also distinguishedName
DN is simply the most important LDAP attribute.
CN=Jay Jamieson, OU= Newport,DC=cp,DC=com
Firstname also called Christian name
Home Folder : connect.  Tricky to configure
name = Jhon Filder.  Exactly the same as CN.
Defines the Active Directory Schema category. For example, objectCategory = Person
objectClass = User.  Also used for Computer, organizationalUnit, even container.  Important top level container.
Office! on the user's General property sheet
Roaming profile path: connect.  Trick to set up
This is a mandatory property, sAMAccountName = name.  The old NT 4.0 logon name, must be unique in the domain. 
If you are using an LDAP provider 'Name' automatically maps to sAMAcountName and CN. The default value is same as CN, but can be given a different value.
SN = Filder. This would be referred to as last name or surname.
Used to disable an account.  A value of 514 disables the account, while 512 makes the account ready for logon.
userPrincipalName =  Often abbreviated to UPN, and looks like an email address.  Very useful for logging on especially in a large Forest.  Note UPN must be unique in the forest.
Examples of Exchange Specific LDAP attributes
Here is where you set the Mail Store
Legacy distinguished name for creating Contacts. In the following example,
Jhon Filder is a Contact in the first administrative group of GUYDOMAIN: /o=GUYDOMAIN/ou=first administrative group/cn=Recipients/cn=Jhon Filder
An easy, but important attribute.  A simple SMTP address is all that is required
mAPIRecipient - FALSE
Indicates that a contact is not a domain user.
Normally this is the same value as the sAMAccountName, but could be different if you wished.  Needed for mail enabled contacts.
Another straightforward field, just the value to:True
Exchange needs to know which server to deliver the mail.  Example:
/o=YourOrg/ou=First Administrative Group/cn=Configuration/cn=Servers/cn=MailSrv
As the name 'proxy' suggests, it is possible for one recipient to have more than one email address.  Note the plural spelling of proxyAddresses.
SMTP:@ e-mail address.  Note that SMTP is case sensitive.  All capitals means the default address.
Displays the contact in the Global Address List.
Country or Region
Company or organization name
Useful category to fill in and use for filtering
Home Phone number, (Lots more phone LDAPs)
l  (Lower case L)
L = Location.  City ( Maybe Office
Important, particularly for printers and computers.
Boss, manager
Mobile Phone number
Usually, User, or Computer
Organizational unit.  See also DN
Force users to change their passwords at next logon
Zip or post code
State, Province or County
First line of address
Office Phone
Enable (512) / disable account (514)

Use can see a list of attributes and there usages along with sample values let we start the coding.

namespace LdapAuth
    public class User
        public string DISTINGUISHEDNAME { set; get; }
        public string UID { getset; }
        public string NAME { getset; }
        public string DISPLAYNAME { getset; }
        public string FIRSTNAME { getset; }
        public string LASTNAME { getset; }
        public string MAIL { getset; }
        public string OU { getset; }    

    public class LdapRequest
        public LdapRequest(string hostName, string baseDn, string ldapAccUser, string ldapAccPassword)
            this.HostName = hostName;
            this.BaseDn = baseDn;
            this.LdapAccUser = ldapAccUser;
            this.LdapAccPassword = ldapAccPassword;

        public string HostName { private set; get; }
        public string BaseDn { set; get; }
        public string LdapAccUser { private set; get; }
        public string LdapAccPassword { private set; get; }

        public User Authenticate(string userName, string password)
            using (var ldap = new LdapConnection(new LdapDirectoryIdentifier(this.HostName)))
                ldap.SessionOptions.ProtocolVersion = 3;

                if (!string.IsNullOrEmpty(LdapAccPassword))
                    ldap.Credential = new NetworkCredential(LdapAccUser, LdapAccPassword);
                ldap.AuthType = AuthType.Basic;

                /* Get the distinguish name of particular user */
                var distinguishname = GetDn(ldap, userName);

                if (distinguishname != null)
                        ldap.AuthType = AuthType.Basic;
                        ldap.Bind(new NetworkCredential(distinguishname, password));
                        /* Get the user attributes  */
                        return GetUser(ldap, distinguishname);
                    catch (DirectoryOperationException ex1)
                    catch (LdapException ex2)
            return null;

        private String GetDn(LdapConnection ldap, String userName)

            var request = new SearchRequest(this.BaseDn, string.Format("uid={0}", userName),                                             SearchScope.Subtree);
            var response = (SearchResponse)ldap.SendRequest(request);

            if (response.Entries.Count > 0)
                return response.Entries[0].DistinguishedName;

            return null;


        private User GetUser(LdapConnection ldap, String dn)
            var request = new SearchRequest(dn, "(objectclass=*)", SearchScope.Base);
            var response = (SearchResponse)ldap.SendRequest(request);
            if (response.Entries.Count > 0)
                return Instance(response.Entries[0]);
            return null;

        private User Instance(SearchResultEntry entry)
            User obj = new User();
            foreach (DictionaryEntry attr in entry.Attributes)
                var name = attr.Key.ToString().ToUpperInvariant();
                var values = (DirectoryAttribute)attr.Value;

                switch (name)
                    case "DISTINGUISHEDNAME":
                        obj.DISTINGUISHEDNAME = values[0].ToString(); 
                    case "UID"
                        obj.UID = values[0].ToString(); 
                    case "CN":
                        obj.NAME = values[0].ToString(); 
                    case "DISPLAYNAME"
                        obj.DISPLAYNAME = values[0].ToString(); 
                    case "GIVENNAME"
                        obj.FIRSTNAME = values[0].ToString(); 
                    case "SN":
                        obj.LASTNAME = values[0].ToString(); 
                    case "MAIL":
                        obj.MAIL = values[0].ToString(); 
                    case "OU":
                        obj.OU = values[0].ToString();
            return obj;


Next call the code form the Application

class App
        static void Main(string[] args)

            var server = "";
            var baseDn = "dc=macrosys,dc=com";
            var domainusername = "cn=root,dc=macrosys,dc=com";
            var domainpassword = "domainpass12*";
            var userName = "chrisbaker";
            var password = "chris#23!";

            var ldap = new LdapRequest(server, baseDn, domainusername, domainpassword);
            var user = ldap.Authenticate(userName, password);

            if (user != null)
                Console.WriteLine("User ID   : " + user.UID);
                Console.WriteLine("Name      : " + user.NAME);
                Console.WriteLine("First name: " + user.FIRSTNAME);
                Console.WriteLine("Last name : " + user.LASTNAME);
                Console.WriteLine("Email ID  : " + user.MAIL);
                Console.WriteLine("Distinguish Name : " + user.DISTINGUISHEDNAME);
                Console.WriteLine("Authorization failed.");



From the above code you can able to validate user existence in LDAP server along with credentials.