Solved

Object reference not set to an instance of an object.

Posted on 2011-03-19
12
579 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
  • 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
 
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
What is MicroStrategy.NET? 2 47
creating a flowchart from an algorithm 5 24
Windows Service with UDP 2 28
Exception in Log4Net 1 20
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…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now