SharePoint 2010 101 Code Samples

Today Microsoft released 101 code samples for SharePoint 2010. They have covered a wide range of topics in their samples. You can download them from the below link. You can also browse the code online from the same link.

http://code.msdn.microsoft.com/SharePoint-2010-101-Code-da251182

Posted in Development, SharePoint 2010 | Leave a comment

Step By Step: Creating Custom Workflow Activity for SharePoint 2010 Workflow

             I am back now almost after 2.5 years! I am going to try and write blogs more often now about any interesting work I do and the things I find interesting which can help the folks in the community. So here I am going to write the blog around step by step process to create a custom workflow activity for SharePoint 2010 workflow.

User Problem: This is not a complete end user requirement, But I can it can be a requirement from power user group. I have found with many of my customers that their power users quite often create SharePoint designer workflow where they find themselves very limited with workflow actions. If there is some action which is very common in their process and need to use it to automate many of their processes using SharePoint designer workflow then creating a custom workflow activity for that makes perfect sense.

Solution:  Here I am going to show you a step by step process to create custom workflow activity for SharePoint 2010 workflow using Visual Studio 2010.

As an example I am going to create a simple Custom Workflow action which will create a History list into the specified site if it doesn’t exist and log the specified message into the newly created/existing history list.

  1. Open Visual Studio 2010
  2. Click on File | New | Project
  3. Select SharePoint 2010 Empty SharePoint Project template as shown in the screenshot below (Note: I am going to use C#, You can pick other language if you want to),  Give name to the project (I am going to use project name as CustomWFActivities), Make sure you select “Deploy as farm solution” option while creating the project.Capture1|
  4. Now add another project to the solution
  5. Select Workflow Activity Library template in the Workflow section as shown below, Give name to the project(I am going to use name as CustomActivityDemo)Capture2
  6. Rename Activity file Activity1.cs with LogHistoryIntoList.cs  and add following code into LogHistoryIntoList.cs file.
  7. using System;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Collections;
    using System.Linq;
    using System.Workflow.ComponentModel.Compiler;
    using System.Workflow.ComponentModel.Serialization;
    using System.Workflow.ComponentModel;
    using System.Workflow.ComponentModel.Design;
    using System.Workflow.Runtime;
    using System.Workflow.Activities;
    using System.Workflow.Activities.Rules;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Workflow;
    using Microsoft.SharePoint.WorkflowActions;
    namespace CustomActivityDemo
    {
    public partial class LogHistoryIntoList : SequenceActivity
    {
    public static DependencyProperty SiteUrlProperty = DependencyProperty.Register(“SiteUrl”,
    typeof(string), typeof(LogHistoryIntoList), new PropertyMetadata(“”));
    [DescriptionAttribute(“Url of site where history list is to be created”)]
    [BrowsableAttribute(true)]
    [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
    [ValidationOption(ValidationOption.Optional)]
    public string SiteUrl {
    get
    {
    return ((string)(base.GetValue(LogHistoryIntoList.SiteUrlProperty)));
    }
    set
    {
    base.SetValue(LogHistoryIntoList.SiteUrlProperty, value);
    }
    }

            public static DependencyProperty HistoryListNameProperty = DependencyProperty.Register(“HistoryListName”,

            typeof(string), typeof(LogHistoryIntoList), new PropertyMetadata(“”));
    [DescriptionAttribute(“Name for history list”)]
    [BrowsableAttribute(true)]
    [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
    [ValidationOption(ValidationOption.Optional)]
    public string HistoryListName
    {
    get
    {
    return ((string)(base.GetValue(LogHistoryIntoList.HistoryListNameProperty)));
    }
    set
    {
    base.SetValue(LogHistoryIntoList.HistoryListNameProperty, value);
    }
    }

            public static DependencyProperty HistoryDataProperty = DependencyProperty.Register(“HistoryData”,

            typeof(string), typeof(LogHistoryIntoList), new PropertyMetadata(“”));
    [DescriptionAttribute(“History data to be logged”)]
    [BrowsableAttribute(true)]
    [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
    [ValidationOption(ValidationOption.Optional)]
    public string HistoryData
    {
    get
    {
    return ((string)(base.GetValue(LogHistoryIntoList.HistoryDataProperty)));
    }
    set
    {
    base.SetValue(LogHistoryIntoList.HistoryDataProperty, value);
    }
    }
     

            public LogHistoryIntoList()
    {
    InitializeComponent();
    }

            protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
    {
    try
    {
    if (!IsListExists(HistoryListName))
    {
    CreateHistoryList();
    }

                  using (SPSite site = new SPSite(SiteUrl))
    {
    using (SPWeb web = site.RootWeb)
    {

                            web.AllowUnsafeUpdates = true;
    SPList historyList = web.Lists[HistoryListName];

                            SPListItem historyListItem = historyList.Items.Add();
    historyListItem[“Title”] = “Workflow Activity”;
    historyListItem[“HistoryTimeStamp”] = DateTime.Now;
    historyListItem[“HistoryData”] = HistoryData;
    historyListItem.Update();

                            web.AllowUnsafeUpdates = false;
    }
    }
    }
    catch (Exception ex)
    {

                }

    return ActivityExecutionStatus.Closed;
    }

    public bool IsListExists(string pListName)
    {//Write code to check if the specified list exist in the root web of the specified site using DependencyProperty – SiteUrl
    }

            public void CreateHistoryList()
    {//Write code to create History List using values of DependencyProperties
    }

        }
    }

  8. Let me summarize the above code,  There are two important things to be considered in the above code 1) DependencyProperty  and 2) Execute method.
  9. You will be overriding the Execute method to write your required for the custom action/activity
  10. Now in the CustomWFActivities project add a SharePoint mapped folder to the path 14/TEMPLATE/1033/Workflow  as shown belowCapture3
  11. Add CustomWFActivities.Actions file into the CustomWFActivities project and add following definition of Actions. (Note: In the following XML change the required bold marked attribute values as per your project, IF YOU ADD .actions FILE AS AN XML FILE PLEASE DO NOT FORGET TO REMOVE THE FILE EXTEION .XML FROM .ACTIONS FILE)<?xml version=”1.0″ encoding=”utf-8″ ?>
    <WorkflowInfo>
    <Actions Sequential=”then” Parallel=”and”>
    <Action Name=”Log into custom History List”
    ClassName=”CustomActivityDemo.LogHistoryIntoList”
    Assembly=”CustomActivityDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=669dc2a521cf9896”
    AppliesTo=”all”
    Category=”My Custom Activities“>
    <RuleDesigner Sentence=”Log %1 into History List Name %2 to site %3.“>
    <FieldBind Field=”HistoryData” Text=”History Data” DesignerType=”TextArea” Id=”1″/>
    <FieldBind Field=”HistoryListName” Text=”History List Name” DesignerType=”TextArea” Id=”2″/>
    <FieldBind Field=”SiteUrl” Text=”Url of base site” Id=”3″ DesignerType=”TextArea”/>
    </RuleDesigner>
    <Parameters>
    <Parameter Name=”HistoryData” Type=”System.String, mscorlib” Direction=”In” />
    <Parameter Name=”HistoryListName” Type=”System.String, mscorlib” Direction=”In” />
    <Parameter Name=”SiteUrl” Type=”System.String, mscorlib” Direction=”In” />
    </Parameters>
    </Action>
    </Actions>
    </WorkflowInfo>
  12. Now add the Custom workflow activity assembly into the package, Click on the Advanced button in package designer. See the below screenshot.
  13. Capture4
  14. Now we need to add “<authorizedType> entry for the custom workflow activity into the web.config, In order to do that we will create a everntreceiver.
  15. Add a new feature in CustomWFActivities project. Set the scope of the feature to “Farm”. Right click on the feature and click on “Add Event Receiver”. Write following code in the event receiver, You will need to add a reference of the custom workflow activity project to the CustomWFActivities project.(Note: DO NOT forget to replace the class name of the custom workflow activity as specified in the bold text in the below code)
  16. public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
    SPWebService contentService = SPWebService.ContentService;
    contentService.WebConfigModifications.Add(GetConfigModification());
    contentService.Update();
    contentService.ApplyWebConfigModifications();
    }
           static SPWebConfigModification GetConfigModification()
    {
    string assemblyValue = typeof(LogHistoryIntoList).Assembly.FullName;
               string namespaceValue = typeof(LogHistoryIntoList).Namespace;

               SPWebConfigModification modification =
    new SPWebConfigModification(string.Format(CultureInfo.CurrentCulture, “authorizedType[@Assembly='{0}’][@Namespace='{1}’][@TypeName=’*’][@Authorized=’True’]”,
    assemblyValue, namespaceValue), “configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes”);

               modification.Owner = “CustomWFActivities”;
    modification.Sequence = 0;
    modification.Type = SPWebConfigModification.
    SPWebConfigModificationType.EnsureChildNode;
    modification.Value =
    string.Format(CultureInfo.CurrentCulture, “<authorizedType Assembly=\”{0}\” Namespace=\”{1}\” TypeName=\”*\” Authorized=\”True\” /> “, assemblyValue, namespaceValue);
    Trace.TraceInformation(“SPWebConfigModification value: {0}”, modification.Value);
    return modification;
    }

  17. This is it! Now build, package and deploy the solution, and the custom action will be available to be used in the SharePoint Designer 2010 as shown in the below screenshot.
  18. Capture5

Happy Customizing SharePoint! Smile

Posted in Developer Tips, Development, SharePoint 2010, Workflows | Leave a comment

Integrating Reporting Services with MOSS 2007 Forms based authentication site

I was planning to write about integrating reporting services with SharePoint 2007 since long and finally i am here to write about it. It is a step by step process to integrate reporting services with forms based authenticated MOSS site. It is a quite big blog but could be helpful to a person who is integrating reporting services with MOSS 2007 for the first time 🙂

  1. Before start installing anything make sure you have following AD accounts created :
    • Service account – should be local admin on all the WFE servers as well as SQL Server
    • MOSSSVC
    • SQLSVC
    • Setup Account – MOSSAdmin – Should be the local admin in all WFE servers
  2. Login to the SQLServer box using Setup account
  3. Install SQL Server
  4. Create Logins for all the above accounts in the SQL Server
  5. Add all the above logins to DBCREATOR and SERVERADMIN Server roles.
  6. Login to the WFE box using Setup account
  7. Install .Net Framework 2.0
  8. Install .Net Framework 3.0
  9. Enable ASP.Net 2.0 Web Service Extension on IIS for all frontend severs
  10. Do the “Advanced” installation of MOSS.
  11. Step 1: Start the installation by clicking the Setup.exe in the x86/x64(for 64 bit machine), and the installation starts with the following screen. Select the Complete Server Type option and click the Install Now button. Change the file location from C:\ to some other drive where the space is enough…. This will take few minutes and will install the basic components.· clip_image002
  12. · Step 2: After the installation of basic components, it will automatically start the SharePoint Products and Technologies Wizard. This Wizard can even be started from the Start–>All Programs–>Microsoft Office Server–>SharePoint Products and Technologies Wizard link also. This will present a Welcome screen, Click the Next > button
  13. clip_image004
  14. Step 3: Next screen will be of Connect to a server farm, if it is the first server in the farm select the option “No, I want to create a new server farm” and if there are already one or more existing server, you can select either of the option “Yes, I want to connect to an existing server farm” or “No, I want to create a new server farm”, Click the Next > button
  15. clip_image006·
  16. Step 4: In this step specify the Configuration Database Settings. Do remember if your configuration database is hosted on another server, you must specify a domain account (Global Domain Account), Click the Next > button
  17. clip_image008·
  18. Step 5: Next step is to Specify the port number for the SharePoint Central Administration Web Application. details of Web Application and the port number can be read from the following screen shot, Click the Next > button
  19. clip_image010
  20. Step 6: Finally it will show the Configuration Successful screen, Click the Finish button
  21. clip_image012
  22. Step 7: This will open up the Central Administration homepage in the browser.

Configure Central Admin

  1. Go to Operations Services on server
  2. Start following services
    • Office SharePoint server search – (Note: Always enable this service because it is required to create SSP – shared service provider)
    • Windows SharePoint services help search
  3. Create SSP if you need any of the shared services. – Create SSP by creating SSP web app.
  4. Check the domain name in the SSP to check if MOSS is connected to AD or not
  5. Create a Web application from Application Management SharePoint web application Management
  6. Crate a Site collection – Blank site (Not necessary is restoring the site from dev. server).
  7. Click on the created site collection. Add this site as a TRUSTED SITE.

Reporting Services Integration

  1. Download Reporting Services Add in from – http://www.microsoft.com/downloads/details.aspx?familyid=58EDD0E4-255B-4361-BD1E-E530D5AAB78F&displaylang=en#filelist
  2. Once the portal is up and running run the “Reporting services Add in”
  3. Configure Reporting Service configuration manager at SQL 2008 side
  4. Go to Microsoft SQL Server 2008 Configuration Tools Reporting Services Configuration Manager.
  5. Connect to the server
  6. clip_image014
  7. Enable the service if not already started
  8. clip_image016
  9. Configure the service account
  10. image
  11. Create a Web server URL – Specify Report server name and TCP Port and then press Apply. Check the Created URL
  12. clip_image020
  13. Configure Database
  14. image
  15. Configure Report Manager URL – specify the Report manager name , Press Apply, Check the created URL (Not required to be configured in SharePoint integration mode)
  16. clip_image024
  17. Reset IIS.
  18. Once you install the “Reporting Services Add in”, Central admin will have section to configure Reporting Services Integration named “Reporting Services” in “Application Management”.
  19. Click on “Manage Integration Settings”
  20. Specify “Report Server URL” as configured previously.
  21. Specify “Authentication Mode” – set it to “Trusted Account”.
  22. Click on “Grant Database Access” – Specify the Server name on which the SQL Reporting services are running and Press OK. Specify the credentials of SQLSVC.
  23. Be aware of the WMI provider exception while configuring Database Access. This is just a bug in SQL Server 2008 Feb CTP(It will not be there anymore but if there is any WMI provider exception error just ignore it).

Enable Forms Based Authentication for MOSS Site

  1. Go to Application Management Authentication Providers.
  2. Change the Authentication Type to “Forms”
  3. Set “LdapMembershipProvider” in Membership provider name
  4. Set “LdapRoleProvider” in RoleManager Name
  5. Check “Enable anonymous access”, Select “Yes” for “Enable Client Integration?”- This setting is required for Report Builder to open in the Forms authentication mode.
  6. Go to “Policy for web application” in “Application Management” and add “Mossadmin” and give “full control”. Otherwise it will not allow you to login to the forms based authenticated site.
  7. Open the web.config of central admin site.
  8. Change the key name to “LdapMembershipProvider” for “PeoplePickerWildcards” section.
  9. Add following configuration in the <system.web> section. [Replace <Organizational Unit name> and <domain controller name > with respecting OU and DC names of your AD structure]
  10. <membership defaultProvider="LdapMembershipProvider">
    <providers>
    <add name="LdapMembershipProvider" type="Microsoft.Office.Server.Security.LDAPMembershipProvider, Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C" server="<server name>" port="389" useSSL="false" userDNAttribute="distinguishedName" userNameAttribute="sAMAccountName" userContainer="OU=<Organizational Unit name>, DC=<domain controller name>, DC=<domain controller name>" userObjectClass="person" userFilter="((ObjectCategory=group)(ObjectClass=person))" scope="Subtree" otherRequiredUserAttributes="sn,givenname,cn" />
    </providers>
    </membership>
  11. Open the web.config of Home Site.
  1. Change the key name to “LdapMembershipProvider” for “PeoplePickerWildcards” section.
  2. Add following configuration in the <system.web> section. Use AD information to do the following configuration.
  3. <membership defaultProvider="LdapMembershipProvider">
    <providers>
    <add name="LdapMembershipProvider" type="Microsoft.Office.Server.Security.LDAPMembershipProvider, Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C" server="<server name>" port="389" useSSL="false" userDNAttribute="distinguishedName" userNameAttribute="sAMAccountName" userContainer="OU=<Organizational Unit name>, DC=<domain controller name>, DC=<domain controller name>" userObjectClass="person" userFilter="((ObjectCategory=group)(ObjectClass=person))" scope="Subtree" otherRequiredUserAttributes="sn,givenname,cn" />
    </providers>
    </membership>
    <roleManager defaultProvider="LdapRoleProvider" enabled="true" cacheRolesInCookie="true" cookieName=".PeopleDCRole">
    <providers>
    <add name="LdapRoleProvider" type="Microsoft.Office.Server.Security.LDAPRoleProvider, Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C" server="<server name>" port="389" useSSL="false" groupContainer="OU=<Organizational Unit name>,DC=<domain controller name>, DC=<domain controller name>" groupNameAttribute="cn" groupMemberAttribute="member" userNameAttribute="sAMAccountName" dnAttribute="distinguishedName" groupFilter="(ObjectClass=group)" scope="Subtree" />
    </providers>
    </roleManager>

This is how you can integrate reporting services with MOSS 2007.

Now you can enable site collection feature “Report Server Integration Feature” which will create content types Report Builder Model,Report Builder Report and Report Data Source.

After this installation you can create different document libraries for deploying reports and data sources of the reports. you can deploy reports directly from Visual Studio just by specifying the path of the document library.

To run reports with different set of the parameters you can either consume out of the box webpart “SQL Server Reporting Services Report Viewer”(Available after enabling “Report Server Integration Feature”) or you can create and use a custom developed webpart (which i did).

Apart from providing functionality to run reports we can provide various functionalities like Scheduling reports, Creating packages of reports etc. We can achieve this by writing custom code and using different web services provided by Reporting Services.

Posted in Reporting Services | Leave a comment

How LINQ can be used in Sharepoint – Power of LINQ in Sharepoint

LINQ – Language Integrated Query, It’s a new technology introduced in .NET 3.5. LINQ defines a set of proprietary query operators that can be used to query or filter data in arrays, enumerable objects, XML, Relational database and third party data sources.

It is extensively used by many .NET developers. I was exploring how LINQ can be used and what advantages it can bring in Sharepoint. I observed atleast two advantages of LINQ into Sharepoint

1) To some extent CAML queries can be replaced by LINQ :

