Solved

Object reference not set to an instance of an object.

Posted on 2011-03-19
12
584 Views
Last Modified: 2012-05-11
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
Comment
Question by:Sha1395
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
  • 2
12 Comments
 
LVL 3

Expert Comment

by:exceter
ID: 35170436
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
 
LVL 8

Expert Comment

by:crysallus
ID: 35170441
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
 

Author Comment

by:Sha1395
ID: 35170472
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!

 
LVL 8

Expert Comment

by:crysallus
ID: 35170477
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
 

Author Comment

by:Sha1395
ID: 35170480
Hey crysallus

Just debug the code its getting null value and just came back you already provide the solution.Thanks a lot
0
 

Author Comment

by:Sha1395
ID: 35170492
crysallus modified your code little bit

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

Open in new window


0
 

Author Comment

by:Sha1395
ID: 35170496
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
 
LVL 3

Assisted Solution

by:exceter
exceter earned 250 total points
ID: 35170497
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
 

Author Comment

by:Sha1395
ID: 35170516
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
 
LVL 8

Accepted Solution

by:
crysallus earned 250 total points
ID: 35170522
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
 

Author Comment

by:Sha1395
ID: 35171113
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
 

Author Comment

by:Sha1395
ID: 35171132
got it

searcher.PageSize = 5000;
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question