Thursday, October 3, 2013

Check SharePoint Version and read User Profile Property value programmatically

[SharePoint 2010; SharePoint 2013]


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server.UserProfiles;
using System.Linq;
using System.Collections;

namespace GetProfileProperty
{
    class Program
    {
        //Declare SKU keys of each SharePoint version
        const string SHAREPOINT2010FOUNDATION = "BEED1F75-C398-4447-AEF1-E66E1F0DF91E";
        const string SHAREPOINT2010STANDARD = "3FDFBCC8-B3E4-4482-91FA-122C6432805C";
        const string SHAREPOINT2010ENTERPRISE = "D5595F62-449B-4061-B0B2-0CBAD410BB51";
        const string SHAREPOINT2013STANDARD = "C5D855EE-F32B-4A1C-97A8-F0A28CE02F9C";
        const string SHAREPOINT2013ENTERPRISE = "B7D84C2B-0754-49E4-B7BE-7EE321DCE0A9";
        const string SHAREPOINT2013FOUNDATION = "9FF54EBC-8C12-47D7-854F-3865D4BE8118";
           

        static void Main(string[] args)
        {
            string _skuID = string.Empty;
            string CurrentSPVersion = string.Empty;
            bool IsUserProfileServiceEnabled = false;
            string result = string.Empty;
            string PropertyName = "Unit System"; //User profile property name to get the value
            string siteURL = "http://siteURL";
            SPSite site = new SPSite(siteURL);

            SPFarm farm = site.WebApplication.Farm;

            //Get the SharePoint Products installed in current Farm
            IEnumerable<Guid> _guid = farm.Products;

            //Iterate each product to find the version installed
            foreach (var item in _guid)
            {
                _skuID = item.ToString();
                //Condition true if the version installed is Enterprise/Standard
                if (_skuID.Equals(SHAREPOINT2010ENTERPRISE, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2010STANDARD, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2013ENTERPRISE, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2013STANDARD, StringComparison.CurrentCultureIgnoreCase))
                {
                    CurrentSPVersion = "SPServer";
                    break;
                }
                //Condition true if the version installed is Foundation
                if (_skuID.Equals(SHAREPOINT2010FOUNDATION, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2013FOUNDATION, StringComparison.CurrentCultureIgnoreCase))
                {
                    CurrentSPVersion = "SPFoundation";
                }

            }
            if (CurrentSPVersion == "SPServer")
            {
                    //Get the service applications installed in the web application
                    Microsoft.SharePoint.SPServiceContext spServiceContext = Microsoft.SharePoint.SPServiceContext.GetContext(site);
                    IEnumerable<SPServiceApplicationProxy> proxies = site.WebApplication.ServiceApplicationProxyGroup.Proxies;

                    foreach (var services in proxies)
                    {
                        //Check if the User Profile Service is enabled
                        if (services.TypeName == "User Profile Service Application Proxy")
                        {
                            IsUserProfileServiceEnabled = true;
                        }
                    }
                    if (IsUserProfileServiceEnabled)
                    {
                        Console.WriteLine("User profile for this web application is enabled");
                        Console.WriteLine(GetUserProfilePropertyValue(siteURL, PropertyName, true));
                    }
                    else
                    {
                        Console.WriteLine("User profile for this web application is NOT enabled");
                    }
                 
            }
            if (CurrentSPVersion == "SPFoundation")
            {
                Console.WriteLine("You have SP Foundation");
            }
         
        }

        /// <summary>
        /// Get the User Profile Property value
        /// </summary>
        /// <param name="property">User Profile Propery Name</param>
        /// <param name="isUserProfileEnabled">boolean</param>
        /// <returns></returns>
        public static string GetUserProfilePropertyValue(string siteURL, string property, bool isUserProfileEnabled)
        {
            string result = "";
            string CurrentWeb =siteURL;
            try
            {
                //Get the value from My Settings/User Information List if User Profile Service is not enabled
                if (!isUserProfileEnabled)
                {
                    using (SPSite site = new SPSite(CurrentWeb))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList userInfoList = web.SiteUserInfoList;
                            SPUser user = web.EnsureUser(@"domainname\username");
                            SPListItem userItem = userInfoList.Items.GetItemById(user.ID);
                            result = userItem[property].ToString();
                        }
                    }
                }
                else
                {
                    //Read the user profile property value if user profile service application is enabled. Reads the value using User Profile Manager
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(CurrentWeb))
                        {
                            SPServiceContext context = SPServiceContext.GetContext(site);
                            UserProfileManager profileManager = new UserProfileManager(context);
                            string sAccount = @"domainname\username";
                            UserProfile userProfile = profileManager.GetUserProfile(sAccount);
                            ProfileSubtypePropertyManager psmanager = userProfile.Properties;

                            //Get the internal name from the display name
                            IEnumerable<string> PropertyInternalName = psmanager.Cast<ProfileSubtypeProperty>()
                                                                        .Where(r => r.DisplayName.ToLower() == property.ToLower())
                                                                        .Select(r => r.Name);
                            //Get the value of property
                            if(PropertyInternalName.Count()==1)
                                result = userProfile[PropertyInternalName.First().ToString()].Value.ToString();
                        }

                    });
                 
                }

            }
            catch (Exception)
            {
           
            }
            return result;
        }

    }
}

PS: Above is a console application and some of the values are hard-coded, you need to change the code accordingly to your requirement/environment.

Tags:
- programmatically retrieve user profile property value using property display name
- Check SharePoint version/edition programmatically


Add custom profile property in User Information List

Using SharePoint 2010;

Requirement: To add/read a custom profile property in My Settings page/ User Information List.

To read profile property and values:

            string fieldName = string.Empty;
            using (SPSite site = new SPSite("http://SiteURL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList userInfoList = web.SiteUserInfoList;
                    SPUser user = SPContext.Current.Web.EnsureUser(login);
                    SPListItem userItem = userInfoList.Items.GetItemById(user.ID);

                    foreach (SPField field in userInfoList.Fields)
                    {
                        fieldName = field.Title;
                        Console.WriteLine(fieldName + "\t " + userItem[fieldName]);
                    }
                }
            }

To add a custom profile property:

//Create custom profile property
   SPField newTextfield = userInfoList.Fields.CreateNewField(SPFieldType.Text.ToString(), "Personal Web Site");                  
  userInfoList.Fields.Add(newTextfield);
  userInfoList.Update();

Few facts about My Settings Page:

1. Keep in mind that “My Profile” and “My Settings” are two completely different things.  My Profile is looking at information directly from the Profile Database.  My Settings is site specific, and is looking at information at the current site.

2. If the User Profile service application is not enabled when you visit the site initially, your data is retrieved from the Active directory and stored in the content database "User Information List"

3. User Information List is a hidden list. You can access it programmatically or using PowerShell.