CAML stands for Collaborative Application Markup Language which is used in Sharepoint technologies for many purposes and one of them is to query sharepoint lists/document libraries/Views. It’s bit complicated and error prone language. There are tools like U2U CAML Generator tool exist which can generate CAML for you but still developers may want to avoid writing CAML if there is an alternative exist and i found that LINQ can be a good alternative for querying sharepoint lists/views/document libraries. Also i think using CAML is heavier than using LINQ. Following example shows how simple and easy to write LINQ as compare to CAML.

2) Sharepoint lists can be joined using LINQ :

When i moved from .Net background to MOSS and when i had used SQL Server a lot to store/manipulate data in various .Net applications, I always had a question in my mind that how can i join Sharepoint Lists? Initially i was treating sharepoint list as a SQL table when i wasn’t aware it can do much more than that. And if you think it as a sharepoint table the very first question which will come to your mind is how can i relate two or more than two sharepoint lists. That leads to joins. Ok so the ultimate question is how the sharepoint lists can be joined? There are multiple ways to achieve it. One of it is using Sharepoint Designer, This link – http://blah.winsmarts.com/2007-10-Performing_joins_between_SharePoint_lists.aspx provides a good explanation of how it can be done using Sharepoint Designer. The another way i found is by using LINQ. Using LINQ you can do anything with Sharepoint list the same way you do with SQL Table meaning using LINQ you can sort,group, filter or join data from sharepoint lists.

