[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 591
  • Last Modified:

Object reference not set to an instance of an object.

I was trying a simple AD retrieval but i throws exception,can some one enlighten me what am missing ?

namespace ADTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

            Console.WriteLine("Active users:");
            string EmailID = string.Empty;
            string phoneNo = string.Empty;
            foreach (SearchResult result in searcher.FindAll())
            {
                phoneNo = result.GetDirectoryEntry().Properties["telephonenumber"].Value.ToString();
                EmailID = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
            } 

            Console.ReadKey();
        }

    }
}

Open in new window

0
Sha1395
Asked:
Sha1395
  • 7
  • 3
  • 2
2 Solutions
 
exceterCommented:
Did you validated for existance of data ?
I suppose that it returns Null - searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
0
 
crysallusCommented:
Have you tried running it with a debugger? It should tell you which line is throwing the exception.

My guess would be that one of the 2 properties doesn't exist, or you haven't typed the property name in properly, but I'm no expert on AD.
0
 
Sha1395Author Commented:
It throws here

 EmailID = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
crysallusCommented:
Try this:

foreach (SearchResult result in searcher.FindAll())
{
    phoneNo = result.GetDirectoryEntry().Properties["telephonenumber"].Value.ToString();
    var mail = result.GetDirectoryEntry().Properties["mail"];
    if (mail != null)
        EmailID = mail.Value.ToString();
} 

Open in new window

0
 
Sha1395Author Commented:
Hey crysallus

Just debug the code its getting null value and just came back you already provide the solution.Thanks a lot
0
 
Sha1395Author Commented:
crysallus modified your code little bit

var mail = result.GetDirectoryEntry().Properties["mail"].Value;
                if(mail!=null)
                {
                    EmailID = mail.ToString();
                }

Open in new window


0
 
Sha1395Author Commented:
crysallus do i need to do for all the fields ? its qjuite weird ,is this any smart way i can check null value and am going to insert in to my db.
0
 
exceterCommented:
In that case better to put validation for both parameters:

try{
foreach (SearchResult result in searcher.FindAll())
{
    if (result.GetDirectoryEntry().Properties["telephonenumber"] != null)
          phoneNo = result.GetDirectoryEntry().Properties["telephonenumber"].Value.ToString();
    var mail = result.GetDirectoryEntry().Properties["mail"];
    if ( result.GetDirectoryEntry().Properties["mail"] != null )
    EmailID = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
}
}
0
 
Sha1395Author Commented:
Any one have any idea how to store all the active users in Data table in SQL ?

Right now i have created a table column EmployeeNo,Phone,Email Id And Name.But i am trying to store in data table and do a periodic update.

0
 
crysallusCommented:
As exceter pretty much said, it would be best to do this for all fields if there's any chance of null's being returned.

If you have to repeat this null checking code for a large amount of fields, you could put it into a separate method. i.e. (I hope I got the type right for the argument, and I haven't tested this by the way, I hope it works...!)

private string GetProperty(PropertyValueCollection propCol)
{
    if (propCol != null && propCol.Value != null)
        return propCol.Value.ToString();
    else
        return "";
}

Open in new window

And then your code above becomes:

foreach (SearchResult result in searcher.FindAll())
{
    phoneNo = GetProperty(result.GetDirectoryEntry().Properties["telephonenumber"]);
    EmailID = GetProperty(result.GetDirectoryEntry().Properties["mail"]);
} 

Open in new window

and so on for any more properties that you need, meaning you avoid the need to rewrite the null checking code for each one.
0
 
Sha1395Author Commented:
Thanks a lot for your great help here is my initial code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Data.SqlClient; 

namespace ADTest1
{
    class Program
    {
        static void Main(string[] args)
        {
           
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.Filter = "(&(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

           // Console.WriteLine("Active users:");
            string EmailID = string.Empty;
            string phoneNo = string.Empty;
            string AccountName = String.Empty;
            string EmployeeNo = string.Empty;
            foreach (SearchResult result in searcher.FindAll())
            {
                var Phone = result.GetDirectoryEntry().Properties["telephonenumber"].Value;
                if (Phone != null)
                {
                    phoneNo = Phone.ToString();
                    Console.WriteLine(phoneNo);
                }
                //phoneNo = result.GetDirectoryEntry().Properties["telephonenumber"].Value.ToString();
                var mail = result.GetDirectoryEntry().Properties["mail"].Value;
                if(mail!=null)
                {
                    EmailID = mail.ToString();
                    Console.WriteLine(EmailID);
                }

                var Name = result.GetDirectoryEntry().Properties["sAMAccountName"].Value;
                if (Name != null)
                {
                    AccountName = Name.ToString();
                    Console.WriteLine(AccountName);
                }

                var Emply = result.GetDirectoryEntry().Properties["otherpager"].Value;
                if (Emply != null)
                {
                    EmployeeNo = Emply.ToString();
                    Console.WriteLine(EmployeeNo);
                }
               

                //SQl Insert


                System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(your connection string");
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();

                cmd.CommandType = System.Data.CommandType.Text;

                cmd.CommandText = "INSERT ADUser (EmployeeNo,Email,PhoneNo ) VALUES("
                                                  + "'" + EmployeeNo + "'" + ","
                                                   + "'" + EmailID.Replace("'", "''") + "'" + ","
                                                   + "'" + phoneNo + "'" + ")";

                cmd.Connection = sqlConnection1;
                sqlConnection1.Open();
                cmd.ExecuteNonQuery();
                sqlConnection1.Close();

            } 
//
//            Console.ReadKey();
        }

    }
}

Open in new window


It returns only 1000 recrods,i think the max page size its configured 1000 how can i increased in my code ?

Thanks in Advance
0
 
Sha1395Author Commented:
got it

searcher.PageSize = 5000;
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 7
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now