4. In People and Group page (http://<sitecollection>/_layouts/people.aspx), it appears as a SharePoint list. Fields can be added or removed to suit the business needs.

5. List events are not raised on the User Information list type. There is no resolution as of now as per Microsoft. Refer: http://msdn.microsoft.com/en-us/library/aa979520.aspx

6. My Settings is the local site collection profile. The UserInfo table (DB instance of ‘User Information List’) is a table stored in the Content Database for each Site Collection.

7. If User Profile is not configured and there are no My sites, then we can use User Information List available per each Site Collection where minimal data is available, such as AD account, SID, Email, First name, last name.

8. Custom properties in User Information List can be added from ‘People and Groups’ site collection page by Site Collection Administrators.

Wednesday, July 31, 2013

Using JQuery in new form and edit form

Using jquery-1.8.2.min.js;

To get the instance of a control which does not have the title field in source view:(f12 view)

Criteria is a lookup field name and the client ID for that would be ctl00_m_g_0cf2a9f8_fc83_4e94_a96e_c4cb7d1d3e09_ctl00_ctl04_ctl09_ctl00_ctl00_ctl04_ctl00_BambooLookupPlus_x0028_1_x0029__x0020_Criteria. Using Client Id directly in the script is not recommended, so use the following syntax to get the Criteria field instance. Normally the ID value would have the field name suffixed.

//To get the field instance:
var criteria1field = $("[id$='Criteria']")[0];

//To disable field
$(criteria1field).attr('disabled', 'disabled');

//To enable field
$(criteria1field).removeAttr("disabled");

//Change event for Issue Type field
 $(criteria1field).bind("change", function() { //code goes here });




//wait for 5 seconds
setTimeout(function()
 {
  // code goes here

}, 5000);

//Set Criteria  field width and style   
$(criteria1field).css('width','70');
$(criteria1field).css("background-color","red")
$(criteria1field).css("font-face","bold")

//Set lookup field value
$(criteria1field).val("This is a sample value");

//To get the value of field that has title field in source view
var Severity = $("input[Title='Severity']").val();


Friday, June 21, 2013

Apply custom css file for default master page

For MOSS 2007;

To apply a custom stylesheet for a specific site.

1. Open the site in SPD
2. Checkout the master page, open, go to design view and open the Apply Styles panel.
Create Custom Style Sheet using SharePoint Designer

3. Select any style and click "Go To Code". This opens the core.css that it was mapped to by default.

Create Custom Style Sheet using SharePoint Designer

4. Modify the style and save the core.css file. This will popup a warning message. Click Yes. This will save customized core.css file in your local site and your master page will be applied with this custom css.

5. Check in the master page.

Wednesday, May 1, 2013

ICellProvider vs IRowProvider vs IListProvider vs IFilterProvider vs IWebPartField vs IWebPartRow vs IWebPartTable vs IWebPartParameters



Interfaces used to make web part connections.

ICellProvider: This API is now obsolete. Enables a Web Part to communicate with a Web Part that implements the ICellConsumer interface to work with a single value item.
IWebPartField : Defines a provider interface for connecting two server controls using a single field of data.

IRowProvider: This API is now obsolete. Enables a Web Part to send a row of data to a Web Part that implements the IRowConsumer, ICellConsumer, IFilterConsumer, or IParametersInConsumer interface.
IWebPartRow: Defines a provider interface for connecting two server controls using a single field of data.


IListProvider: This API is now obsolete. Defines events that a Web Part can implement so that it can provide an entire list (rowset) of data to another Web Part that implements the IListConsumer interface.
IWebPartTable: Defines a provider interface for connecting two server controls using an entire table of data.

IFilterProvider: This API is now obsolete. Used to communicate with a Web Part that implements IFilterConsumer interface to provide filter information to the consumer.
IWebPartParameters: Defines the contract a Web Parts control implements to pass a parameter value in a Web Parts connection.

Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.aspx

Tuesday, April 23, 2013

Fast Search in SharePoint 2010


Advantages of using Fast Search in SharePoint 2010
1. Crawl BDC content with FAST.
2. Previewers – Display inline previews of Word, PowerPoint, and Excel files.
3. Indexing more documents
4. FAST can be configured for Enterprise edition only
5. Search enhancements based on user context Scopes Best Bets, visual Best Bets, and document promotions and demotions to a sub-group of employees.
6. Rich Web indexing support Indexing of wide variety of Web content, including Flash.

Using LINQ to SharePoint


The LINQ to SharePoint provider is a new feature in SharePoint 2010 that allows you to use a strongly-typed entity model and the language integrated query (LINQ) query syntax to query list data. Essentially, LINQ to SharePoint hides the complexity of developing CAML queries from developers, which can reduce development time and make code more readable. The LINQ to SharePoint provider converts the LINQ expressions into CAML queries at run time.

Using LINQ to SharePoint in your own solutions consists of three main steps:
  • Generate the entity classes. Before you can start writing LINQ queries against your SharePoint lists, you must create or generate the strongly-typed entity classes that represent your list data and lookup column relationships.
  • Develop the solution. After you add the entity classes to your Visual Studio 2010 project, you can write LINQ queries against the strongly-typed entities that represent your data model.
  • Run the solution. At run time, the LINQ to SharePoint provider dynamically converts your LINQ expressions into CAML queries, executes the CAML, and then maps the returned items to your strongly-typed data entities.
Although you can manually develop your entity classes, in most cases, you will want to use the SPMetal command line tool. This is included in SharePoint Foundation 2010 and can be found in the BIN folder in the SharePoint root. The SPMetal tool targets an individual SharePoint site and, by default, generates the following code resources:
  • A data context class that derives from DataContext. This is the top-level entity class. It represents the content of your site and provides methods that allow you to retrieve list entities. The data context class uses the EntityList<TEntity> class to represent the lists in your site, where TEntity is a class that represents a content type.
  • Classes that represent content types. These are marked with the ContentTypeAttribute. Content type classes are generated for implicit content types as well as content types that are explicitly defined on the site. For example, if a user adds a column to an existing list, the user is creating an implicit content type and a representative class will be generated.
  • Classes and properties that represent relationships between lists. SPMetal can detect relationships based on lookup columns. Within the entity class that represents a content type, SPMetaluses the EntityRef<TEntity> class to represent the singleton side of a one-to-many relationship and the EntitySet<TEntity> class to represent the “many” side of one-to-many or many-to-many relationships (known as a reverse lookup). Properties that are mapped to a field in a related list are decorated with the AssociationAttribute.
Reference: