Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Tuesday, February 26, 2013

SPUser and Query-Based Distribution Lists

My current contract is with a company that decided after they installed Exchange 2003 that "if it ain't broke, don't fix it!!!!" So, they haven't updated Exchange in 10 years. It makes life harder in certain ECM and in Records Management situations, but for the most part it really doesn't affect me with my SharePoint work. Until the client wanted to get a task list created from every user in a very particular Distribution List...

First, what is a Query-Based Distribution List? In the Exchange 2003 world it is a security group that contains LDAP query objects, instead of the typical principal entities that normal groups contain. Now, it is a security group in name only. Because it does not contain actual entities, you can't use it to secure anything. You can only use it to email the users that are returned from the query or queries contained within. What makes it tricky is that the membership of the group is dynamic. The user list is created on the fly by the queries every time the group is called. Also, in Exchange 2003, there is no Exchange API that can be used to connect to these groups to resolve the members. Got all that? Good. Here we go!

First things first... In SharePoint if you are given a Security Group or a traditional Distribution List, how do you resolve the membership? Simple!! You need only call the SPUtility.GetPrincipalsInGroup method. That guy will return to you an array of SPPrincipalInfo objects which you can use to create SPUser objects in the manor of your choosing. My preference is to use the SPWeb.EnsureUser method. If the SPUser is not a member of the web or the group EnsureUser will add it and return the resolved SPUser object. If it IS a member it simply returns the SPUser object. It makes no difference if the group is a Distribution List or if the group is a Security Group. This method works for both.
public List<SPUser> GetUsersFromADGroup(string groupName, string groupDisplayName,  System.Collections.Generic.List<SPUser> masterList, SPWeb web) {
bool reachedMaxCount;
SPPrincipalInfo[] principalInfoArray = SPUtility.GetPrincipalsInGroup(web, groupName, int.MaxValue - 1, out reachedMaxCount);
if (principalInfoArray.Count() != 0) {
  foreach (SPPrincipalInfo info in principalInfoArray) {
    if (info.PrincipalType == SPPrincipalType.SecurityGroup || info.PrincipalType == SPPrincipalType.DistributionList) {
     GetUsersFromADGroup(info.LoginName, info.DisplayName,  masterList, web);
   } else {
      try {
       SPUser user = web.EnsureUser(info.LoginName);
        if (!masterList.Any(u => u.Name == user.Name)) {
         masterList.Add(user);
        }
     } catch {
        continue;
     }
   }
  }
  } else {
    GetUsersFromDynamicGroup(groupDisplayName, masterList, web);
  }
    return masterList;
}

A quick bit of code to show how you can get the SPRincipalInfo array using the SPUtility.GetPrincipalsInGroup method, then create SPUsers from that. The try/catch block is there in case there are any orphaned accounts sitting in the groups. These accounts can not be resolved, and will throw exceptions. You can choose to output these to an error list, or simply ignore them as I do here.


BUT, what about the Query-Based Distribution List(QBDL)? Since the QBDL has no actual members, remember the membership of the group is determined by LDAP query, the entities don't actually "belong" to the group, when you call the SPUtility.GetPrincipalsInGroup, you get a SPPrincipalInfo array with no objects. Bummer!

So, where do we go from here? We cannot directly get the group membership. So, have to come at this problem from a different angle. What if we had the LDAP query contained within the AD Query Object? If we had that, we could use .NET's System.DirectoryServices classes to execute it. Great!! So... where is that query held??
The one thing we know for sure about Microsoft Exchange is that they LOVE updating Active Directory Schema. They do it every time there is an update. Fortunately for us, anything that is added to the AD schema, we can very easily pull out and use.
First, you need to add a couple of references. You are going to need to reference System.DirectoryServices and System.DirectoryServices.AccountManagement. Add those guys to your using statements:

using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;

After that we will be constructing the GetUsersFromDynamicGroup method that will be called should the SPPrincipalInfo array return with a count that is equal to 0. You can see the if up in the code, if (principalInfoArray.Count() != 0), and our method GetUsersFromDynamicGroup, being called in the "else" statement.

Now, what do we need to make everything happen. I first need the display name of the group. This is important, because the display name is how the methods in the System.DirectoryServices find the actual group. Why? Because that is how the object is named in LDAP. Note that the SPUtility.GetPrincipalsInGroup uses the login name of the group, NOT the display name. SPUtility.GetPrincipalsInGroup is looking for AD principals, NOT LDAP objects. These two concepts must be kept separate, or this process will not work (LDAP is looking for CN=GroupName,OU=OrgUnitName,DC=DomainName,DC=com, where a principal is looking for a name of DomainName\GroupLogInName).
After I have the display name, I am going to need all of the stuff to make a SPUser so I need the SPWeb object. Since I am returning everything as a List, I want to make sure that I am appending my SPUsers found in the QBDL to whatever else is in the group object, I include the existing List.

The first thing we are going to do in the method is set up a System.DirectoryServices.AccountManagement.PrincipalContext. Why? Well, I need to get a hold of the System.DirectoryServices.DirectoryEntry of the group. From that object, I can read what the members of the group are, and begin to resolve the users. Fortunately, getting the DirectoryEntry is very easy. I create a PrincipalContext using my domain name, then I create a GroupPrincipal using the PrincipalContext and the group display name. Now, it is just a matter of casting the return of the GroupPrincipal.GetUnderlyingObject method as a DirectoryEntry.
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "DomainName");
GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupDisplayName);
DirectoryEntry group = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();

After we have these objects ready to go, we are ready to start the heavy lifting. Now that we have the group as a DirectoryEntry, we can strip out the members of the group, in this case it will be the query objects. Since there really isn't a DirectoryEntry.Members property that will give us a nice DirectoryEntry.MembersCollection, we have to do that on our own. Luckily, we only need to cast the members property as IEnumerable. From there we can create our "foreach" loop and start our work.

object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members) {
   //Do work in here
}

Here is where things get a little messy. We now have the Members as generic "objects." We really can't do anything with "objects." C# is a strongly typed language, so we need to transform this "object" in to something that has meaning. So, we need to create a new DirectoryEntry object. We then pass the member object to the DirectoryEntry constructor and, we automagically have a DirectoryEntry object from just a plain old "object." I have to admit here that I don't like using "objects." I like to strongly type everything so there is no confusion at design time or run time as to what objects are and how they can be used... But, because there is no MembersCollection object provided by the DirectoryEntry class, I couldn't figure out away to get the members and put them in a foreach loop. Sure, I could use some other loop, but... I am lazy and I didn't want to. You can make my code suck less and make your own cool loops. I didn't want to worry about it, so I punted and used "object."
Anyway, we have the member as a DirectoryEntry now. This member represents the query object that contains the LDAP query we need to actually resolve the users in the group. So, we can now finally call up the property that stores the LDAP query and execute it!! Yay!!

The property that concerns us is "msExchDynamicDLFilter." Essentially, all we need is that guy's value, and we are off to the next section of our code. Remember that all property objects are Dictionary objects. So you would retrieve the property value the exact same way you would any other dictionary value:
DirectoryEntry.Properties["msExchDynamicDLFilter"].Value.ToString().
Fun, right?

There is one other property that we need to get. Because we want to execute our LDAP query across the entirety of our domain forest, we want to grab the value of the msExchDynamicDLBaseDN property as well. With this guy we will construct the LDAP URI that we will use as our search base.

Now that we have our search base and our LDAP query we are ready to search AD for the members of the Dynamic group. .Net makes this very easy for us, because Microsoft has included a DirectorySearcher class that we can use to search AD. Intuitive, right? Actually it is:
  DirectoryEntry memberEntry = new DirectoryEntry(member);
  string ldapBase = memberEntry.Properties["msExchDynamicDLBaseDN"].Value.ToString();
  ldapBase = string.Format("LDAP://{0}", ldapBase);
  DirectoryEntry adRoot = new DirectoryEntry(ldapBase);
  DirectorySearcher search = new DirectorySearcher(adRoot, memberEntry.Properties["msExchDynamicDLFilter"].Value.ToString());
  SearchResultCollection results = search.FindAll();
 foreach (SearchResult result in results) {
//Create your SPUsers here
}

As you can see, we create the DirectorySearcher object using the the search base (adRoot), and the LDAP query (memberEntry.Properties["msExchDynamicDLFilter"].Value.ToString()). Microsoft provides us with a SearchResultCollection, nice of them, and all we need to do is call the FindAll method to populate it. There is also a FindOne method, if you are only looking for a single item. I'm looking for lots and lots, so I call FindAlll.
As with all of Microsoft's "collection" objects, the SearchResultsCollection inherits IEnumerable, so we can create a foreach loop using it.

Now it is just a matter of getting the property in the SearchResult object that contains the user's login name. After we have that, we need only call SPWeb.EnsureUser(loginName) and we are ready to add our SPUser object to the master List list. We do that the same way that we did it above:

 string loginName = string.Format("TRONOX\\{0}", result.Properties["samaccountname"].Value.ToString());
 try {
    SPUser user = web.EnsureUser(loginName);
    if (!masterList.Any(u => u.Name == user.Name)) {
      masterList.Add(user);
    }
} catch {
    continue;
}


You will notice that I do a little LINQ after calling EnsureUser and before I actually add the SPUser object to the List. I don't want any duplicates, so I check to see if there is a user already in the list with the same Name. If there isn't, I add it to the list. If there is, I ignore the object.

That is all there is to it!! It takes some getting around, but it is possible to get the membership of the QBDL!

Here are both of the methods that I was using in their entirety:

public List<SPUser> GetUsersFromADGroup(string groupName, string groupDisplayName,  System.Collections.Generic.List<SPUser> masterList, SPWeb web) {
 bool reachedMaxCount;
 SPPrincipalInfo[] principalInfoArray = SPUtility.GetPrincipalsInGroup(web, groupName, int.MaxValue - 1, out reachedMaxCount);
 if (principalInfoArray.Count() != 0) {
  foreach (SPPrincipalInfo info in principalInfoArray) {
    if (info.PrincipalType == SPPrincipalType.SecurityGroup || info.PrincipalType == SPPrincipalType.DistributionList) {
     GetUsersFromADGroup(info.LoginName, info.DisplayName,  masterList, web);
   } else {
      try {
       SPUser user = web.EnsureUser(info.LoginName);
        if (!masterList.Any(u => u.Name == user.Name)) {
         masterList.Add(user);
        }
     } catch {
        continue;
     }
   }
  }
  } else {
    GetUsersFromDynamicGroup(groupDisplayName, masterList, web);
  }
    return masterList;
}


public List<SPUser> GetUsersFromDynamicGroup(string groupDisplayName, List<SPUser> masterList, SPWeb web) {
 PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "TRONOX");
 GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupDisplayName);
 DirectoryEntry group = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();
 object members = group.Invoke("Members", null);
  foreach (object member in (IEnumerable)members) {
    DirectoryEntry memberEntry = new DirectoryEntry(member);
    string ldapBase = memberEntry.Properties["msExchDynamicDLBaseDN"].Value.ToString();
    ldapBase = string.Format("LDAP://{0}", ldapBase);
    DirectoryEntry adRoot = new DirectoryEntry(ldapBase);
    DirectorySearcher search = new DirectorySearcher(adRoot, memberEntry.Properties["msExchDynamicDLFilter"].Value.ToString());
    SearchResultCollection results = search.FindAll();
    foreach (SearchResult result in results) {
       string loginName = string.Format("TRONOX\\{0}", result.Properties["samaccountname"].Value.ToString());
       try {
          SPUser user = web.EnsureUser(loginName);
             if (!masterList.Any(u => u.Name == user.Name)) {
                masterList.Add(user);
             }
       } catch {
           continue;
       }
    }
  }
 return masterList;
}

Monday, September 3, 2012

ItemDeleting Event Not Firing

I have written many event receivers.  I have written them for just about every conceivable business use, and for some that are not so conceivable.
I am a MCPD, passing both tests in the 90% range.  I have written these receivers for SPS 2003, MOSS 2007, SharePoint 2010, and even on SharePoint 2013 Beta.

I'm kind of a big deal.

So, why, when I was writing such a mundane application as an event receiver, did one of the events not fire? I overrode the proper method.  I used the correct syntax.  I had no runtime exceptions, and everything built and deployed just fine.  During debugging, as this was a farm deployed solution, I attached to the correct w3wp.exe worker process application (if it would have been a sandboxed solution I would have attached to the user worker process application, SPUCWorkerProcess.exe).  I knew this, because the other events I overrode were firing and doing their jobs just fine.  BUT when it came to the delete events nothing...  What the heck?????????

After looking around and pulling out more than a little bit of hair, out of frustration I created a new solution with just the delete events.  This solution worked just fine.  No muss no fuss.  So, why would the very same code not work in one solution, but not in another???   I did a file comparison of the wsp files to find out what was up.

What happened was this...  When I initially created the project in Visual Studio, I checked the box for just the ItemUpdating event.  Nothing else.  What Visual Studio does with this setting is it adds in the Elements.xml a <Receiver> section in a <Receivers> block.  In that block is an element called <Type>.
What I had forgotten to do with my first solution was to add a <Type> element for my ItemDeleting event.  The Elements.xml file registers the receiver with SharePoint.  If it doesn't have a <Type> section for your events, it doesn't matter how much code you have written in as many overridden methods, the will not fire.
Now, the ItemDeleting event is a separate receiver event, thus it does need its own <Receiver> section.
I just copied my ItemUpdating receiver, and pasted it below.  Then I changed the name and the <Type>.  Everything else can remain the same.

After realizing my mistake, I added the proper <Type> elements to register my deleting events, and BLAMO, they fired just as they should have.
One little trick that may catch many people is that you may have to deactivate then re-activate your feature in order to register the new receiver section, and get the event to fire.  For whatever reason, SharePoint may not load the new XML, even after the IIS Application Pool is recycled.  It can be very annoying, ESPECIALLY if you are trouble shooting other reasons why your event is not firing.

It was a rookie mistake that I made.  Nearly every part of SharePoint development has two parts to it.  The code or assembly part, and the declarative XML part.  The code never works without the XML letting SharePoint know what's up.

One of the good things about software development is that the code will always find away to keep you humble.

Wednesday, December 21, 2011

Configuring FAST Search Server 2010 To Use SSL With A CA Certificate

I had the opportunity to configure a FAST Search Server 2010 deployment in a secure environment. Instructions for configuring SSL for FAST are fairly straight forward, however there were a few gotchas involved.

First, install FAST just as you normally would. Follow these instructions from Microsoft: Configure a stand-alone deployment or a multiple server deployment (FAST Search Server 2010 for SharePoint)
You want to use the FASTSearchCert.pfx self signed certificate that is generated by FAST when using the SecureFASTSearchConnector.ps1 for the first time. Be sure that the user that you use in the -username switch is the SAME user that is running the SharePoint Search Service that you configured when you created the Content SSA. This user also needs to be a member of the FASTSearchAdministrators local group on the FAST Admin and non-admin servers. This is very important!
Also, use the normal http settings for the Administrative Services and the Query Services for the time being. We want to make sure that our connections to FAST work with out incident BEFORE we complicate things by introducing the CA cert.

After you set up your environment, and you have confirmed that everything is working properly, no errors in the SharePoint 2010 event logs, it is time to complicate our deployment by adding the CA signed certificates. The instructions for setting up the use of SSL are a bit vague in places, so I will set down what I did to make everything work.

First things first... Check out the following site: Manage certificates (FAST Search Server 2010 for SharePoint)
As you can see you will need to obtain certificates, all signed by the same Certificate Authority, for any server that is being used. You can really complicate your instillation by changing the DNS alias that is hosting your FAST Search Administration and Resource Store IIS web sites. If you choose to do so, not recommended personally, a specific SSL cert needs to be created and signed by the same CA that is signing the rest of your server certificates then bound to those web sites.

Be sure to complete the section on Replacing the Query HTTPS certificate. It is very important that you have the port correctly configured to use the proper certificate.

One gotcha that I ran in to was that you do need to update the deployment.xml to reflect your usage of SSL for the Administrative services. Be sure to follow the instructions on the following page: Enable Administration Service over HTTPS (FAST Search Server 2010 for SharePoint) Step number four is the one that points you to change the config.xml file.
I like to do one last check here and attempt to access the secure URLs for my services. You should get 403 errors saying that directory browsing is not permitted. What you should not get is the page saying that there is a problem with the certificate. If you get this page, you need to go back to the instructions, and make sure that you have secured everything correctly and that the proper certificates are installed.

Now that everything on the FAST server is taken care of, go back to your SharePoint 2010 Central Administration server. The server certificates for this server should be installed as well as the root certificate for the CA. The certificate used for the SharePoint server needs to have been created specifically for the SharePoint server. You can't just export the server certificate from the FAST server and install it on the SharePoint server. It must be specifically for the SharePoint server created from the same CA as the FAST certificates.
Get in to Central Administration and find your Query Search Service Application properties. Update the Query, Administrative, and Resource Store Service Locations with their secure locations. This is fairly straightforward, to check if things are working correctly, simply click on the Query Search Service Application then click FAST Search Administration on the left. Go through each link on the FAST Administration page and confirm that there are no errors.