Following code block explains how you can join Sharepoint lists named “Customers” and “Orders”. Also if you have used CAML to query sharepoint lists you can think that how LINQ can replace CAML to achieve the same thing.

using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{
using (SPWeb web = site.OpenWeb())
{
var CustomerItems = web.Lists[“Customers”].Items;
var OrderItems = web.Lists[“Orders”].Items;

//The resultset contains the results of joining two sharepoint lists

var JoinItems = from SPListItem c in CustomerItems
join SPListItem o in OrderItems on c[“Title”].ToString() equals
o[“CustomerName”].ToString()
where c[“Title”].ToString() == “Gary”
select new { Name = c[“Title”].ToString(), Product = o[“Title”].ToString()};

// The Results are being displayed in GridView
gv.DataSource = JoinItems;
gv.DataBind();
}
}

I have shared my thoughts of LINQ in Sharepoint. It can do much more than i am thinking but i am sure LINQ is powerful. Let’s see if Sharepoint 2010 brings any LINQ API(s) for us or it focus on LINQ.

Posted in Development | 1 Comment

How to restore closed webpart on shrepoint page?

You can remove webparts from webpart page by two ways. One is by closing the webpart and another is by deleting the webpart. If you delete the webpart the webpart instance will be deleted from the page itself but if you close the webpart it will be hidden but the instance will be still there on the page. You can check all the closed webparts in the webpart maintenance page.

