Top Menu

Tuesday, January 14, 2014

Export Sharepoint User Profiles to CSV

I was looking for PowerShell script to export SharePoint User Profile data to a CSV and found this beautiful script by John Lynch.

I have made following little modification to the script:
  1. Export users which have special characters in their name by applying the UTF8 encoding.
  2. Check for manager field and show their display name instead of network id.
# Export Sharepoint User Profiles to CSV file
# Created: John Lynch 2013
# Updated: Tahir Naveed 2014
# MIT License

$siteUrl = "http://MySite.com"
$outputFile = "G:\UPAExport\UPAexport_20140428.csv"

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function GetDisplayName($UserName)
{
    $serviceContext = Get-SPServiceContext -Site $siteUrl
    $upm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
    $userProfile = $upm.GetUserProfile($UserName);
    $FullName = $userProfile.DisplayName
    return $FullName
}

$serviceContext = Get-SPServiceContext -Site $siteUrl
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
$profiles = $profileManager.GetEnumerator()

$fields = @(
            "UserName"
            "FirstName",
            "LastName",
            "PreferredName",
            "WorkPhone",
            "MobilePhoneFromAD",
            "HomePhone",
            "CellPhone",
            "Fax",
            "localTelephone",
            "SPS-Birthday",
            "WorkEmail",
            "PersonalSpace",
            "PictureURL",
            "Office",
            "title",
            "department",
            "manager",
            "SPS-School",
            "PersonalInterests",
            "LocationExperience",
            "HomeTown",
            "Assistant"
)

$collection = @()

foreach ($profile in $profiles) 
{
   $user = "" | select $fields
   foreach ($field in $fields) 
   {    
        if($profile[$field].Property.IsMultivalued) 
        {
            $user.$field = $profile[$field] -join "|"
        } 
        else 
        {
            if ($field -eq "manager" -or $field -eq "Assistant")
            {
                $DomainName = $profile[$field].Value;
                if ($DomainName -ne $null)
                {
                    $DisplayName = GetDisplayName $DomainName
                    $user.$field = $DisplayName
                }
            }
            else
            {
                $user.$field = $profile[$field].Value
            }
        }
       
   }
   $collection += $user
   Write-Host $user.UserName
}

$collection | Export-Csv $outputFile -NoTypeInformation -Encoding UTF8
$collection |  Out-GridView

Friday, December 6, 2013

SharePoint 2013 - Claim Information in a Web Part

I ran into a situation where I have to see what is the claims information for the current SharePoint user. You have to have Windows Identity Foundation (WIF) 4.5 installed on the SharePoint server in order to run the code.

Following is the updated version of the code I found on MSDN:

Ref: http://msdn.microsoft.com/en-us/library/ee517271.aspx
using Microsoft.IdentityModel.Claims;

protected override void CreateChildControls()
{
try
  {
      this.Controls.Add(new LiteralControl(GetClaimInfo()));
  }
  catch (System.Exception exp)
  {
       this.Controls.Add(new LiteralControl(exp.Message));
  }
}

public string GetClaimInfo()
{
    String strClaim = null;
    IClaimsPrincipal icp = Page.User as IClaimsPrincipal;

    // Access IClaimsIdentity which contains claims
    IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;

            
    // Access claims
    foreach (Claim claim in claimsIdentity.Claims)
    {
     strClaim = claim.Issuer + " - " + claim.ClaimType + " - " + claim.Value + "<br/>" + strClaim;
    }
    return strClaim;
}
Here is another version of the code to get all the AD groups for a user:
public string GetClaimInfo()
        {
            String strClaim = null;
            string strGroup = null;

            IClaimsPrincipal icp = Page.User as IClaimsPrincipal;

            // Access IClaimsIdentity which contains claims
            IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;

            
            // Access claims
            foreach (Claim claim in claimsIdentity.Claims)
            {
                if (claim.ClaimType.EndsWith("groupsid"))
                {
                    strGroup = new System.Security.Principal.SecurityIdentifier(claim.Value).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                    strClaim = claim.Value + " - " + strGroup + "<br/> " + strClaim;
                }
            }
            return strClaim;
        }

Tuesday, December 3, 2013

PowerShell - Get List Size

Following is the PowerShell script to get the size of a SharePoint list by calculating the size of the attachments for all items in a list:
function GetListSize($List)
{
    [long]$listSize = 0
    $allAttachmentsFolder = $List.RootFolder.SubFolders["Attachments"]

    foreach ($listItem in $List.Items)
    {                   
        $listItemAttachments = $listItem.Attachments
        $attachmentsFolder = $allAttachmentsFolder.SubFolders[$listItem.ID]
        foreach($file in $listItemAttachments) 
        {            
            $listSize += $attachmentsFolder.Files[$file].Length
        }
    }

    $totalInMb = ($listSize/1024)/1024
    $totalInMb = "{0:N2}" -f $totalInMb

    return $totalInMb    
}