Next, open up a SharePoint PowerShell command window. Execute the following cmdlet: Ping-SPEnterpriseSearchContentService -hostName [FASTContentDistributor:PORT] where the FAST Content Distributor is the proper location for your Content Distributor. Don't forget the port number, it is 13391 if you used the default ports.
This handy dandy cmdlet will give you a listing of the installed Personal Certificates on the server will confirm witch one will successfully connect to your newly secured Content Distributor. Copy the thumbprint of the cert that connected and rerun the SecureFASTSearchConnector.ps1 script that you ran before to set up your Content SSA. This time, instead pointing to a specific certificate file, you will be using the thumbprint of your installed certificate, as shown in the instructions from Microsoft.

If all goes well you will get the magic words, Connection to contentdistributor [your content distributor site:PORT] successfully validated.
After that your communications between SharePoint and FAST Search Server will be conducted over SSL. Of course, if you add Content Distributors, or Query Service locations you WILL need to run through the steps of installing certificates and securing those sites just as we did above.

Friday, December 2, 2011

Authentication Types and Authentication Providers - SharePoint and IIS

I have been having an interesting discussion with my client that has nearly caused my head to explode. The discussion centers around Negotiate, Kerberos, NTLM, IIS, and SharePoint.

A little background first. The client wanted to set up a SharePoint site that could be accessed both by Kerberos and NTLM. SharePoint 2010 only allows for a singe Windows Authentication per zone, so you need to set up two zones for a single web application. One that is configured for Kerberos, and one that is configured for NTLM. Pretty straight forward stuff.
I created a Web Application diagram detailing out the need for these two zones, and was called out by my client. He remarked that if you set your Web Application up for "Negotiate" you can use both Kerberos and NTLM, so the extra zone is not needed.
Wait... What?? Negotiate uses both NTLM and Kerberos?? Eh?? My world had just turned upside down. Kerberos and NTLM are mutually exclusive authentication methods, and can not be mixed together. You are using NTLM, or you are using Kerberos, there is nothing in between. This is evident in Central Administration by having to select either NTLM or Kerberos as your Windows Authentication.

So what is NTLM and Kerberos? Why don't they work together? Well, Kerberos is a token based authentication method that requires all parties involved to be registered with Active Directory, and trusted to use Kerberos. I like to call this connection to AD the Kerberos chain. Why? Well, because everything is registered and trusted in AD, special things can happen. Once a user is authenticated, servers and applications can use that user credential for many authentications. Thus Kerberos can make multiple "hops" without having to re-authenticate the user. It makes a "chain" of authentication.
It works like this... The user attempts to connect to a web site that uses a database back end. The web site is secured with Kerberos. The user is first prompted for their credentials, and authenticated by AD. The user is issued a "token" by the authenticating Domain Controller, called the Kerberos Domain Controller (KDC).
The web site then makes a call to the back end database. The database asks who wants the data, and the web server responds with the user's token. The database says well, the user is trusted by the KDC, the Web server is trusted by the KDC, the web site is trusted by the KDC, I'm trusted by the KDC, and since I trust the KDC, I will send the user the data requested. Everything is chained together by AD, thus the Kerberos chain.
As you can imagine, Kerberos takes some configuration... This can be the tricky part, because all pieces of the puzzle need to be included in AD. That means that the SQL instances and DNS aliases used in IIS need to be registered with Security Principal Names. All servers that host the SQL and IIS instances need to be trusted for delegation in AD. And all users involved need to have their SPNs as well. By default, users get an SPN when they are created in Active Directory Users and Computers, but servers are not trusted for delegation by default.
Here is a GREAT whitepaper on how to configure Kerberos for SharePoint.
NTLM is a simple challenge response authentication method that only requires the user to be registered in AD. Because of this, NTLM can not make the multiple security hops that Kerberos can make. So for each additional hop that is required by the application, the user will need to re-authenticate, or some other trusted credential needs to be used.

Getting back to the story... As you can imagine, the situation set off a flurry of emails, me trying to explain that you cannot do such a thing, and the client insisting on he has done this impossibility in his test environment. So, like my Physics professors told me many years ago, when things don't make sense, go back to the scientific method. I didn't do that...
Instead of having my client describe his environment in excruciating detail, I tried to come up with ways in which he could be thinking NTLM and Kerberos could be working in concert. I asked him if he was talking about his IIS settings, which could indeed be set to be open to using Kerberos and NTLM.

Back in the good old days of the IIS Metabase, there was a property called NtAuthenticationProviders. You could use this property to explicitly state which Windows authentication method you wanted to use. In the IIS 6 days, if you wanted to use Kerberos, you needed to make sure that the "Negotiate" value was set. If you wanted to use both, you set the property to Negotiate,NTLM. (If you want to know more about setting this property in IIS 5 and 6 click the link.)
In IIS 7 Microsoft changed IIS fundamentally. Instead of the proprietary Metabase, an XML file is used for configuration. This file is found by default in the ApplicationHost.config file at %SYSTEMROOT%\system32\inetsrv\config.
In that file there is a property called windowsAuthentication, and under that property is the providers property. In that area you can see the values for Negotiate and NTLM. (If you want to know more about setting this property in IIS 7 and 7.5 click the link.)

This is where things can get tricky... SharePoint is nothing more than an IIS hosted .NET application. IIS is a service on the Windows server platform. Windows, by default, uses Kerberos as its authentication method. Therefore, if your Kerberos chain is configured (all servers trusted for delegation and SPNs for all DNS aliases, SQL instances, as well as users) IIS will authenticate the user using Kerberos DESPITE the SharePoint web application being set for NTLM. User impersonation will not be used, but the initial authentication will be Kerberos. A check of the Windows Security logs will confirm this.

