Wednesday, 29 April 2015

How to delete Maintenance plan when you get error message “Exception has been thrown by the target of an invocation (mscorlib)


Use MSDB


Step 1:
Execute the below query to obtain the Maintenance plan name and Id
SELECT NAME, ID FROM MSDB..SYSMAINTPLAN_PLANS

Step 2:
Replace the Id obtained from Step 1 into the below query and delete the entry from log table
DELETE FROM SYSMAINTPLAN_LOG WHERE PLAN_ID=' '

Step 3:
Replace the Id obtained from Step 1 into the below query and delete the entry from subplans table as shown below,
DELETE FROM SYSMAINTPLAN_SUBPLANS WHERE PLAN_ID = ' '

Step 4:
Finally delete the maintenance plan using the below query where ID is obtained from Step1
DELETE FROM SYSMAINTPLAN_PLANS WHERE ID = ' '

Tuesday, 28 April 2015

Active Directory User Details in JSON Format

In the past I have posted series of Active Directory reading and writing operations. Below is a sample query that you can use to get an idea on how to read from an Active Directory group and output into JSON format. I used Group Principal to read from Active Directory Group. I have posted my extended class in one of my previous post which I reuse here as Extended Principal User to read Tel, Fax etc… Otherwise I use principal user to read from active directory. I have created a data table with the column names which I want to print and added Active Directory Group members into this data table.


To create JSON output I used JavaScriptSerializer. I created a new List type Dictionary and added Active Directory members details along with the header. To write into txt file I have used “WriteAllText” with Replace method to replace Unicode character “\u0026”  to “&”. Because any character may be encoded using the unicode escape in JSON and any valid JSON parsing library must be able to interpret those escapes. There are many workarounds available including regex. I have used Replace method in this example.

using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

       public void Read_ActiveDirectory(string filelocation,string ADgroupname)
        {
            string filepath = filelocation;
            string grpname = ADgroupname;
            ctx = new PrincipalContext(ContextType.Domain);
            group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, grpname);
            exprUser = new ExtendedPrincipalUser(ctx);
            prinUser = new UserPrincipal(ctx);
            srch = new PrincipalSearcher(prinUser);

            DataSet dsADCloud = new DataSet("AD");
            DataTable dtUsers = new DataTable("Users");
            dtUsers.Columns.Add("DisplayName");
            dtUsers.Columns.Add("Surname");
            dtUsers.Columns.Add("First_Name");
            dtUsers.Columns.Add("JobTitle");
            dtUsers.Columns.Add("Position");
            dtUsers.Columns.Add("Phone");
            dtUsers.Columns.Add("Mobile");
            dtUsers.Columns.Add("EmailAddress");
            dtUsers.Columns.Add("Department");
            dtUsers.Constraints.Add("UniqueUserId", dtUsers.Columns["UserName"], true);

            if (group != null)
            {
                foreach (Principal p in group.GetMembers(true))
                {
                    prinUser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);
                    exprUser = ExtendedPrincipalUser.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);
                    DataRow drUser = dtUsers.NewRow();
                    if (prinUser.Enabled != false)
                    {
                        try { drUser["DisplayName"] = prinUser.DisplayName.ToString().Trim();  }
                        catch { drUser["DisplayName"] = null; }
                        try { drUser["Surname"] = prinUser.Surname.ToString().Trim();  }
                        catch { drUser["Surname"] = null; }
                        try { drUser["First_Name"] = prinUser.GivenName.ToString().Trim(); }
                        catch { drUser["First_Name"] = null; }
                        try { drUser["JobTitle"] = prinUser.Description.ToString().Trim(); }
                        catch { drUser["JobTitle"] = null; }
                        try { drUser["Position"] = exprUser.jobTitle.ToString().Trim(); }
                        catch { drUser["Position"] = null; }
                        try {drUser["Phone"] = exprUser.VoiceTelephoneNumber.Trim();}
                        catch { drUser["Phone"] = null; }
                        try { drUser["Mobile"] =  exprUser.mobile.ToString().Trim() ; }
                        catch { drUser["Mobile"] = null; }
                        try { drUser["EmailAddress"] = prinUser.EmailAddress.ToString().Trim(); }
                        catch { drUser["EmailAddress"] = null; }
                        try { drUser["Department"] = exprUser.department.ToString().Trim(); }
                        catch { drUser["Department"] = null; }

                        dtUsers.Rows.Add(drUser);
                    }
                }
            }
            dsADCloud.Tables.Add(dtUsers);

            string strExcelPath = System.Configuration.ConfigurationManager.ConnectionStrings[filepath].ConnectionString;
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();    
                    Dictionary<string, object> row;


                    foreach (DataRow dr in dtUsers.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dtUsers.Columns)
                        {
                            row.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(row);
                    }

                    System.IO.File.WriteAllText(strExcelPath, serializer.Serialize(rows).ToString().Replace(@"\u0026", @"&"));
        }



Sample Output:

[{
"DisplayName":"ABC DEF","Surname":"DEF","First_Name":"ABC","JobTitle":"Manager","Position":"Manager","Phone":"123456789","Mobile":"147258369","EmailAddress":"ABCDEF@sampleemail.com","Department":"TEST DEPARTMENT 1"}, {"DisplayName":"GHI JKL","Surname":"JKL","First_Name":"GHI","JobTitle":"Coordinator","Position":"Coordinator","Phone":"012345678","Mobile":null,"EmailAddress":"GHI.JKL@sampleemail.com","Department":"TEST DEPARTMENT 2"}]

Tuesday, 14 April 2015

C# Extended class to read properties in Active Directory

