DCSIMG
August 2008 - Posts - justguy's

August 2008 - Posts

Empty application.master

Hi,

I you ever need it, this may prove very time consuming…

<%@Master language="C#"%>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<HTML id="HTML1" dir="<%$Resources:wss,multipages_direction_dir_value%>" runat="server">
<HEAD id="HEAD1" runat="server">
    <SharePoint:CssLink runat="server"/>
    <SharePoint:ScriptLink language="javascript" name="core.js" runat="server" />
    <SharePoint:CustomJSUrl runat="server" />
    <SharePoint:SoapDiscoveryLink runat="server" />
</HEAD>
<BODY>
  <form id="Form1" runat="server" onsubmit="return _spFormOnSubmitWrapper();">
        <asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>
        <asp:ContentPlaceHolder id=PlaceHolderPageTitle runat="server"/>
        <asp:ContentPlaceHolder id="PlaceHolderMain" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderGlobalNavigation" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderGlobalNavigationSiteMap" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderSiteName" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderTopNavBar" runat="server" />
        <asp:ContentPlaceHolder ID="WSSDesignConsole" runat="server" />
        <asp:ContentPlaceHolder ID="SPNavigation" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderPageImage" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderTitleLeftBorder" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderTitleAreaClass" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderMiniConsole" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderTitleRightMargin" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderTitleAreaSeparator" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderLeftNavBarDataSource" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderCalendarNavigator" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderLeftNavBarTop" runat="server"/>
        <asp:ContentPlaceHolder id="PlaceHolderLeftNavBar" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderLeftActions" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderLeftNavBarBorder" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderBodyLeftBorder" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderBodyAreaClass" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderPageDescriptionRowAttr" runat="server"/>
        <asp:ContentPlaceHolder id="PlaceHolderPageDescription" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderPageDescriptionRowAttr2" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderBodyRightMargin" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderUtilityContent" runat="server" />
        <asp:ContentPlaceHolder id="PlaceHolderFormDigest" runat="server" /> 
  </form>
</BODY>
</HTML>
Posted by justguy | with no comments

SharePoint Shared Services Personalization Permissions Check

Hi,

I needed to know if a user has permissions to manage user profiles (create, delete, etc.).
Some reflecting showed me that all relevant methods were internal. “Damn” was the word I used.

I have come across this post by Gary Lapointe, and have decided I need something a little simpler:

/// <summary>
///
Checks if the provided user has the permissions set in the rightMast
/// </summary>
/// <example>
///
bool canManageProfiles = DoesUserHaveSSPRights(ServerContext.Current, "DOMAIN\\myusername", SharedServiceRights.ManageUserProfiles | SharedServiceRights.UsePersonalFeatures);
/// </example>
public static bool DoesUserHaveSSPRights(ServerContext context, stringusername, SharedServiceRights rightMask)
{
    return(GetUserSSPRights(context, username) & rightMask) == rightMask;
}

/// <summary>
///
Gets the user's Personalization Services rights
/// </summary>
public static SharedServiceRights GetUserSSPRights(ServerContext context, string username)
{
    Type sharedServiceAccessControlListType = Type.GetType("Microsoft.Office.Server.Infrastructure.SharedServiceAccessControlList, Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");

    MethodInfo sharedServiceAccessControlListMethod =
        sharedServiceAccessControlListType.GetMethod("GetInstance",
            BindingFlags.NonPublic |
            BindingFlags.Public |
            BindingFlags.Instance |
            BindingFlags.InvokeMethod |
            BindingFlags.FlattenHierarchy |
            BindingFlags.Static,
            null,
            new Type[] { typeof(ServerContext) },
            null
          
);

    object acl = sharedServiceAccessControlListMethod.Invoke(
        null,
        new object[] { context }
        );

     PropertyInfo itemProp = acl.GetType().GetProperty("Item",
         BindingFlags.NonPublic |
         BindingFlags.Instance |
         BindingFlags.InvokeMethod |
         BindingFlags.GetProperty |
         BindingFlags.Public
         );
   
    SharedServiceAccessControlEntry aclEntry =
        (SharedServiceAccessControlEntry)itemProp.GetValue(
            acl,
            new object[] { username }
            );

    // check if the user has any permissions
  
if(aclEntry != null)
    {
        returnaclEntry.Rights;
    }
    else
  
{
        // the user is not even in the list
      
return SharedServiceRights.None;
    }
}

 

 