So, knowing all that I thought that perhaps my client had his SharePoint web application authentication method set for NTLM, but was seeing Kerberos in his security logs. Not the case. A screen shot later proved that he was indeed configured to use Kerberos.

So now I finally get smart and start to apply the scientific method. I ask for a complete description of their environment and what evidence he had to say that he was being authenticated via NTLM. And the truth finally emerged.
He was creating his web application in his intranet. He would then VPN in to the network from an outside network, and then connect to the site with his browser. He was prompted for credentials in a standard NT challenge response window. It was this window that he was calling NTLM. He thought that Kerberos needed to include the client's computer in the Kerberos chain, and that Kerberos could only be configured if the user's browser was configured to pass the user's logged on credentials. This, of course is false. Only the user needs to be authenticated, and it is the SECOND computer in the chain that needs to be trusted for delegation. The first hop you get with just the password. Because of this, ANY user can be used as the impersonated user, as long as they are registered with AD. It is how you can change the logged on user in SharePoint. Because his Kerberos chain is in tact, Kerberos can be successfully used as the authentication method.

And with that, the mystery was solved and all was well with the world. A second zone was not needed for NTLM, because Kerberos could be used. Despite my diagrams and explanations, my client STILL can not get his head around the fact that NTLM is not being used at any point. He thinks that if the challenge response window pops up, you are in NTLM's grip...

The moral of this story is to use the scientific method first to solve issues, rather than attempting to prove someone wrong, and that you are the smartest guy in the room first... Goes better for client relations too.

Wednesday, October 5, 2011

Hiring for SharePoint

I am at the SharePoint 2011 Conference this week and I have found a reoccurring theme popping up with the manager types that come to the conference. Most of them are overwhelmed with the breadth of the SharePoint product, and nearly all of them realize that what they have in place to support SharePoint is not what they need.

I was talking to some of the other participants about a particular project they were involved it. He was involved in trying to deploy SharePoint as a fault tolerant system, and I was running down what he needed to do. We noticed that we were attracting a lot of attention from the leader types. You know, they are the guys in the button up shirts trying not to look lost in the sea of geeks. After a bit, the managers started to ask about how they could go about hiring the right people to set up their SharePoint environments "right." The first thing I said was that to set up their SharePoint environments "right," they needed to spend some serious money. In my experience, SharePoint needs a dedicated cross-functional team in order to be successfully deployed and maintained. The word that really stuck in the manager's craw is "dedicated." Even after seeing all of what SharePoint can do, they still believed that there would not be enough work for dedicated staff. This just isn't true. At any company were there is not dedicated SharePoint staff, immediate problems start to pop up, mostly surrounding the direction of the product, and what it can do. If staff is not dedicated, there is no incentive for an individual to study the features of SharePoint, and find out how it can be best used in the company. There is no one to support the product, leaving the end users wondering how to use it. Essentially, if you don't have dedicated staff, you are throwing the product down the tubes, and dooming your deployment for failure.

As to the hiring question... This spawned a long and interesting conversation about how many people were needed, getting input from the tech side, me, and the business side, them. All in all, those that accepted the fact that they need dedicated staff saw value in the team that I suggested.

In my ideal deployment, and this means ANY deployment, from one server to 10,000, you are going to need four roles; Architect, Administrator, Designer, and Developer. The most important, most senior, and most critical is the Architect role. This person will lead the team, develop the overall vision of the deployment, be the chief evangelist, and mentor the other roles. As you can imagine, this role is also the most difficult to hire.

Architect

This should be the first person that is hired, and should do the hiring for the rest of the team. This is a special person, because they need to have a split IT personality. In that I mean that they need to have experience with software development, and systems administration. It helps if they also have some Network Engineering in their background as well. What I mean by software development experience, is that they need to have a firm grasp of OOP, the .NET Framework, and modern design principals. They need to have written code as a developer on a software team. A person who has written code, but as a one project, one programmer shop is not your ideal candidate, as these developers often have a tough time leading a team of people.
They need to have designed and written WCF services, web services, and windows services. They need to know the role that each play, and how to integrate them in to a cohesive SOA. After all that... They need to have a good grasp of the SharePoint API, and they need to have written and deployed the major pieces involved in SharePoint development. What major pieces? Web parts, timer jobs, site definitions, and workflows. They need to know what each part does and what problems each solves.

The Architect should be able to speak to the database staff about indexes, backups, and SharePoint database architecture. They should also have a good grasp of what Remote BLOB storage is and when it is a good idea. They should be able to present this to the database staff.

On the other side of the IT fence, the Architect needs to know how SharePoint is installed, configured, deployed, and maintained. In other words, this person needs to have spent time as a professional SharePoint Administrator. As an administrator this person should have handled at least one major farm migration. This will ensure that they know what is involved in a migration, and that they have all of the lessons learned from that migration. It also ensures that they have been involved in SharePoint long enough to have seen where Microsoft has come with the product, and have some idea on where Microsoft is going with the product.
They need to have planed for and executed disaster recovery plans with SharePoint, and should be very comfortable with recovery scenarios, from a total loss of the farm, to the loss of a single file.

They should be well versed on search. How SharePoint does it, what the limitations of the Out Of the Box search features are, and when it is a good idea to put FAST Search in. They should know how to configure search so that it will return the proper results.

They also need to be a very well rounded IT person. They should know about the different methods on how to make SQL redundant, they should know how to load balance a web server, they should know what LDAP is, and what a good Active Directory design consists of and how it will impact the SharePoint deployment.