Ref: http://sharepoint.stackexchange.com/questions/12652/get-total-size-of-attached-files-on-all-list-items-in-sharepoint-2007with-powers

Friday, November 15, 2013

Detect iPhone through JavaScript

Here is a quick script to redirect iOS (iphone and iPad) users to the mobile page.
<html>
<head>
<script type="text/javascript">
   if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
        window.location = "Default_m.aspx";
        }
</script>
</head>
<body>
     This is a non mobile page.
</body>
</html>
This script should be inside the head tag for performance. Script will redirect user to mobile page before the body of the page gets rendered.

Monday, November 11, 2013

SharePoint 2013 - Download MySite Profile Picture

Scenario:
There was a requirement to download all the profile pictures from SharePoint 2013 MySite and save them in different folders (based on user's domain name). After downloading images need to be resized to 30x30 pixels.


Solution:
I wrote following command line utility to achieve the goal.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;

namespace MySiteDownloader
{
    class Program
    {
        static string strURL = ConfigurationManager.AppSettings["MySiteURL"];
        static string strDomain = ConfigurationManager.AppSettings["Domain"];
        static string strLogin = ConfigurationManager.AppSettings["Login"];
        static string strPassword = ConfigurationManager.AppSettings["Password"];
        

        static void Main(string[] args)
        {
            Console.WriteLine("MySite Downloader");
            Console.WriteLine("=================");

            GetProfilePictures();

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }

        static void GetProfilePictures()
        {
            try
            {
                string strAccount = null;
                string strProfilePicURL = null;
                string strFileName = null;
                Uri uri = null;

                WriteLog("Getting user profiles from " + strURL);

                using (SPSite site = new SPSite(strURL))
                {
                    SPServiceContext context = SPServiceContext.GetContext(site);
                    UserProfileManager upm = new UserProfileManager(context);
                    WriteLog("Total user profiles found: " + upm.Count);

                    foreach (UserProfile profile in upm)
                    {
                        strAccount = profile.GetProfileValueCollection("AccountName").ToString();

                        try
                        {
                            strProfilePicURL = profile.GetProfileValueCollection("PictureURL").ToString();
                        }
                        catch(System.Exception ex)
                        {
                            strProfilePicURL = "";
                        }

                        WriteLog(strAccount + " - " + strProfilePicURL);

                        if (strProfilePicURL != "")
                        {
                            uri = new Uri(strProfilePicURL);
                            strFileName = System.IO.Path.GetFileName(uri.LocalPath);

                            DownloadPicture(strProfilePicURL, strAccount.Split('\\')[0], strFileName);
                        }
                    }

                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static  void DownloadPicture(string strPicURL, string strFolder, string strFile)
        {
            string FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + strFolder + "\\" + strFile.Replace("_MThumb", "");

            //File Download

            try
            {
                using (WebClient Client = new WebClient())
                {
                    if (!System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\" + strFolder))
                    {
                        System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\" + strFolder);
                    }

                    Client.Credentials = new NetworkCredential(strLogin, strPassword, strDomain);
                    Client.DownloadFile(strPicURL, FilePath);
                }

            }
            catch(System.Exception ex)
            {
                WriteLog(ex.ToString());
            }

            

            //Image Processing

            try
            {
                var image = Image.FromFile(FilePath);
                var newImage = ScaleImage(image, 30, 30);
                newImage.Save(FilePath.Replace("_MThumb", ""), ImageFormat.Png);
                //System.IO.File.Delete(FilePath);
            }
            catch (System.Exception ex)
            {
                WriteLog(ex.ToString());
            }

        }

        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }

        static void WriteLog(string strMessage)
        {
            Console.WriteLine(strMessage);

            string strLogMessage = string.Empty;
            string strLogFile = AppDomain.CurrentDomain.BaseDirectory;
            strLogFile += "MySiteDownloader.txt";
            StreamWriter swLog;

            strLogMessage = string.Format("{0}: {1}", DateTime.Now, strMessage);

            if (!File.Exists(strLogFile))
            {
                swLog = new StreamWriter(strLogFile);
            }
            else
            {
                swLog = File.AppendText(strLogFile);
            }

            swLog.WriteLine(strLogMessage);
            swLog.Close();

        }
    }
}
Note: Image re-sizing code has been copied from internet.

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="MySiteURL" value="http://mysite" />
    <add key="Domain" value="US" />
    <add key="Login" value="Login" />
    <add key="Password" value="Password" />
  </appSettings>
</configuration>

Free E-Books by Microsoft

Yup, you read it right. Free e-books from Microsoft.
http://social.technet.microsoft.com/wiki/contents/articles/11608.e-book-gallery-for-microsoft-technologies.aspx


Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...