Get UserProfile Object of Logged-in User

Tuesday, October 11, 2011

In this article, I will explain how to get UserProfile object for Logged-in User (current user).
//Function Call
UserProfile objUserProfile= GetProfileOfCurrentUser(SPContext.Current.Web.CurrentUser.LoginName)
public UserProfile GetProfileOfCurrentUser(string accountName)
        {
            UserProfile profile = null;
            try
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    return null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = SPContext.Current.Site;
                    ServerContext context = ServerContext.GetContext(site);

                    UserProfileManager profileManager = new UserProfileManager(context);
                    if (!profileManager.UserExists(accountName))
                    {
                        profile = null;
                    }

                    profile = profileManager.GetUserProfile(accountName);
                });
            }
            catch (Exception ex)
            {
                profile = null;
            }
            return profile;
        }

Event receiver to update an item's in list

How to update Created By and Modified By fields in sharepoint list using C#
In this article I will explain, how to update list item in event receiver. In event receiver, I will update Created By /Modified By/Title metadata of list item.
Code:

public override void ItemUpdated(SPItemEventProperties properties)
    {
        int userID=0;
        string userNTID = "WIN\AMITKUMAR";
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
        SPListItem CurrentItem = properties.ListItem;
        CurrentItem.Web.AllowUnsafeUpdates = true;
        CurrentItem.Web.Site.AllowUnsafeUpdates = true;
        // In the next statment i am updating CreatedBy(Author) filed with SystemAccount
        CurrentItem["Author"] = CurrentItem.Web.Site.SystemAccount.ID; //CreatedBy
        //We can also update CreatedBy(Author)/ModifiedBy(Editor) field with Any user account
         FindUserIDByNTID(userNTID, CurrentItem.Web.Site, ref userID);
         if (userID > 0)
         {
            CurrentItem["Editor"] = userID; //ModifiedBy
         }
         else
         {
            CurrentItem["Editor"] = CurrentItem.Web.Site.SystemAccount.ID; //ModifiedBy
         }
        CurrentItem["Title"] = "Amit Kumar";
        CurrentItem.Update();
        CurrentItem.ParentList.Update();
        CurrentItem.Web.Update();
        CurrentItem.Web.AllowUnsafeUpdates = false;
        CurrentItem.Web.Site.AllowUnsafeUpdates = false;
        });
    }
public static void FindUserIDByNTID(string userNTID, SPSite site, ref int userID)
        {
          try
            {
              //--Check user NTID is null or not
              if (!string.IsNullOrEmpty(userNTID))
              {
               //--userNTID is not null
               //--then fetch ID of the user
               userID = site.RootWeb.AllUsers[userNTID].ID;
              }
              else
              {
               //--If userNTID is null
               userID = 0;
              }
          }
        catch (ArgumentException ex)
            {
              userID = 0;
            }
      catch (Exception ex)
      {
      userID = 0;
      }
     }

Get unique value from Array (String/Integer):

Problem: In one of my project, I am getting values from one datasource in the form of .net Array. In the .NET Framework 3.5 there is a function called Distinct(). This Distinct() function return unique values from Array. This function works fine in the case of integer array. In string array, it not able to handle case sensitivity. If all items in the string array in same case, then it will work fine. Due to this, I was facing problem in getting unique value from String Array. Resolution: To Solve this problem, I have created functions, which used Stringcomparison. InvariantCultureIgnoreCase. .NET Framework 3.5: It is one line of code.
//If integer array
int [] intArr={5,2,3,3,5};
intArr = intArr.Distinct().ToArray(); // Output : intArr ={5,2,3}
//If string array
string [] strArr={“Amit”,”Amit”,”Kumar”,”Kumar”};
strArr = strArr.Distinct().ToArray(); //Output: strArr ={“Amit”,,”Kumar” }
string [] strArrCase={“Amit”,”AMIT”,”Kumar”,”KUMAR”,”Amit”,”Kumar”};
strArrCase = strArrCase.Distinct().ToArray(); //Output: strArrCase ={“Amit”,”AMIT”,”Kumar”,”KUMAR” }
Custom Function:
//Function call
string [] strArr={“Amit”,”Amit”,”Kumar”,”Kumar”};
strArr= GetUniqueArray(strArr); //Output: strArr ={“Amit”,”Kumar” }
        #region Get unique From Array
        public static string[] GetUniqueArray(string[] itemValues)
        {
            string stringList=string.Empty;
            string currentValue=string.Empty;
            string[] newArray=null;
            ArrayList uniqueList = new ArrayList();
            try
            {
                for (int counter = 0; counter < itemValues.Length; counter++)
                {
                    currentValue = Convert.ToString(itemValues[counter]);
                    if (!CheckDuplicateArray(currentValue, uniqueList))
                    {
                       uniqueList.Add(itemValues[counter]);
                    }
                }
                if (uniqueList.Count != 0)
                {
                    newArray = uniqueList.ToArray(Type.GetType("System.String")) as string[]; 
                }
            }
            catch (Exception ex)
            {
            }
            return newArray;
        }
        #endregion

        #region Check Duplicates From Array
        public static bool CheckDuplicateArray(string value, ArrayList uniqueList)
        {
            bool itemFound = false;
            try
            {
                foreach (string currentValue in uniqueList)
                {
                    if (string.Equals(value, currentValue, StringComparison.InvariantCultureIgnoreCase))
                    {
                        itemFound = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return itemFound;
        }
        #endregion

Render(Parse) XML using XSLT

Tuesday, September 06, 2011

Requirement:
The requirement is to render xml data into a page.
Resolution:
We can perform this task by following ways:
1. Read xml file using C#.Net and iterate the xml node. At the time of iteration, render data from xml to page.
2. Use the XSL. In this approach, create .XSLT file, which store the formatting in the form of HTML/CSS. By using XSL, we can separate the data rending from the data itself.
Example to render (parse) xml using xslt:
Save given xml in to file called "myNavigation.xslt":



  
    
  



Now add following tag in your .ASPX page:


In the code behind file of .ASPX page (.ASPX.CS file), add following directive:
using System.Xml;
using System.Xml.Xsl;

After that,in the code behind file of .ASPX page (.ASPX.CS file), write following code in the Page_Load method:

string languageDetails =
 @"
    
        
            
                
                
                
            
            
                
                
            
            
            
            
                
                
                
                
                
              
            
            
              
            
        
      ";
XmlDocument myNavigationDoc = new XmlDocument();
myNavigationDoc.LoadXml(languageDetails);

XslTransform myNavigationTransform = new XslTransform();
myNavigationTransform.Load(Server.MapPath("myNavigation.xslt"));

this.myNavigationControl.Document = myNavigationDoc;
this.myNavigationControl.Transform = myNavigationTransform;