With all of this experience, it will be very difficult to interview for this position. You have to accept that the SharePoint stuff you will have to simply ask about and hope that they give you a straight answer. You are an IT manager, so hopefully you have some skill in the area of bullshit detection... If you have development staff, bring in a developer to aid in the interview. You will get a good grasp of their development skills from your trusted developer. Also bring in one of your Systems Engineers to find out what they know about AD and other Windows related services. If you have web staff, bring one in to discuss web topics. Your trusted staff should be able to give a good rundown on the candidate's general skill. From this you should be able to judge if the candidate is being truthful about what is on their resume.

Here are some of the qualities that I think that an Architect should have personally:
  • Passionate about SharePoint, this should be evident in the interview.
  • Passionate about IT in general.
  • They should have some decent social skills. They will end up being a cheerleader and evangelist for SharePoint and its features as well as effectively lead the SharePoint team. Thus, they have to be able to communicate effectively with other humans.
    With all of the technical skill we are asking for, this particular feature will be some of the hardest to meet...
  • They should be worried with improving their skills. They will ask about training and conference budgets.


With all of the above, you must realize that this person will not come cheap. This kind of skill comes at a premium, and you have to giver proper incentive for them to stay. The good news it that you can save money on the other members of the team.

Administrator
The Administrator position is going to be easier to find. You can ask for some SharePoint administration experience, but it really isn't required, especially if you want to save some money on this position. In a perfect world, this position will have about 2 years experience with SharePoint as an IT pro.
The necessary skills, in my opinion, are going to center around, in order of importance, IIS, PowerShell, software deployment, Windows, and experience supporting "N" tier applications. SharePoint experience would fit somewhere between Windows and supporting "N" tier applications.

IIS is the key in this position, because SharePoint is a .NET program hosted in IIS. Without a firm grasp on how IIS works, how applications are hosted, how WAS works, the administrator will fall flat on his face when the fit hits the shan. SharePoint deals heavily in Web Services and WCF and if the administrator has never supported those two things in IIS, they will be baffled on why the sections hosting the different technologies use the same authentication, but have different settings in IIS. Without web experience, the critical difference between a web application and a web site will trip them up. These things are vital to the SharePoint farm.
I would like this person to be up on the latest load balancing techniques so that they can put in to practice the load balancing methods that the Architect selects for the deployment, but this is not necessary and it can be something that the Architect mentors the Administrator on.

Experience with PowerShell is absolutely vital. Much of SharePoint administration is done through PowerShell, and many tasks can be automated with PowerShell. Being only one person, the Administrator who only uses Central Administration can only do so much. The Administrator who automates and scripts tasks multiplies their worth to the company, by being able to clone themselves many times over. Also, many tasks need to be handled off hours, the stupid Administrator stays late, or remotes in from home to complete these tasks via Central Administration. The smart, savvy Administrator, the one you want to hire, scripts all off hour tasks and has the script send him email confirmations of task completion or failure. No muss no fuss. An Administrator that automates the most common tasks also builds in automatic redundancy for themselves and has more time to focus on interesting and important work, R&D, and preventative maintenance. The administrator who does not script is constantly putting out fires, repeating the same tasks over and over, and never seems to have any time to R&D and do anything preventative.

As the developers will be handing the Administrator their code to deploy, it is a good idea to look for an IT Pro with experience in deploying software. Again, you want to see this person insist on scripted deployments, as well as packaged solutions. It makes their job easier, and makes a solid repeatable, predictable deployment the rule rather than the exception.

Supporting "N" tier applications forces the Administrator to always be thinking about what service is calling what. It also will mean that the candidate knows about authentication methods that can handle multi-server hops, or what must happen so that authentication methods that can not multi-hop on their own make those vital hops.

Developer
Again, it is not vital that the Developer have SharePoint development experience. It is vital, however, that the Developer have .NET web development experience. From the developer standpoint, SharePoint is just another API to call. Take away the funky deployment, and SharePoint development is just like any other development, inherit a base class, and implement a method. A week training class will get the Developer up to speed on SharePoint development. After that the Architect will be able to mentor them and guide them to become SharePoint developers.
What we do want out of a developer is a deep sense of curiosity. We want them to want to know why things work the way that they do, and once they know that, they should wonder how they can manipulate those things to fit what the business wants to do.

Designer
The most common flaw that very technical people have is that they have no eye for the aesthetic. Their art is in their code, or in how smoothly their servers run. Unfortunately, no matter how brilliant the code behind the site may be, if it is not pleasing to the eye, or if the user experience is bad, the deployment will fail. This is where the Designer comes in. The designer is a person who should be able to design functional, pretty, web sites. I also like my designer to be experts in the client side scripting languages that make their visions possible. JavaScript, JQuery, CSS, Flash, and Silverlight should be on the Designer's resume along with the ability to work with technical people. In my opinion the designer should be able to create a UI, then hand that UI off to the developer to wire up the functionality. In other words the Designer creates the button and puts it on the page, the Developer takes over at the mouse click.
It is not required that the Designer know about SharePoint. SharePoint experience is good, but it is far from the most vital thing you are looking for.

DBA
This last position is not listed above on my three position team list because this position does not need to be 100% dedicated to SharePoint. SharePoint handles most of the database work all on its own, with as little human interaction as possible. BUT since a major part of the SharePoint functionality depends on the database it is important to have a DBA that can be the "go-to" person with SharePoint team issues. It will be up to the DBA and the Architect to make the redundancy decisions with regards to the SQL farm. If the Developer needs to hit an external database for some reason, the DBA is who they go to to get permissions and other things in line. When the Administrator is setting up Business Intelligence, they will need the DBA to create data cubes in Analysis Services.