Following are the steps to restore closed webpart on sharepoint page :

  1. Go to Site Actions Edit Page
  2. Select “Add Web Part” option
  3. In the Add Web Part page, click “Advanced web part gallery and options”
  4. Select the “Closed Web Parts” group
  5. Drag the closed web part(s) into the desired web part zone in desired order
Posted in Installation & Configuration, MOSS 2007 | Leave a comment

Take custom action on MOSS FBA login

I had a requirement of taking some custom action on sharepoint FBA login. I had to log security login information of currently logged in user. How can you achieve that?

To achieve it inherit login page from Microsoft.Sharepoint.ApplicationPages.LoginPage and override its OnLoad event. Implement LoggedIn event to write your custom action you want to do after user logged in.

The code could look like as below:

public partial class Mylogin : Microsoft.SharePoint.ApplicationPages.LoginPage
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Session.RemoveAll();
this.login.LoggedIn += new EventHandler(OnLoggedIn);
}
// To Implement the custom action after user logged in.
void OnLoggedIn(object sender, EventArgs e)
{
//Your custom action will go here.
}
}

Posted in Development, MOSS 2007 | Leave a comment

Create/Deploy/Configure/Use a custom ASP.NET HTTP Handler by Using C#

Best article which describes How To Create/Deploy/Configure/Use a custom ASP.NET HTTP Handler by Using C#:

