Monday 19 November 2012

CSS selector

When it comes to selecting html tags by their ID or Class specifically in SharePoint you have id's that look like this"WebPartctl00_m_g_e7bf4283_529c_413e_884c_10c2adb8690a", now wtf is the jargon after webpart? I don't want to create a css selector that looks like

div#WebPartctl00_m_g_e7bf4283_529c_413e_884c_10c2adb8690a

so instead i'd use an attribute selector

div[id^="WebPart"] {
  font-size:1.5em
}

or i could use

div[id*="Part"] {
  font-size:1.5em
}

or if i hate myself

div[$="ctl00_m_g_e7bf4283_529c_413e_884c_10c2adb8690a"] {
  font-size=1.5em
}

so to sum it up

^= "selects text at the beginning of the attribute"
*= "selects text that's contained in our attribute"
$= "selects text at the end of the attribute"

Friday 16 November 2012

Simple jQuery & JavaScript Bubble Sort

jQuery is pretty powerful, and you should leverage it as much as possible. Someone might say but what if the client has javascript disabled? My response is simple, they don't even deserve to sort. anyway here's a quick example.

Here's the HTML

<html>
  <head>
    <title>Date Example</title>
    <script src = "jquery-1.6.1.js"></script>
    <script src = "script.js"></script>
  </head>
  <body>
    <input type = "button" value = "sort" onclick="sort();" />
    <div>Nov 12, 2012 1:00 PM EST</div>
    <div>Oct 09, 2012 5:00 PM EDT</div>
    <div>Nov 29, 2012 2:00 PM EST</div>
    <div>Oct 09, 2012 5:00 PM EDT</div>
    <div>Nov 09, 2012 2:00 PM EST</div>
    <div>Nov 19, 2012 2:00 PM EST</div>
    <div>Nov 09, 2012 2:00 PM EST</div>
    <div>Nov 29, 2012 2:00 PM EST</div>
    <div>Nov 05, 2012 12:00 AM EST</div>
    <div>Nov 08, 2012 9:10 AM EST</div>
  </body>
</html>

and followed by the JQuery

function sort()
{
  var swap = false
  var prev = null;
 
  do {
    prev = null;
    swap = false;
    $('div').each(
    function (indexelement)
    {
      if(prev != null && shouldSwap(prev,element))
      {
        $(this).after($(prev));
        swap = true;
      } 
  
      prev = element;
    });
  }while(swap)
}

function shouldSwap(d1d2)
{
  var dateOne = new Date($(d1).text());
  var dateTwo = new Date($(d2).text());
 
  return dateOne > dateTwo;
}

or if you prefer vanilla JavaScript (which I now do, since I haven't written JQuery in years)

function sort() {
  let swap = false
  let prev = null;
  let predicate = (d1d2=> new Date(d1) > new Date(d2);
  
  do { 
    prev = null;
    swap = false;
    const divs = [...document.getElementsByTagName("div")];
    
    divs.forEach((elementindex=> {
        if(prev != null && predicate(prev.innerText, element.innerText)) {
          element.after(prev);
          swap = true;
        } 
        prev = element;
   });
 } while(swap)
}

now you may notice this is not the most efficient bubble sort, it's a simple example to prove a point not efficiently sort 1'000'000 records.

Tuesday 13 November 2012

Populate List with Attachment

once in a while you'll need to create a list that contains an attachment; why not use a document library or a documents set, well i'll tell you why. When I came up with this i was a nOOb and had no idea what I was doing. So this example is by no means a best practice, but hey maybe one day I'll come across a scenario where it'll come in handy, so hey toss it into the old toolbox for later.



$RootURL = "http://ssrdevinter.corp.windsor/"

function LoadSharePointPowerShellEnviroment
{
write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}

function AddAttachment($item, $filePath)
{
    $bytes = [System.IO.File]::ReadAllBytes($filePath)
    $item.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes)
    $item.Update()
}
     
function CreateJobPosting($newJobPost, $Title, $PostingID, $StartDate, $EndTime, $DepartmentIndex, $DescriptionPath)  
{
    $newJobPost["Title"] = $Title
    $newJobPost["PostingID"] = $PostingID
    $newJobPost["StartDate"] =  $StartDate
    $newJobPost["EndDate"] = $EndTime
    $newJobPost["Department"] = 1
    AddAttachment $newJobPost $DescriptionPath
    $newJobPost.update()
   
    Write-Host -ForegroundColor Green Job Posting: $Title Completed
}
 
try
{
    LoadSharePointPowerShellEnviroment
    $RootSite = new-object Microsoft.SharePoint.SPSite($RootURL)
    $jobWeb = $RootSite.rootweb.webs["cityhall"].webs["work-for-windsor"]
    $JobPostingList = $jobWeb.lists["JobPostingsListInstance"]
 
    CreateJobPosting $JobPostingList.items.Add() "It Weather Widget Updater" "IT100" ([DateTime]::Now) ([DateTime]::Now.addDays(15)) 1 "c:\test.txt"
    CreateJobPosting $JobPostingList.items.Add() "Barista" "IT001" ([DateTime]::Now) ([DateTime]::Now.addDays(5)) 1 "c:\test.txt"
    CreateJobPosting $JobPostingList.items.Add() "Bard" "IT002" ([DateTime]::Now) ([DateTime]::Now.addDays(5)) 1 "c:\test.txt"
    CreateJobPosting $JobPostingList.items.Add() "Easter Bunny" "IT003" ([DateTime]::Now) ([DateTime]::Now.addDays(5)) 1 "c:\test.txt"

}
catch [Exception]
{
    Write-Host -ForegroundColor Red "Error in  Create job Postings$_"
}
finally
{
    $jobWeb.Dispose()
}  

Thursday 8 November 2012

List non published pages

This is a PowerShell snippet that lists all non published pages.


param($web_app_url=$(read-host "Please provide web app url of the list to be delete (EG:'http://SSRAP1'):"))
 
function LoadSharePointPowerShellEnviroment
{
write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}

function NonPublishedPagesReport($nodeWeb2)
{
    $pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($nodeWeb2)
    $pubPages = $PubWeb.GetPublishingPages()

    foreach($pp in $pubPages)
    {
        if ($pp.ListItem.File.level -ne "Published")
        {
            $data = @{"url" = $pubWeb.url.ToString() + "/pages/"
                      "name" = $pp.name.ToString()
                      "Status" = $pp.ListItem.File.level.ToString()
                      "user" = $pp.ListItem.File.CheckedOutByUser.LoginName
                      }
             New-Object PSObject -Property $data        
        }
    }
}

function RecurseNav([Microsoft.SharePoint.SPWeb]$nodeWeb)
{
    $subWebs = $nodeWeb.GetSubwebsForCurrentUser()
    NonPublishedPagesReport($nodeWeb)

    foreach ($nextweb in $subWebs)
    {
        RecurseNav($nextWeb)
    }
}


try
{
    if($web_app_url -eq $null -or $web_app_url -eq '')
    {
        throw "You must specify your server name. Value provided was null/empty."
    }
 
    $web = Get-SPWeb $web_app_url

    RecurseNav($web) | Out-GridView
}
catch [Exception]
{
    Write-Host -ForegroundColor Red "Error: $_"
}

Tuesday 6 November 2012

Elevated Privileges

In SharePoint once in a while you need to run something in an anonymous environment that requires user credentials not very promising is it? well luckily you can run your request using elevated privileges, you just need to remember to grab your site and your web again inside your delegate.

 string welcomePageURL = null;

 if (PublishingWeb.IsPublishingWeb(SPContext.Current.Web))
 {
       SPSecurity.RunWithElevatedPrivileges(delegate()
       {
           using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID))
           {
               using (SPWeb elevatedWeb = elevatedSite.OpenWeb(SPContext.Current.Web.ID))
               {
                   PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(elevatedWeb);
                   welcomePageURL= pWeb.DefaultPage.ServerRelativeUrl;
               }
           }
       });
   }

Friday 2 November 2012

Remove user From all Groups

PowerShell script to remove a user from all groups in a web app


param($web_app_url=$(read-host "Please provide web app url of the list to be delete (EG:'http://Wingtip'):"))

function LoadSharePointPowerShellEnviroment
{
write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}

try
{
    if($web_app_url -eq $null -or $web_app_url -eq '')
    {
        throw "You must specify your server name. Value provided was null/empty."
    }
   
    $UserToRemove = $(read-host "Please Provide the User to remove; include the domain eg: domain/smithj")
   
    if($UserToRemove -eq $null -or $UserToRemove -eq '')
    {
        throw "You must specify your user to remove. Value provided was null/empty."
    }
   
    LoadSharePointPowerShellEnviroment
   
    $site = new-object Microsoft.SharePoint.SPSite($web_app_url)
    $web = $site.OpenWeb()
   
    $web.SiteUsers.Remove($UserToRemove)
}
catch [Exception]
{
    Write-Host -ForegroundColor Red "Error: $_"
}  
finally
{
    $web.Dispose()
    $site.Dispose()
}

Delete All Groups

This script Deletes all SharePoint groups


param($web_app_url=$(read-host "Please provide web app url of the list to be delete (EG:'http://Wingtip'):"))

function LoadSharePointPowerShellEnviroment
{
write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}

try
{
    if($web_app_url -eq $null -or $web_app_url -eq '')
    {
        throw "You must specify your server name. Value provided was null/empty."
    }
   
    LoadSharePointPowerShellEnviroment
   
    $site = new-object Microsoft.SharePoint.SPSite($web_app_url)
    $web = $site.OpenWeb()
    $groups = $web.sitegroups
    $GroupsToDelete = @()
   
    foreach ($groupToDelete in $groups)
    {
        write-host "Group to Delete : ",$groupToDelete -foregroundcolor Magenta
        $GroupsToDelete += $groupToDelete.Name
    }
   
   
    foreach ($delgroup in $GroupsToDelete)
    {
        $web.SiteGroups.Remove($delgroup)
        write-host "Group Deleted : ",$delgroup -foregroundcolor Green
    }
   
}
catch [Exception]
{
    Write-Host -ForegroundColor Red "Error: $_"
}  
finally
{
    $web.Dispose()
    $site.Dispose()
}