Comments:

Add a reference to Microsoft.Office.Server.

Using:

using Microsoft.Office.Server;
using Microsoft.Office.Server.Infrastructure;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Reflection;

Posted by justguy | 2 comment(s)

Checking if a Publishing page is in edit mode

… and avoiding ASP.NET validator errors such as:

This page contains content or formatting that is not valid. You can find more information in the affected sections.

or

Input string was not in a correct format.

 

Hi,

After being asked by a customer to create a web part diaplying a form with validation on input fields, I have come acoross a problem.
It turns out that ASP.NET validators can prevent you from checking in or editing Publishing pages.

Searching for solution I have come across a few:

Check if the web part is in edit or design mode and only add the validator if not:

if (this.WebPartManager.DisplayMode != WebPartManager.EditDisplayMode &&
    this.WebPartManager.DisplayMode != WebPartManager.DesignDisplayMode)
{
    // in display mode
}
This solution applies only if you have a single web part on the page, because you can only check if the current web part is in display/edit/design mode.
Another solution is using the EditModePanel. It allows you to add contols to the page in display or edit mode.
For example:

// add the EditBox to the page in edit mode
EditModePanelpanel = newEditModePanel();
TextBoxtextBox = newTextBox();

panel.Controls.Add(textBox);
panel.PageDisplayMode = PageDisplayMode.Edit;
this.Controls.Add(panel);


This solution didn’t work. Some replection shows me that the panel uses this function (which is obfuscated): public staticSPControlModeGetContextualFormModeFromPostedForm()
This function comes from the internal class ConsoleUtilities.
The solution that worked for me was quite simple:

// check if the form is in display mode
bool inDisplayMode = SPContext.Current.FormContext.FormMode == SPControlMode.Display;

 

Well, good luck ;)

Posted by justguy | 5 comment(s)

FBA in SharePoint – Everything you’ve ever wanted to do - continued

Hi,

This is my 2nd post on this subject.

This post will get down and dirty with code samples. The first post contains some background info and links to tutorials and guides. I recommand you have a look unless you’re a no-fear-willing-to-spand-days-making-this-work like me :)

To user user profiles with FBA users, you’ll have to extend

 

Chapter 3 – UserProfileManager and FBA (provider issues)

First thing’s first: THERE ARE 2, YES, 2, UserProfileManager CLASSES. The first (Microsoft.SharePoint.Portal.UserProfiles) is obsolete. The second (Microsoft.Office.Server.UserProfiles)  is not.

I’ll use the one in the Microsoft.Office namespace. Note there are differences between them as well as between the corresponding UserProfile classes.

User Profiles in MOSS

User profiles are a nice feature in MOSS. They allow you to store meta data about the users in your portal importing it from other sources (SharePoint 2007: Importing User Profile Information by Sahil Malik).

User information commonly stored in user profiles includes: first and last name, birthday, manager name, company, department, address etc. User profiles are stored in a SSP making them available throughout the farm.

You can add and change the user profile properties using the management interface:

Central Administration –> Shared Services Provider –> User Profiles and Properties

For more info, try Google or Live! search.

 

Retrieving User Profile Info

In order to retrieve user profile info, you’ll have to have the SSP up and running. If it’s not, you’ll get errors trying to user a UserProfileManager object.

  1. Create a new UserProfileManager object:

    UserProfileManager userProfileManager = new UserProfileManager();

    This will create profile manager that will work in the context of the current site and the assigned SSP.
    You can retrieve user profile information from other SSPs in the farm using this function:
    /// <summary>
    /// Creates a <see cref="UserProfileManager"/> object for a specific site collection
    /// 
    /// Note the functions contains no error handling what so ever
    /// </summary>
    /// <param name="siteURL">The URL of the site</param>
    /// <returns>The <see cref="UserProfileManager"/> object for the site collection</returns>
    public UserProfileManager GetUserProfileManagerForAnotherSite(string siteURL)
    {
        SPSite anotherSite = new SPSite(siteURL);       // reference the other site collection
        ServerContext serverContext = ServerContext.GetContext(anotherSite);        // get the server context
        UserProfileManager userProfileManager = new UserProfileManager(serverContext);      // create the profile manager object
    
        return userProfileManager;
    }
    This function will be useful for bridging the gap between a site using Windows Authentication and a site using FBA.
    You could access user profile info from either site using the correct context of UserProfileManager.
  2. To create a user profile, use: 
          
    UserProfile
    profile = userProfileManager.CreateUserProfile();    // create a profile for the current user
    or
    UserProfile profile = userProfileManager.CreateUserProfile("domain\\username");    // create a profile for the provided user
    or
    UserProfile profile = userProfileManager.CreateUserProfile("Provider name:username");    // create a profile for the provided user (FBA)
    Where:
    Provider name is the name of the default membership provider defined in the web.config.
    Example:
                      <membership defaultProvider="FBADemoMember">
    Username is the name of the user from the membership database.










    Note that unlike domain users that use ‘\’ as a separator, FBA user require ‘:’.
  3. Get the user profile for the current user:

    UserProfile
    profile = userProfileManager.GetUserProfile(false);

    The user’s profile can be null if there was no profile created. GetUserProfile can create the user profile if needed when you set bCreateIfNoExist to true:
          UserProfile profile = userProfileManager.GetUserProfile(true); 

    GetUserProfile will allow you to retrieve user profiles for user by users referenced by username:
    UserProfile profile = userProfileManager.GetUserProfile("domain\\username");    // retrieve the user profile for a domain user
    UserProfile profile = userProfileManager.GetUserProfile("Provider name:username");    // retrieve the user profile for a FBA user
  4. As you can imagine, deleting a user profile will be quite simple. I’ll skip the code sample.
  5. Setting values in user profiles or retriving them is as easy a using any other collection. The only challenge is using the correct property names (not display names, but internal names). To help you out, you can use PropertyConstants for the OOO stuff.

    Examples:

    string firstName = (string)profile[PropertyConstants.FirstName].Value;
    string lastName = (string)profile[PropertyConstants.LastName].Value;
    DateTime hireDate = (DateTime)profile[PropertyConstants.HireDate].Value;
    string myCustomProperty = (string)profile["MyCustomPropertyName"].Value;    // retrieve the value for a custom property
    Choice fields have multiple values, and you can take a look at this post: Setting MOSS User Profile properties by Dan Matthews.

Note you can access user profile information using the user profile service. Here’s a nice post (InfoPath team blog) demostrating the use with InfoPath.

What’s next?

The sky’s the limit… just kidding…

Here’s a sample method I came up with demonstrating a sample use for user profiles:

/// <summary>
///
Looks for an anniversary, meaning any date in the user's profile matching today's month and day
/// </summary>
/// <param name="profile">
The user profile to check</param>
/// <returns>
true if found, false if not</returns>
public bool DoesTheUserHaveAnythingToday(UserProfile profile)
{
    bool result = false;    // assume the user has nothing today
    // get the profile manager
   
UserProfileManager userProfilem = profile.ProfileManager;

    // go over all the properties looking for dates
   
foreach (Property prop in userProfilem.Properties)
    {
        // is it possbible for a prop to be null?
       
if (prop != null)
        {
            try
           
{
                if (prop.Type == "datetime" || prop.Type == "datenoyear" || prop.Type == "date")
                {
                    DateTime date = (DateTime)profile[prop.Name].Value;

                    // check if the day and month match today
                  
if (date.Month == DateTime.Today.Month && date.Day == DateTime.Today.Day)
                    {
                        // found a date so stop looking
                      
result == true;
                        break;
                    }
                }
                else
              
{
                    // this property is not a date value
              
}
            }
            catch
          
{
                // nothing to do... move on to the next property
          
}
        }
    }

    return result;
}

 

Disclaimer: I didn’t run this code so… :)

Posted by justguy | 2 comment(s)