http://support.microsoft.com/default.aspx/kb/308001

Posted in Development | Leave a comment

How to manage Lists and Libraries with many items in MOSS

If you have a sharepoint list or library which has got many items/documents in it and which is causing performance problem then you should use the indexed columns in the list/library. Following article describes what can be done in this case:

http://office.microsoft.com/en-us/sharepointtechnology/HA101736671033.aspx

Posted in Installation & Configuration | Leave a comment

Removing Links from Create.aspx Page

One of my colleague had a requirement of removing a link from Create.aspx page in MOSS. He had to remove Discussion Board link from Create.aspx. I found the following solution to remove the link from Create.aspx. In fact you can remove any link from Create.aspx page which is installed in MOSS by activating a feature.

Let me mention the steps to remove Discussion Board link from Create.aspx page here:

1) Open Feature.xml of Discussion Lists feature from C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\DiscussionsList folder.
2) Set Hidden attribute of the feature to FALSE. This will enable “Discussion Lists” feature to be visible under site features at site level. By default the Hidden attribute of “Discussion Lists” feature is TRUE because it is a part of TeamColob feature so it will be activated when TeamColob feature will be activated.
3) Deactivate the “Discussion Lists” feature for the site you want. It will hide the “Discussion Board” from the Create.aspx page.

Same way you can hide any link(like links of Lists, Document libraries etc) from Create.aspx page.

Posted in Installation & Configuration | Leave a comment

Getting "an operations error occurred" while trying to access Active Directory using .Net DirectorySearcher class?

Hi,

I was getting “an operations error occurred” error while trying to access Active Directory using .Net DirectorySearcher class and that to when the site is being access from the client. I was not getting an error when i access site from local web server. Weird right?

I was able to find a solution of it. If you will pass credentials to access AD (of user account who has browse access of AD) while you create DirectoryEntry class as shown below, It will resolve the problem.

DirectoryEntry myLdapConnection = new DirectoryEntry(ConfigurationManager.AppSettings[“ADPath”].ToString(),”UserName”,”Password”);

OR

Add following in identity tag under system.web tag of web.config will resolve the problem.

identity impersonate=”true” userName=”DomainName\UserName” password=”Password”

Cheers!

Posted in Development | Leave a comment