Welcome to MSDN Blogs Sign in | Join | Help

Rodney Viana's (MSFT) Blog

Post on Sharepoint, IIS and C#
Getting Sharepoint Site/Web Context in a Console Application

I had recently faced a problem which I believe other people will face at least once: how to get the context from a URL in a C# Console Application. I needed to use ProfileLoader which requires a context. You cannot get current context when you run an application outside a Sharepoint page (like in Windows or Console Application). The solution below gets a context from the topology (which happens to be deprecated but works) and get all properties from the profile. See the sample code below:

 

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using Microsoft.SharePoint.Portal;
using Microsoft.SharePoint.Portal.Topology;
using Microsoft.SharePoint;
using System.Web;

namespace TestProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //get portal site context from topology
            string strUrl = "
http://myserver";
            TopologyManager tm = new TopologyManager();
            PortalSite ps = tm.PortalSites[new Uri(strUrl)];
            PortalContext pc = PortalApplication.GetContext(ps);
            ServerContext sc = pc.ServerContext;

            PropertyCollection props = ProfileLoader.GetProfileLoader(sc).GetUserProfileManager().Properties;

            foreach (Property prop in props)
            {
                if (prop.Type != PropertyDataType.Binary && prop.DefaultPrivacy == Privacy.Public)
                {
                    Console.WriteLine("{0} - {1}", prop.DisplayName, prop.Name);
                }
            }

        }
    }
}

Posted: Wednesday, May 20, 2009 2:35 AM by Rodney Viana

Comments

Georgi said:

Hi Rodney,

You don't need to use deprecated objects, just look in Sharepoint SDK (http://msdn.microsoft.com/en-us/library/ms544366.aspx) and you will find code with same functionality.

Happy coding,

Georgi

# May 26, 2009 5:03 PM

Rodney Viana said:

Hi Georgi,

Even better. Thanks for the feedback.

# May 26, 2009 5:43 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker