Solved

Object reference not set to an instance of an object.

Posted on 2011-03-19
12
585 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
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

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

728 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