Showing posts with label Create WCF Service. Show all posts
Showing posts with label Create WCF Service. Show all posts

Friday, 16 June 2017

Get AD User Using WCF Service and Ajax Call

1. Create WCF Service Application Project

2. Copy below code and paste in IService1 interface class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ActiveDirectoryDetails
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetADUsers/?domain={domain}&userid={userid}&password={password}")]
        List<Users> GetADUsers(string domain, string userid, string password);
    }

    [DataContract]
    public class Users
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string MiddleName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public string FullName { get; set; }
        [DataMember]
        public string LogonName { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public string Department { get; set; }
        [DataMember]
        public string Designation { get; set; }
        [DataMember]
        public string Company { get; set; }
        [DataMember]
        public string GroupName { get; set; }
        [DataMember]
        public string Manager { get; set; }
        [DataMember]
        public string Reporting { get; set; }
        [DataMember]
        public string MobileNumber { get; set; }
        [DataMember]
        public string Status { get; set; }
        [DataMember]
        public string PostalAddresses { get; set; }
        [DataMember]
        public string Country { get; set; }
        [DataMember]
        public string StateProvince { get; set; }
        [DataMember]
        public string City { get; set; }
        [DataMember]
        public string ZIPPostalCode { get; set; }
        [DataMember]
        public string HomeAddress { get; set; }
        [DataMember]
        public string StreetAddress { get; set; }
        [DataMember]
        public string CountryAbbreviation { get; set; }
        [DataMember]
        public string HomePhone { get; set; }
        [DataMember]
        public string OfficeLocation { get; set; }
        [DataMember]
        public string ExtensionName { get; set; }
        [DataMember]
        public string OtherEMailAddress { get; set; }
        [DataMember]
        public string OtherMobileNumber { get; set; }

    }


}


3. Copy below code and paste in Service1 class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.DirectoryServices;
//using Microsoft.Web.Hosting.Administration;
namespace ActiveDirectoryDetails
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {

        public List<Users> GetADUsers(string domain, string userid, string password)
        {
            List<Users> lstADUsers = new List<Users>();
            try
            {
                string domainName = domain;
                DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + domainName, null, null);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";
                searchRoot.Username = userid;
                searchRoot.Password = password;
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");
                search.PropertiesToLoad.Add("department");
                search.PropertiesToLoad.Add("manager");
                search.PropertiesToLoad.Add("userAccountControl");
                search.PropertiesToLoad.Add("company");
                search.PropertiesToLoad.Add("givenName");
                search.PropertiesToLoad.Add("sn");
                search.PropertiesToLoad.Add("c");
                search.PropertiesToLoad.Add("co");
                search.PropertiesToLoad.Add("homePostalAddress");
                search.PropertiesToLoad.Add("l");
                search.PropertiesToLoad.Add("postalCode");
                search.PropertiesToLoad.Add("st");
                search.PropertiesToLoad.Add("streetAddress");
                search.PropertiesToLoad.Add("postalAddress");
                search.PropertiesToLoad.Add("homePhone");
                search.PropertiesToLoad.Add("mobile");
                search.PropertiesToLoad.Add("middleName");
                search.PropertiesToLoad.Add("Title");
                search.PropertiesToLoad.Add("directReports");
                search.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                search.PropertiesToLoad.Add("extensionName");
                search.PropertiesToLoad.Add("otherMailbox");
                search.PropertiesToLoad.Add("otherMobile");
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        Users objSurveyUsers = new Users();
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname"))
                        {
                            objSurveyUsers.LogonName = (String)result.Properties["samaccountname"][0];
                        }
                        if (result.Properties.Contains("mail"))
                        {
                            objSurveyUsers.Email = (String)result.Properties["mail"][0];
                        }
                        if (result.Properties.Contains("displayname"))
                        {
                            objSurveyUsers.FullName = (String)result.Properties["displayname"][0];
                        }
                        if (result.Properties.Contains("department"))
                        {
                            objSurveyUsers.Department = (String)result.Properties["department"][0];
                        }
                        if (result.Properties.Contains("manager"))
                        {
                            objSurveyUsers.Manager = (String)result.Properties["manager"][0];
                        }

                        if (result.Properties.Contains("userAccountControl"))
                        {

                            objSurveyUsers.Status = IsActive(Convert.ToInt32((int)result.Properties["userAccountControl"][0]));
                        }
                        if (result.Properties.Contains("givenName"))
                        {

                            objSurveyUsers.FirstName = (String)result.Properties["givenName"][0];
                        }
                        if (result.Properties.Contains("usergroup"))
                        {

                            objSurveyUsers.GroupName = (String)result.Properties["usergroup"][0];
                        }
                        if (result.Properties.Contains("sn"))
                        {

                            objSurveyUsers.LastName = (String)result.Properties["sn"][0];
                        }
                        if (result.Properties.Contains("c"))
                        {

                            objSurveyUsers.CountryAbbreviation = (String)result.Properties["c"][0];
                        }
                        if (result.Properties.Contains("co"))
                        {

                            objSurveyUsers.Country = (String)result.Properties["co"][0];
                        }
                        if (result.Properties.Contains("homePostalAddress"))
                        {

                            objSurveyUsers.HomeAddress = (String)result.Properties["homePostalAddress"][0];
                        }
                        if (result.Properties.Contains("l"))
                        {

                            objSurveyUsers.City = (String)result.Properties["l"][0];
                        }
                        if (result.Properties.Contains("postalCode"))
                        {

                            objSurveyUsers.ZIPPostalCode = (String)result.Properties["postalCode"][0];
                        }
                        if (result.Properties.Contains("st"))
                        {

                            objSurveyUsers.StateProvince = (String)result.Properties["st"][0];
                        }
                        if (result.Properties.Contains("streetAddress"))
                        {

                            objSurveyUsers.StreetAddress = (String)result.Properties["streetAddress"][0];
                        }
                        if (result.Properties.Contains("postalAddress"))
                        {

                            objSurveyUsers.PostalAddresses = (String)result.Properties["postalAddress"][0];
                        }
                        if (result.Properties.Contains("homePhone"))
                        {

                            objSurveyUsers.HomePhone = (String)result.Properties["homePhone"][0];
                        }
                        if (result.Properties.Contains("mobile"))
                        {

                            objSurveyUsers.MobileNumber = (String)result.Properties["mobile"][0];
                        }
                        if (result.Properties.Contains("middleName"))
                        {

                            objSurveyUsers.MiddleName = (String)result.Properties["middleName"][0];
                        }
                        if (result.Properties.Contains("Title"))
                        {

                            objSurveyUsers.Designation = (String)result.Properties["Title"][0];
                        }
                        if (result.Properties.Contains("directReports"))
                        {

                            objSurveyUsers.Reporting = (String)result.Properties["directReports"][0];
                        }
                        if (result.Properties.Contains("physicalDeliveryOfficeName"))
                        {

                            objSurveyUsers.OfficeLocation = (String)result.Properties["physicalDeliveryOfficeName"][0];
                        }
                        if (result.Properties.Contains("extensionName"))
                        {

                            objSurveyUsers.ExtensionName = (String)result.Properties["extensionName"][0];
                        }
                        if (result.Properties.Contains("otherMailbox"))
                        {

                            objSurveyUsers.OtherEMailAddress = (String)result.Properties["otherMailbox"][0];
                        }
                        if (result.Properties.Contains("otherMobile"))
                        {

                            objSurveyUsers.OtherMobileNumber = (String)result.Properties["otherMobile"][0];
                        }
                        if (result.Properties.Contains("company"))
                        {

                            objSurveyUsers.Company = (String)result.Properties["company"][0];
                        }

                        lstADUsers.Add(objSurveyUsers);

                    }
                }
            }
            catch (Exception ex)
            {

            }
            return lstADUsers;
        }
        public string IsActive(int value)
        {
            string status = string.Empty;
            if (value == 66050)
            {
                status = "DeActive";
            }
            else
            {
                status = "Active";
            }
            return status;
        }
    }
}



4. Copy below web.config code in your web.config



<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
 
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

    <services>

      <service name="ActiveDirectoryDetails.Service1" behaviorConfiguration="ServiceBehaviour">

        <endpoint address ="" binding="webHttpBinding" contract="ActiveDirectoryDetails.IService1" behaviorConfiguration="web">

        </endpoint>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehaviour">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="1" />

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>
  </system.webServer>

</configuration>


5. Create your Client Application and paste below Ajax Call Method



    <script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
      GetUsersDetails();
      function GetUsersDetails() {
          $.ajax({
              url: "http://localhost:80/Service1.svc/GetADUsers/?domain=sfsd&userid=wjrkj&password=4728346",
              data: {
                  format: 'json'
              },
              type: 'GET',
              dataType: 'json',
              success: function (data) {
                  console.log(data.GetADUsersResult);
              }, error: function () {
                  console.log("Error....");
              }
          });
      }
});

</script>
4. Finally below will be result