Solved

Object reference not set to an instance of an object.

Posted on 2011-03-19
12
583 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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

789 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