With these positions filled, your SharePoint deployment is set up for success. SharePoint is a unique product, and not one that can simply be thrown in to an environment. It needs dedicated people to support and maintain it so that you can get the most out of the product.

Tuesday, February 8, 2011

Adding the SharePoint Snap In to PowerShell

What's the first step? If you are using the ISE, and you want to have the scripts excited from any PowerShell environment:
Add-PSSnapin Microsoft.SharePoint.PowerShell

This line adds the SharePoint snapin and makes any PowerShell console the same as the SharePoint Management Console.

If you want to get cute you can add the following code to see if the SharePoint snapin is available, and throw a friendly error message if it is not:

$snapin = Get-PSSnapin | Where-Object{$_.Name -eq 'Microsoft.SharePoint.PowerShell'}
if($snapin -eq $null)
{
Write-Output('SharePoint snapin does not exist on this server')
}else{
Add-PSSnapin Microsoft.SharePoint.PowerShell
}


As long as you know the namespace of the PowerShell snap in that you want to add, the above code will work to add it simply replace the SharePoint snapin namespace (Microsoft.SharePoint.PowerShell) with the namespace of your snap in.

Friday, October 22, 2010

Presence in SPGridView MOSS 2007

A company I work for will be incorporating Windows Communicator with their VOIP and IM system.
We also have a web based Corporate Directory application.
Wouldn't it be nice, someone thought, if we could put the Windows Communicator Presence Indicator in to our Corporate Directory?
The Corporate Directory is currently a SharePoint Data View Web part. Adding Presence would require custom development.
Off I go.

The first issue I ran in to was that there is some debate on how to get Presence information in to SharePoint (MOSS) 2007, some blogs say to use the IMNRC java script, while others say to use the imnmark image with a IMNImageOnClick java script event.
Confused? Me too. The problem is that Microsoft left the old way to do Presence in to the new version of SharePoint, so what would work in 2003:


<span><img border=\"0\" height=\"12\" src=\"/_layouts/images/imnhdr.gif\" onload=\"IMNRC('"you@domain.com"')\" ShowOfflinePawn=\"1\" alt=\"\" id=\"user_presence_icon\"/></span>


will work in 2007, but the way Microsoft does Presence in 2007 is with the anchor and image tags:


<a href="javascript:" onclick="IMNImageOnClick();return false;" class="ms-imnlink"><img title="" alt="No presence information" name="imnmark" border="0" valign="middle" height="12" width="12" src="/_layouts/images/blank.gif" sip="you@domain.com" id="imn1,type=sip" ></a></span>


Great! It works for just one user, with their email address hard coded. The problem is that I have lots of users, and everything is stored in a database.
Easy!, you say, Just use a GridView and put that stuff in there!! Sounds good, but SharePoint always has a way of messing with us. The SharePoint version of a GridView is the SPGridView. It is just like a GridView, only harder. In SharePoint you do nearly everything in the code. It sucks. Personally, I like the ability to use the Design tap of Visual Studio it lets me know what I have going. So, I tend to use User Controls so that I can see what is going on. Only that does not really apply here.
Anyway, typically what you would do in ASP.NET programming would be to drop a GridView on a page and set up your fields. Because we are using some HTML you will need to create some template fields. Generally looks like this:


<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


No problem! Except that we are in SharePoint and we have to do all of that in code...

This is where it really gets sticky. You will notice that the Template Field is called as a control. That means that it is a part separate from the GridView. That makes your life in SharePoint difficult.

As Oscar Medina details in his awesome blog post SPGridView - Using a custom TemplateField to add a Checkbox Column you can declare a Template Field inside your SPGridView, but you will need to create a class for your Item Templates.

A class that inherits from ITemplate, and you will need to override the InstantiateIn method in order to stick your stuff in.

During my very frustrating trial and error period, I found that the best way to get the Presence stuff to work is to use the new 2007 method, but convert all of that HTML in to ASP.NET controls. The ITemplate object likes those better. So what I ended up doing was creating two Literal Controls for the span tags, a Hyperlink Control for the anchor, and an Image control for the image. I used the Attributes.Add for all of the extra stuff in the anchor and the image tags that is not supported in the normal control.
So your code from above now becomes:


LiteralControl lc = new LiteralControl();
lc.ID = "lcSpan1";
lc.Text = "";


HyperLink hypLink = new HyperLink();
hypLink.Attributes.Add("onclick", "IMNImageOnClick();return false;");
hypLink.CssClass = "ms-imnlink";
hypLink.NavigateUrl = "javascript:";


System.Web.UI.WebControls.Image imgPresence = new Image();
imgPresence.Attributes.Add("name", "imnmark");
imgPresence.Attributes.Add("id", "imn1,type=sip");
imgPresence.ImageUrl = "/_layouts/images/blank.gif";
imgPresence.Attributes.Add("sip", "you@domain.com");
imgPresence.ID = "imgPresence";


LiteralControl lc1 = new LiteralControl();
lc1.ID = "lcSpan2";
lc1.Text = "
";


Sweet huh? Again, it works great for hard coding a single user to a Presence indicator. We don't want that. We want something we can stick in to a SPGridView to display a whole bunch of people. Here we go.

First you need to set up your data source. I like to use DataTables.


DataTable DT = new DataTable("Data");
DT.Columns.Add("Name");
DT.Columns.Add("Position");
DT.Columns.Add("Presence");
DataRow row = DT.NewRow();
row["Name"] = "Natto Ninja";
row["Position"] = "Goofball";
row["Presence"] = "nattoNinja@domain.com";
DT.Rows.Add(row);

row = DT.NewRow();
row["Name"] = "Megan Fox";
row["Position"] = "Megga Hottie";
row["Presence"] = "iamhot@domain.com";
DT.Rows.Add(row);

