0

Check for User existence in Active Directory (Domain) using C# and AccountManagement API

by Syed Aziz ur Rahman 10. December 2013 08:02

 

System.DirectoryServices.AccountManagement API has been added to .net in version 3.5. The API makes it very easy to manage Active Directory (Domain) using code (e.g. C# ). The API lets you perform different operations like add user, delete user, check for user existence in very Object Oriented way as compare to the old API i.e. (DirectoryEntry)

To use the API, you have to add reference to "System.DirectoryServices.AccountManagement.dll" in your project.

Here is some basic code to check if the user exist in Active Directory

 

private string OU = "CN=Users,DC=test,DC=domainName,DC=com";
private string adminUserName = "testAdmin";
private string adminPassword = "T3st123";
string domainName = "Test.DomainName.com";

private void Form1_Load(object sender, EventArgs e)
{
    try
    {        
        if (CheckUserExist("testUser"))
        {
            MessageBox.Show("User found");
        }
    }
    catch (AuthenticationException secEx)
    {
        MessageBox.Show(secEx.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    this.Close();
}

private bool CheckUserExist(string samAccountName)
{
    //Use admin account if current user does not have Active Directory rights.
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName, OU, ContextOptions.SimpleBind, adminUserName, adminPassword))
    {
        //validate the credentials of admin user.
        if (context.ValidateCredentials(adminUserName, adminPassword))
        {
            UserPrincipal existedUserPrincipal = new UserPrincipal(context);
            existedUserPrincipal.SamAccountName = samAccountName;
            PrincipalSearcher searcher = new PrincipalSearcher(existedUserPrincipal);
            if (searcher.FindOne() != null)
            {
                return true;
            }
        }
    }
    return false;
}

Tags:

DotNet

0

Add User to Active Directory (Domain) using C# and AccountManagement API

by Syed Aziz ur Rahman 10. December 2013 07:31

 

System.DirectoryServices.AccountManagement API has been added to .net in version 3.5. The API makes it very easy to manage Active Directory (Domain) using code (e.g. C# ). The API lets you perform different operations like add user, delete user, check for user existence in very Object Oriented way as compare to the old API i.e. (DirectoryEntry)

To use the API, you have to add reference to "System.DirectoryServices.AccountManagement.dll" in your project.

Here is some basic code to Add User

 

private string OU = "CN=Users,DC=test,DC=domainName,DC=com";
private string adminUserName = "testAdmin";
private string adminPassword = "T3st123";
string domainName = "Test.DomainName.com";

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        AddUser("testUser", "First", "Last", "testPass123");
    }
    catch (AuthenticationException secEx)
    {
        MessageBox.Show(secEx.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    this.Close();
}

private void AddUser(string samAccountName, string firstName, string lastName, string userPass)
{
    //Use admin account if current user does not have Active Directory rights.
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName, OU, ContextOptions.SimpleBind, adminUserName, adminPassword))
    {
        //validate the credentials of admin user.
        if (context.ValidateCredentials(adminUserName, adminPassword))
        {
            UserPrincipal userPrincipal = new UserPrincipal(context, samAccountName, userPass, true);
            userPrincipal.GivenName = firstName; //FistName
            userPrincipal.Surname = lastName;  //LastName
            userPrincipal.DisplayName = userPrincipal.GivenName + " " + userPrincipal.Surname;
            userPrincipal.Name = userPrincipal.GivenName + " " + userPrincipal.Surname;
            userPrincipal.Save();
            userPrincipal.Dispose();
        }
    }
}

Tags:

DotNet

0

VsPackage 2010 - Accessing underlying UserControl inside a Custom Editor using IVsWindowFrame

by Syed Aziz ur Rahman 12. October 2012 17:07

By using the sample I mentioned in my previous post here (VsPackage 2010 - Custom Tool Window using IVsHierarchy and IVsUIHierarchy ), I was able to make a custom tool window and a custom editor by Implementing IVsUIHierarchy and IVsHierarchy. Now on an UI event in my custom tool window e.g. double click, I am opening my custom Editor by calling "OpenSpecificEditor". As you know, OpenSpecificEditor method has a out parameter (handle) of IVsWindowFrame which you can use to show the editor. It is working fine and editor is getting opened. A call would be like this.

private IVsWindowFrame OpenEditor(HierarchyTreeNode selectedItem)
{
	IVsUIShellOpenDocument openDoc = (IVsUIShellOpenDocument)GetService(typeof(SVsUIShellOpenDocument));
	IVsWindowFrame editorFrame;
	Guid guidEditorType = GuidList.guidEditorFactory;
	Guid guidLogView = VSConstants.LOGVIEWID.Primary_guid;
	IOleServiceProvider spContext = (IOleServiceProvider)GetService(typeof(IOleServiceProvider));
	string moniker = selectedItem.Text;

	int hr = openDoc.OpenSpecificEditor(0, moniker, ref guidEditorType, "",
	ref guidLogView, "Vj Editor - ", (IVsUIHierarchy)this, (uint)selectedItem.ID,
	IntPtr.Zero, spContext, out editorFrame);

	if (editorFrame != null)
	{
		editorFrame.Show();
	}
	return editorFrame;
}

 Similarly when I tried to get a reference of already created editor using "IsDocumentOpen" method, I got an object of same IVsWindowFrame class. Sample code will be like 

private IVsWindowFrame AddEditorIfNotExist(HierarchyTreeNode hNode)
{
    IVsUIHierarchy outHierOwner = null;
    UInt32[] outHierItem = null;
    IVsWindowFrame editorFrame;
    int open;
    Guid guidLogView = VSConstants.LOGVIEWID.Primary_guid;

    IVsUIShellOpenDocument openDoc = (IVsUIShellOpenDocument)GetService(typeof(SVsUIShellOpenDocument));
    int result = openDoc.IsDocumentOpen(this, (uint)hNode.ID, hNode.Text, ref guidLogView, (uint)__VSIDOFLAGS.IDO_ActivateIfOpen,
            out outHierOwner, outHierItem, out editorFrame, out open);

    if (open != 1)
    {
        editorFrame = OpenEditor(hNode);
    }
    return editorFrame;
}

Now I want to call some public methods of the actual user control inside the editor. I also want to hook up with some events in case the editor control wants to send a message to tool window. Searching on google didn't help so I asked this basic question on MSDN VSX forum. The answer I got was quite cryptic but it worked.

private CtrlChatEditor GetChatEditorFromIVsWindowFrame(IVsWindowFrame editorFrame)
{
    if (editorFrame == null) return null;
    object objControl = null;

//the code to get the inner object
 int result = editorFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out objControl);


if (result != VSConstants.S_OK) return null; VjEditorPane pane = objControl as VjEditorPane; if (pane == null) return null; CtrlChatEditor ctrlChatEditor = pane.Window as CtrlChatEditor; return ctrlChatEditor;//might be null }

Therefore my OpenEditor will look like this now.

private IVsWindowFrame OpenEditor(HierarchyTreeNode selectedItem)
{
    //HierarchyTreeNode selectedItem = ctrlToolWindow.GetItem(itemID);
    IVsUIShellOpenDocument openDoc = (IVsUIShellOpenDocument)GetService(typeof(SVsUIShellOpenDocument));
    IVsWindowFrame editorFrame;
    Guid guidEditorType = GuidList.guidEditorFactory;
    Guid guidLogView = VSConstants.LOGVIEWID.Primary_guid;
    IOleServiceProvider spContext = (IOleServiceProvider)GetService(typeof(IOleServiceProvider));
    string moniker = selectedItem.Text;

    int hr = openDoc.OpenSpecificEditor(0, moniker, ref guidEditorType, "",
        ref guidLogView, "Vj Editor - ", (IVsUIHierarchy)this, (uint)selectedItem.ID,
        IntPtr.Zero, spContext, out editorFrame);

    if (editorFrame != null)
    { editorFrame.Show(); 
//call public propreties and hooking up with the events. CtrlChatEditor ctrlChatEditor = GetChatEditorFromIVsWindowFrame(editorFrame); if (ctrlChatEditor != null) { ctrlChatEditor.OnMessageNeedToBeSend += CtrlChatEditor_OnMessageNeedToBeSend; ctrlChatEditor.ClientContact = selectedItem.ClientContact; ctrlChatEditor.BuddyContact = selectedItem.BuddyContact; } } return editorFrame;
}

Hope this will help someone.

 

Tags: ,

VsPackage 2010 | VSX

30

CRM FetchXML Builder - Tool for building and testing FetchXML statements

by Syed Aziz ur Rahman 10. October 2012 09:38

I just started to work with FetchXML and need a tool to easily create and test statements. Google search resulted in this fine tool i.e. CRMFetchXMLBuilder It is very nice and handy. Use all zeros as key while installation. Here is a snapshot

 

Tags:

MS CRM

0

VsPackage 2010 - Custom Tool Window using IVsHierarchy and IVsUIHierarchy

by Syed Aziz ur Rahman 25. September 2012 16:58

Environment: VS2010

I am trying to make an extension with the following requirements

1. Need a tool window like solution explorer.
2. Double click on a node will open a custom editor.
3. The editor will NOT be linked to a file.
4. The extension should work with or without any solution opened.

So you can say it is like Server explorer. I came to know after search that i have to use IVsHierarchy and IVsUIHierarchy etc to implement this. I found some samples for that for vs2008 but was unable to find any basic tutorial/sample for vs2010.

I have downloaded Mr.Ed Dore sample for Visual Studio 2008 from VSX Insider, merged it with default package project created by Visual Studio 2010, made it working and upload it here. Please feel free to use it. HierAnarchy.zip (378.70 kb)  . Ed Dore is working on a sample where we can host our own control in toolwindow instead of using default VsHierarchy window.

Tags: ,

VSX

4

Visual Studio Extensions (VSX) Articles, Tutorials and Resources

by Syed Aziz ur Rahman 20. September 2012 15:59

I have started learning Visual Studio SDK and interested in developing an extension for Visual Studio. I am compiling of the resources that helped me.

Tags: , , ,

DotNet | DotNet | VSX | VSX

0

VsPackage 2010 How to host Windows Forms User Control in Visual Studio Tool Window

by Syed Aziz ur Rahman 14. September 2012 15:38

I recently started learning how to extend Visual Studio using packages. I will be posting more about it. Here is the first thing I learned today. Do not mind about the site layout. I will fix it soon.

When we create a new VS Package project with ToolWindow, by default a control MyControl.xaml will be added which will be tied to the ToolWindow. I do not have expertise in WPF and its controls. Therefore I tried to use normal winforms user controls. I added a new usercontrol in the project and changed the code in the MyToolWindow.cs to use that control but all I see is a blank Toolwindow when I debug the project.

//Normal code in auto generated MyToolWindow.cs
base.Content = new MyControl();

//The usercontrol i created is SimpleControl. I have changed the code to.
base.Content = new SimpleControl();

 

Here is the snapshot of the code and solution exploror.

Snapshot of a auto generated project

 

I searched a lot for the simple question. I was not able to get any answer. I knew that it should be very simple. I found another guy asking the same question on stackoverflow here but no answer. Finally posted the question on MSDN forum. Mr. Ed Dore was nice enough to answer it here. I am cross posting it here for more visibility in search engine.

The ToolWindowPane can be used to host WPF content or a Winform control.

For a Winform control, you just need to override the Window property get, and leave the Content property null.

For example:

public MyToolWindow() :  base(null)
    {
        this.Caption = Resources.ToolWindowTitle;
        this.BitmapResourceID = 301;
        this.BitmapIndex = 1;
        control = new MyControl();
    }

     override public System.Windows.Forms.IWin32Window Window
    {
        get
        {
            return (System.Windows.Forms.IWin32Window)control;
        }
    }



I hope this will help someone.

Tags: ,

DotNet | VSX

0

Manual change in applicationHost.config not appear in IIS 7 UI

by Syed Aziz ur Rahman 5. September 2012 15:42

If you are manually changing your IIS7 metadata file "applicationHost.config" located in \System32\inetsrv\config and the changes does not show up in IIS 7 user interface, do this.

1. Copy applicationHost.config for config folder to a temp folder i.e. your desktop.

2. Do your changes on the desktop copy.

3. Overwrite the desktop copy back to config folder copy.

4. Open IIS and you will see your changes.

 

Same logic applies to IIS6 and its metadata file.

Tags:

IIS

2

Video about Intoduction of Microsft .net Micro Framework/.netmf/TinyCLR

by Syed Aziz ur Rahman 16. May 2012 03:34

What is Microsoft .Net Micro Framework

The .NET Micro Framework is .NET for small and resource constrained devices. It offers a complete and innovative development and execution environment that brings the productivity of modern computing tools to this class of devices.

For current .NET developers, this means that they can now create applications that run on a range of devices from targeted devices like remote controls to PCs and Servers and on to the cloud – all with the same programming model and tools.

Check out a very nice Channel 9 Video here.

Tags:

26

Migrate From Community Server 2.1 to BlogEngine.Net

by Syed Aziz ur Rahman 31. December 2011 18:51

Recently I need to migrate my blog (http://weblogs.com.pk/aziz)  which was running on Community Server 2.1 to my new blog here which is running on BlogEngine.Net.  I did not have access to code or database as the blog was hosted on a free blogging site. I was unable to find any direct and easy way in the control panel of Community Server therefore I started looking for other options

Now you may or may not have access to code. Therefore I will discuss both options.

How to export if code is accessible:

Keyvan Nayyeri has developed a user control that you can upload, add it to the syndication page and generate BlogML xml of your blogs. Then you can use the import option in the settings of BlogEngine.Net to migrate the data. Check Step 3 below for details about import to BlogEngine.Net. You can find the details about the converter  here. You can also download the code from BlogML codeplex site here. This link also contains other Community Server version utilities, Wordpress export utility and a RSS to BlogML convertor which we will used if we do not have access to our blog codebase.

Here is a screen shot of how it looks like.

 

How to export if code is NOT accessible:

The technique is to use the Community Server RSS feed to generate BlogML xml using a tool called RSS2BlogML, then change BlogEngine.Net code to fix on bug and then finally use the import option of BlogEngine.Net to migrate data.

 Step 1: Generation of BlogML Xml from RSS feed

Rss2BlogML , courtesy of  Simone Chiaretta,  is a simple tool that downloads RSS feed, comment RSS (if provided), and then convert everything to BlogML format. You can download the exe as well as the source code from here (Check other available download sections). It was only tested to work with .Text and with the core blog module of DNN and was having few problems with Community Server 1.2 RSS dialects. Hence I added the functionality in the original code. You can download the latest code from here which supports Community Server 2.1.

Here is the screen shot of the updated version. Please read the original post to understand how to use the tool.

 

Step 2: Fix a minor bug in BlogEngine.Net code.

If any of the blog post has comments in the generated BlogML file and the email address is not there, then BlogEngine.Net code will throw exception. Unfortunately Community Server 2.1 may not always provide email associated with comments. If comments in your blog posts have email addresses then you can skip this step.

Open \BlogEngine\DotNetSlave.BusinessLogic\Providers\DbBlogProvider.cs and go to line:2496.  If you have not changed this file earlier, you will see the code below. Otherwise search for method “UpdateComments” and search the code below.

parms.Add(conn.CreateParameter(FormatParamName("email"), comment.Email ));

and change it to

parms.Add(conn.CreateParameter(FormatParamName("email"), (comment.Email == null ? string.Empty : comment.Email.ToString())));

Compile and upload the dll to your hosting.

Import to BlogEngine.Net

  • Login to your BlogEngine.Net control panel.
  • Click on settings and then on Import & Export.
  • Click on the browse and select your BlogML file.
  • Click on import and done.



RSS2BlogMLv22

 

References

Tags: , , ,

DotNet

Powered by BlogEngine.NET 2.5.0.6
Original Design by Laptop Geek, Adapted by onesoft