Well I thought I have written this post, but it was always in my mind to do and realized I haven't done it yet. Time has come to share my extended class to retrieve properties from Active Directory not listed under User Principal. I have used Directory Services which is compatible with earlier versions of .Net  3.5. The reason is UserPrincipal class has limitations. Eg: If you want Fax number then easy way to do this is using directory services.

Below is my extended class snippet.

 
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.DirectoryServices;

using System.DirectoryServices.AccountManagement;

namespace ExtPrincipalUser


{
[DirectoryRdnPrefix("CN")]

[DirectoryObjectClass("Person")]

public class ExtendedPrincipalUser : UserPrincipal

{
// Inplement the constructor using the base class constructor.

public ExtendedPrincipalUser(PrincipalContext ctx): base(ctx)

{

}
// Implement the constructor with initialization parameters.

public ExtendedPrincipalUser(PrincipalContext ctx, string samAccountName, string password, bool enabled)

: base(ctx, samAccountName, password, enabled)
{

}
[DirectoryProperty("facsimileTelephoneNumber")]

public string facsimileTelephoneNumber
{   get
   {
       if (ExtensionGet("facsimileTelephoneNumber").Length != 1)
       return null;
       return (string)ExtensionGet("facsimileTelephoneNumber")[0];
  }
set

  {
     this.ExtensionSet("facsimileTelephoneNumber", value);
  }
}

 
[DirectoryProperty("title")]

public string jobTitle


{
get


{
if (ExtensionGet("title").Length != 1)

return null;

return (string)ExtensionGet("title")[0];


}
set


{
this.ExtensionSet("title", value);


}

}
[DirectoryProperty("manager")]

public string manager


{
get


{
if (ExtensionGet("manager").Length != 1)

return string.Empty;

return (string)ExtensionGet("manager")[0];


}
set


{
this.ExtensionSet("manager", value);


}

}
[DirectoryProperty("facsimileTelephoneNumber")]

public string fax


{
get


{
if (ExtensionGet("facsimileTelephoneNumber").Length != 1)

return null;

return (string)ExtensionGet("facsimileTelephoneNumber")[0];


}
set


{
this.ExtensionSet("facsimileTelephoneNumber", value);


}

}

 
[DirectoryProperty("department")]

public string department


{
get


{
if (ExtensionGet("department").Length != 1)

return null;

return (string)ExtensionGet("department")[0];


}
set


{
this.ExtensionSet("department", value);


}

}
[DirectoryProperty("division")]

public string division


{
get


{
if (ExtensionGet("division").Length != 1)

return null;

return (string)ExtensionGet("division")[0];


}
set


{
this.ExtensionSet("division", value);


}

}
[DirectoryProperty("mobile")]

public string mobile


{
get


{
if (ExtensionGet("mobile").Length != 1)

return null;

return (string)ExtensionGet("mobile")[0];


}
set


{
this.ExtensionSet("mobile", value);


}

}
[DirectoryProperty("displayname")]

public string displayName


{
get


{
if (ExtensionGet("displayname").Length != 1)

return null;

return (string)ExtensionGet("displayname")[0];


}
set


{
this.ExtensionSet("displayname", value);


}

}
[DirectoryProperty("mail")]

public string mail


{
get


{
if (ExtensionGet("mail").Length != 1)

return null;

return (string)ExtensionGet("mail")[0];


}
set


{
this.ExtensionSet("mail", value);


}

}
// Implement the overloaded search method FindByIdentity.

public static new ExtendedPrincipalUser FindByIdentity(PrincipalContext context, string identityValue)


{
return (ExtendedPrincipalUser)FindByIdentityWithType(context, typeof(ExtendedPrincipalUser), identityValue);


}
// Implement the overloaded search method FindByIdentity.

public static new ExtendedPrincipalUser FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)


{
return (ExtendedPrincipalUser)FindByIdentityWithType(context, typeof(ExtendedPrincipalUser), identityType, identityValue);


}
internal static ExtendedPrincipalUser FindByIdentity(PrincipalContext ctxMNGR)


{
throw new NotImplementedException();


}

}

}

C# : How to read from Active Directory(AD) Group


In the past I have posted how to read from Active Directory(AD) but I have missed out how to read from Active Directory(AD) Group.

I use Principal context which is compatible with .NET 3.5 or above. This is a simple solution. If you pass the group name in AD to GroupPrincipal.FindByIdentity method it will do the job for you. See the code snippet below. In one of my previous post I have explained how to extract telephone number from AD using extended class using System Directory Services. I have used the same class to extract telephone number. I have created an  object of ExtendedPrincipalUser(Extended Class).

 
public void Get_ITUSERS()
{
   Read_ActiveDirectory("ITSTAFF");
}

public void Read_ActiveDirectory(string groupname)
{

  string filepath = filelocation;
  string grpname = groupname;
  ctx = new PrincipalContext(ContextType.Domain);
  group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, grpname);
  exprUser = new ExtendedPrincipalUser(ctx);
  prinUser = new UserPrincipal(ctx);
  srch = new PrincipalSearcher(prinUser);

  if (group != null)
  {
      foreach (Principal p in group.GetMembers(true))
      {
prinUser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);
exprUser = ExtendedPrincipalUser.FindByIdentity(ctx, IdentityType.SamAccountName, p.SamAccountName);

       if (prinUser.Enabled != false)
       {
                   Console.WriteLine(prinUser.DisplayName.ToString().Trim());
           Console.WriteLine(prinUser.Description.ToString().Trim());
           Console.WriteLine(exprUser.VoiceTelephoneNumber.Trim());

       }

      }
  }
}