row = DT.NewRow();
row["Name"] = "Al Sharpton";
row["Position"] = "King of the Goofballs";
row["Presence"] = "KOG@domain.com";
DT.Rows.Add(row);


DataTables are fun. Now we need to create our SPGridView. There are a couple of different ways to do this, if you are using a control, you can use Ted Pattison's approach or you can just create it in the code. Calling it in the code makes it tougher for you to place on the page, but Pattison's approach requires you to create a code behind (not a code beside, very important distinction. If you don't know the difference you need to read Pattison's article). At any rate you have to create the grid.


SPGridView grdSPGrid = new SPGridView();
//Createyourfields
SPBoundFieldfldName=newSPBoundField();
fldName.HeaderText="Name";
fldName.DataField="Name";
grdSPGrid.Columns.Add(fldName);

SPBoundFieldfldPosition=newSPBoundField();
fldPosition.HeaderText="Position";
fldPosition.DataField="Position";
grdSPGrid.Columns.Add(fldPosition);

TemplateFieldfldPresence=newTemplateField();
fldPresence.HeaderText="Presence";

//Call your class that creates your Item Template
fldPresence.ItemTemplate=newGridViewTemplate("Presence");

grdSPGrid.Columns.Add(fldPresence);

//Call the method that inserts your row information in to your image control
grdSPGrid.RowDataBound+=newGridViewRowEventHandler(grdSPGrid_RowDataBound);

//Bind the the DataTable to the SPGridView
grdSPGrid.DataSource=DT.DefaultView;
grdSPGrid.DataBind();


You will notice the place where I call a class to get my Item Template going. It is in that class where I create my objects that will become my Presence indicator.
Here is that class:


public class GridViewTemplate : ITemplate
{

private string columnName;

public GridViewTemplate(string colname)
{

columnName = colname;
}

public void InstantiateIn(System.Web.UI.Control container)
{

LiteralControl lc = new LiteralControl();
lc.ID = "lcSpan1";
lc.Text = "";
container.Controls.Add(lc);

HyperLink hypLink = new HyperLink();
hypLink.Attributes.Add("onclick", "IMNImageOnClick();return false;");
hypLink.CssClass = "ms-imnlink";
hypLink.NavigateUrl = "javascript:";
container.Controls.Add(hypLink);

System.Web.UI.WebControls.Image imgPresence = new Image();
imgPresence.Attributes.Add("name", "imnmark");
imgPresence.Attributes.Add("id", "imn1,type=sip");
imgPresence.ImageUrl = "/_layouts/images/blank.gif";
imgPresence.ID = "imgPresence";
container.Controls.Add(imgPresence);

LiteralControl lc1 = new LiteralControl();
lc1.ID = "lcSpan2";
lc1.Text = "
";
container.Controls.Add(lc1);


}

}


That builds our template field. Now for the last little piece. There has to be a way to insert the data from the DataTable in to a variable that we can set in to the image control.
To do that, we need to go in during the data binding of the SPGridView. Which is why I have this line in the code that creates the grid:


grdSPGrid.RowDataBound+=newGridViewRowEventHandler(grdSPGrid_RowDataBound);


That guy calls this method in the same class:


void grdSPGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string row = "";
//Find the row with the data
DataRowView rowView = (DataRowView)e.Row.DataItem;
row = rowView["Presence"].ToString();
//Create a new image control and cast it as the control in the grid
System.Web.UI.WebControls.Image imgPresence =
(System.Web.UI.WebControls.Image)e.Row.FindControl("imgPresence");
imgPresence.Attributes.Add("sip", row);

}


}


That is all there is to it! It took me nearly a week to figure all of this stuff out. It was a lot of fun finding the right events, and creating the proper event handlers and stuff.

In case you are confused, the code that creates the SPGridView and the code that does the special binding all should be in the same class. The class that creates the ItemTemplate can be in a separate class file, or just as another class in the same class file as your other class.
Hope this helps some people.

Many thanks to Oscar Medina and Ted Pattison. Their posts really helped be out, and I surely would not have gotten my grid to work without them.

Thursday, October 7, 2010

SharePoint Template Gotchas

I am having to do a lot of simple web part movement and site design stuff lately and I ran across some issues that threw me...

In the past, I have created a site and configured the basic web parts that I wanted set up the primary pages generically and configured everything the way I wanted to see it anytime I created a new sub site. I would then go to the Site Settings and to Look and Feel then save the site as a template. Anytime I wanted my generic site look, I would simply create a new subsite with this template. Easy peasy.

This time I was working on a Publishing Site that would need several sub sites that would all have the same basic properties, lists, and web part views. I created the first site, clicked on up the Site Settings, looked over at Look and Feel and... Nothing. No Save Site as a Template link. What the...?? I stated going through the site features and even in to Central Admin to see if I had all of the Farm Features active that I needed to be active. No Dice.

It turns out that Publishing Sites can not be saved as templates. Bummer.

SharePoint being SharePoint, many times you can do things you are not supposed to do if you know how to use the forms and other features, I decided to poke around to see if I could get things to work the way I wanted to. The first thing I found was that if I deactivated the Publishing features, I could save the site as a template, create a new site, then activate the Publishing features at that time... This would do what I wanted... kind of. I wanted a better solution, so I tried a trick that I learned to do when I had a number of web parts that I wanted to delete from a page, to grab the actual template save application page URL and append that on to my publishing site URL to see if I could get it to save the template as I wanted it.

The URL of the save as a template application page is: _layouts/savetmpl.aspx. So my site URL: http://MOSS2007/TemplateSite became http://MOSS2007/TemplateSite/_layouts/savetmpl.aspx
To my wonder and surprise the application page popped up and I was able to save the site as a template. I created a new site using this template, and it worked like a champ.
Turns out my buddy Shane Young already had this figured out way back when. Go figure...