Tuesday, 11 February 2014

PowerShell - Update default list view by adding 2 columns for all site under all site collection under specified Managed Path

PowerShell - Update default list view by adding 2 columns for all site under all site collection under specified Managed Path:-

<#
.SYNOPSIS
   <A brief description of the script>
.DESCRIPTION
   <A detailed description of the script>
.PARAMETER <paramName>
   <Description of script parameter>
.EXAMPLE
   <An example of using the script>
#>

$UrlDochubWebApp = Read-Host "Enter destination web app url"

$FieldPropetyInternalname = "Property"; # column 1
$FieldTitleInternalname = "Title"; # Column 2

#Loading Snap in for Microsoft.Sharepoint.Powershell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{

Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
$snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"

Write-Host $snapin
}

function updateView($list)
{
$View = $list.DefaultView;
$ViewFields = $View.ViewFields;
try
{
if(!$ViewFields.Exists($FieldTitleInternalname))
{
$ViewFields.add($FieldTitleInternalname);
$ViewFields.MoveFieldTo($FieldTitleInternalname,2);
}
if(!$ViewFields.Exists($FieldPropetyInternalname))
{
$View.ViewFields.add($FieldPropetyInternalname);
$View.ViewFields.MoveFieldTo($FieldPropetyInternalname,4);
}
$View.update();
}
catch [System.Exception]
{
Write-Host $_;
}

}

function updateLIbraries()
{
 $Webapplication =GEt-SPWebAPplication $UrlDochubWebApp


$AllLibraryNames = New-Object "System.Collections.Specialized.StringCollection"
$AllLibraryNames.Add("Library1") | Out-Null;
$AllLibraryNames.Add("Library2") | Out-Null ;
$AllLibraryNames.Add("Library3") | Out-Null ;
$AllLibraryNames.Add("LIbrary4") | Out-Null ;
if($Webapplication -ne $null)
{
$Allsites = $Webapplication.Sites
foreach($Site in $Allsites)
{
$siteUrl = $Site.Url;

foreach($web in $site.AllWebs)
{
try
{
$WebURl = $web.Url;
if(($web.Url.toLOwer() -match ("/debt/"))) # Condition to check managed path
{
$WebURl = $web.Url;
$allLists = $web.Lists;
$alllistsCount = $allLists.Count;
for($counter = 0;$Counter -lt $alllistsCount;$counter++)
{
$list = $allLists[$counter];
$ListTitle = $list.Title
$LIstITemCount = $list.ItemCount;
if(($list.BaseType -eq "DocumentLibrary") -and ($AllLibraryNames.Contains("$ListTitle") ) )
{
updateView $list;
}
}
Write-Host "Updated for $WebURl";
}
}
finally
{
$web.Dispose();
}
}
}
}

}

updateLIbraries;



PowerShell - Extract all files modified within a date range in a web application in to CSV file

PowerShell - Extract all files modified within a date range in a web application in to CSV file :-

$UrlDochubWebApp = Read-Host "Enter destination web app url" # http://<site url>
$fromDate = Read-Host "Enter From Date (Format YYYY-MM-DD)"; # files modified start date
$toDate = Read-Host "Enter To Date (Format YYYY-MM-DD)"; # file modified end date
$SiteCollFilePath = Read-Host "Enter SIte collection csv details Path(folder path)"
#Loading Snap in for Microsoft.Sharepoint.Powershell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{

Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
$snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"

Write-Host $snapin
}
$Webapplication =GEt-SPWebAPplication $UrlDochubWebApp
$SiteCollFilePath = "$SiteCollFilePath\ItemsCreated_$(get-date -format MMddyyHHmmss).csv";

$AllLibraryNames = New-Object "System.Collections.Specialized.StringCollection"
$AllLibraryNames.Add("library1") | Out-Null;
$AllLibraryNames.Add("library2") | Out-Null ;
$AllLibraryNames.Add("library3") | Out-Null ;
$AllLibraryNames.Add("library4") | Out-Null ;
$AllLibraryNames.Add("library5") | Out-Null ;
$dtToDate = Get-Date -Date $toDate
$dtFromDate = $dtFromDate.ToString("yyyy-MM-ddThh:mm:ss");
$dtToDate = $dtToDate.ToString("yyyy-MM-ddThh:mm:ss");
$strToBeInserted = "Site URL,Web Url,FileName,FileUrl,Created By,Created";

function LogData()
{
 Param ([string]$logstring)
Add-content $SiteCollFilePath -value $logstring
}

LogData $strToBeInserted;
if($Webapplication -ne $null)
{
$Allsites = $Webapplication.Sites
foreach($Site in $Allsites)
{
$siteUrl = $Site.Url;

foreach($web in $site.AllWebs)
{
try
{
$WebURl = $web.Url;
if(-not($web.Url.toLOwer() -match ("/scrapsite"))) # Condition to exclude a subsite named scrapsite..
{
foreach($list in $web.Lists)
{
$ListTitle = $list.Title
$LIstITemCount = $list.ItemCount;
if(($list.BaseType -eq "DocumentLibrary") -and ($AllLibraryNames.Contains("$ListTitle") ) -and ($LIstITemCount -gt 0))
{
$spQueryFilesAdded = New-Object Microsoft.SharePoint.SPQuery
$spQueryFilesAdded.Query="<Where><And><Geq><FieldRef Name='Created' /><Value Type='DateTime'>$dtFromDate</Value></Geq><Leq><FieldRef Name='Created' /><Value Type='DateTime'>$dtToDate</Value></Leq></And></Where>";
$spQueryFilesAdded.ViewAttributes="Scope='Recursive'";
$ItemsAdded = $list.getItems($spQueryFilesAdded);
if( $ItemsAdded.Count -gt 0)
{
foreach($item in $ItemsAdded)
{
$itemCreated = $item["Created"];
$itemCreatedBY = $item["Author"].ToString().Split("#".ToCharArray())[1];
$spFIle = $item.File;
$filename = $spFIle.Name;
$fileURl = $spFIle.URl;

$strToBeInserted = "$siteUrl,$WebURl,$filename,$fileURl,$itemCreatedBY,$itemCreated";

LogData $strToBeInserted;
}
}

}
}
}
}
finally
{
$web.Dispose();
}
}
}
}


PowerShell - Bulk Solution Deployment

PowerShell - Bulk Solution Deployment <Add & Install Solution> :-

#Loading Snap in for Microsoft.Sharepoint.Powershell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}

if ($snapin -eq $null)
{

Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
$snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"

Write-Host $snapin
}

$Path  = Read-HOst "Enter network folder path for WSPs (e.g F:\WSPs)"
#"F:\WSPs"
$WebApp = Read-Host "Enter Web Application URL (e.g http://<site URL>/)"
#"http://<Site URL>/"
Write-Host "Adding Solutions to solution store..." -ForegroundColor Yellow

Add-SPSolution -LiteralPath $Path\WebTemplates.Core.Features.wsp
Add-SPSolution -LiteralPath $Path\TEMPLATE.wsp
Add-SPSolution -LiteralPath $Path\Working.Site.wsp
Add-SPSolution -LiteralPath $Path\Presentation.wsp
Add-SPSolution -LiteralPath $Path\Master.wsp
Add-SPSolution -LiteralPath $Path\MasterpageExtension.wsp
Add-SPSolution -LiteralPath $Path\ContentTypes.wsp
Add-SPSolution -LiteralPath $Path\DocumentPromotion.wsp



Write-Host "Solutions uploaded to solution store !!!" -ForegroundColor Green

Write-Host "Deploying Solutions..." -ForegroundColor Yellow

Install-SPSolution -Identity WebTemplates.Core.Features.wsp -GacDeployment
Install-SPSolution -Identity TEMPLATE.wsp -GacDeployment
Install-SPSolution -Identity Working.Site.wsp -GacDeployment
Install-SPSolution -Identity Presentation.wsp -GacDeployment -Webapplication $WebApp
Install-SPSolution -Identity Master.wsp -GacDeployment
Install-SPSolution -Identity MasterpageExtension.wsp -GacDeployment
Install-SPSolution -Identity ContentTypes.wsp -GacDeployment
Install-SPSolution -Identity DocumentPromotion.wsp -GacDeployment


Write-Host "Solutions Deployed !!!" -ForegroundColor Green

PowerShell - Read data from SQL Table and Insert in to SharePoint List

PowerShell - Read data from SQL Table and Insert in to SharePoint List:-

#Gets the Powershell snapin
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
#Checking the snapin
if ($snapin -eq $null)
{

Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
$snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"

Write-Host $snapin
}

#Creating sql connection
WRite-HOst "Moving XREF information to Sharepoint list"
$con = New-Object System.Data.SqlClient.SqlConnection
#Providing sql connection string
    $con.ConnectionString = "Server=<Server Name>;Database<Database Name>;Integrated Security=false;user id=<User Id>;password=<Password>";
    # Opening the connection
    $con.open()
    #Creating new sql command
    $cmd = New-Object System.Data.SqlClient.SqlCommand
    #Providing query to command
    $cmd.CommandText = "select lm.LOAN as Loan,eg.XREF as Xref from LNMAST LM,egeneral eg WHERE lm.LOAN = eg.LOAN and XREF is not null and XREF != '' order by lm.LOAN asc"
    #Providing connection to command
    $cmd.Connection = $con
 
    # Create SqlDataAdapter object and set the command
    $da = New-Object System.Data.SqlClient.SqlDataAdapter
    $da.SelectCommand = $cmd

    # Create and fill the DataSet object
    $LMSDataTable = New-Object System.Data.DataTable
    $da.Fill($LMSDataTable)
    #Closing the sql connection
    if($con -ne $null)
    {
        $con.close();
    }
 
    [Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(

    {

 #Getting the web site
    $DebtWeb=Get-SPWeb "http://<Machine Name>:8800/<Subsite>/"
    #Getting the List
    $mylist = $DebtWeb.Lists["Mapping"] # List Name
 
    $Items = $mylist.GetItems()
    $Items | ForEach-Object{$mylist.GetItemById($_.Id).Delete()}
    $mylist.Update()
 
    #looping lms datatable
    foreach ($row in $LMSDataTable.Rows) {
 
 
    #adding new item in list
 
    $newItem = $mylist.Items.Add()
    #assigning values to list columns
    $newItem["Title"] = $($row["Loan"])
    $newItem["LoanNumber"] = $($row["Loan"])
    $newItem["XrefNumber"] = $($row["Xref"])
    #updating list item
    $newItem.Update()
 


    }

   }

)

 

    #End
    WRite-HOst "XREF information moved to Sharepoint list"

Create Managed Path using PowerShell

Create Managed Path using PowerShell

$Webappname = Read-Host "Enter web application URL"
#"http://testsite.com"

$mPathEquity = "equity" # manged Path 1
$mPathDebt = "debt" # manged Path 2

function Create-SPManagedPath
{
param ($webApplicationUrl, $managedPathName)
$managedPath = Get-SPManagedPath -WebApplication $webApplicationUrl -Identity $managedPathName -ErrorAction SilentlyContinue
if ($managedPath -ne $null)
{
Write-Host "Managed path $managedPathName already exists."
return
}
Try
{
Write-Host "Creating managed path $managedPathName ..."
New-SPManagedPath –RelativeURL $managedPathName -WebApplication $webApplicationUrl

Write-Host "Managed path $managedPathName created sucessfully" -foregroundcolor Green
}
catch [Exception]
{
Write-Host   $_.Exception.ToString()
}
}

 Write-Host "Creating Managed Paths" -foregroundcolor Yellow
 Create-SPManagedPath  $Webappname $mPathDebt
 Create-SPManagedPath  $Webappname $mPathEquity
 Write-Host "Completed Creating Managed Paths" -foregroundcolor Green

Wednesday, 29 January 2014

How to use Status Bar in SharePoint 2010?

How to use Status Bar in SharePoint 2010?


In SharePoint 2010, Status bar is used to display information/warnings without disturbing user with Javascript alerts. Please don't think it is Browser's Status bar. It's a special information bar which displays below ribbon/top bar when invoked. No Server side code or manual setup required to enable status bar. The required functions are bundled in SP.UI.Status class that defined in SP.Js/SP.Debug.Js and it's included in SharePoint master page. So no need to include Js manualy to use Status bar.

Well, Javascripts alerts are not helpful to display HTML content, images, links. Where Status bar accepts HTML content and can be invoked just with Javascript.

SP.UI.Status Functions
The SP.UI.Status class has 6 functions. They are
  1. SP.UI.Status.addStatus(strMessageHeading, strHTMLContent, boolAtBegining) This function used to display specified content in Status bar. The parameters are self explanatory. boolAtBegining parameter specifies whether this content should be shown at First(just like to give priority) and it's useful when more than one status messages invoked.
  2. SP.UI.Status.appendStatus(strStatusID, strHTMLContent) This function appends HTML content with an existing status bar content.
  3. SP.UI.Status.updateStatus(strStatusID, strHTMLContent) This function updates/replaces existing HTML content with given HTML content.
  4. SP.UI.Status.setStatusPriColor(strStatusID, strColor) This function sets/changes the color of status bar. Only four colors[red, yellow, green, blue] are allowed which specifies the priority. Red - High Priority, yellow, green, blue - Low Priority. When two colors applied on same status bar then High priority color will be considered by SharePoint.
  5. SP.UI.Status.removeStatus(strStatusID) This function removes the specific Status bar.
  6. SP.UI.Status.removeAllStatus(boolHideStatus) This function removes all Messages. If the boolHideStatus passed as true then it'll hide all status bar with messages. Otherwise it'll hide only Status Message but a thin status bar will remains in place.
How to add code?
Follow the steps to add Content Editor Webpart and add HTML/Javascript Code.
  1. Site Actions -> Edit Page (or Edit page Icon on top bar)
  2. Click Editing Tools(Tab) -> Insert (Tab) -> Webpart
  3. Select Media and Content (Section) -> Content Editor.
  4. Select Content Editor Webpart (Black triangle on top right of the webpart)-> Edit Webpart.
  5. Editing Tools (Tab) -> Format Text -> HTML -> Edit HTML Source.
Edit HTML Content of Content Editor WebPart
Demo Code
 <Script type="text/javascript">
var
 strStatusID;function showInfo()
{
  strStatusID = SP.UI.Status.addStatus(
"Information : ", "<img src='/_Layouts/Images/STS_ListItem_43216.gif' align='absmiddle'> <font color='#AA0000'>Registration process <i>completed</i>.</font>", true);
  SP.UI.Status.setStatusPriColor(strStatusID, 
"yellow");
}

function
 appendInfo()
{
  SP.UI.Status.appendStatus(strStatusID, 
" Next : ", " <b>You can <a href='Login.aspx'>Login Now</a>", false);
  SP.UI.Status.setStatusPriColor(strStatusID, 
"blue");
}
function updateInfo()
{
  SP.UI.Status.updateStatus(strStatusID, 
"Status Update: This content updated with " + strStatusID + " using updateStatus");
  SP.UI.Status.setStatusPriColor(strStatusID, 
"green");
}
function updateInfoRed()
{
  SP.UI.Status.setStatusPriColor(strStatusID, 
"red");
}
function removeInfo()
{
  SP.UI.Status.removeStatus(strStatusID);
}
function removeAllInfos()
{
  SP.UI.Status.removeAllStatus(
true);
}
</Script>

<
div class="ms-toolpanefooter">
  <
input type="button" onclick="Javascript:showInfo();" value="Show Info" class="UserButton" /> 
  <
input type="button" onclick="Javascript:appendInfo()" value="Append Info" class="UserButton" />   <input type="button" onclick="Javascript:updateInfo()"value="Update Info" class="UserButton" /> 
  <
input type="button" onClick="Javascript:updateInfoRed()" value="Make Red" class="UserButton" />   <input type="button" onClick="Javascript:removeInfo()" value="Remove Info" class="UserButton"/>
  
<input type="button" onClick="Javascript:removeAllInfos()" value="Remove All Infos" class="UserButton"/>
</
div>
Add Status
Append Status
Update Status
Change Color of Status Bar
Remove Status


Status bar is used at client side(browser) to display message. If you want to fetch data from status bar then use a hidden variable and assign same value which u pass to status bar via Java Script.
If you want to pass data from Server side to client side then

Add the below function in Javascript.
function showInfo(strMessage)
{
strStatusID = SP.UI.Status.addStatus(strMessage, true);
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
Add a label "lblScripter"
Then in Server Side Code add
lblScripter.Text = "<Script language='javascript;>showInfo('" + strYourMessage + "');</script>";
This will invoke the Javascript and show the statusbar. 

How to Hide Top Bar, Ribbon, Quick Launch in SharePoint 2010?

How to Hide Top Bar, Ribbon, Quick Launch in SharePoint 2010?

Top Bar, Ribbon, Quick Launch are come up with Application Pages by default. If you want to open the page in Dialog Framework then those elements will take more space and make the layout cluttered. You can remove these elements by creating new page layout which is cumbersome/time consuming.
One way to hide these controls is by passing a Parameter with the URL. [ ?IsDlg=1 ] SharePoint will hide these elements when It gets IsDlg Parameter on URL.
But every time we can't pass these parameters. Then how to get rid of these elements?
Simple Just add the below css Code in Application Page under PlaceHolderMain section.
<style type="text/css">
    #s4-ribbonrow, .ms-cui-topBar2, .s4-notdlg, .s4-pr s4-ribbonrowhidetitle, .s4-notdlg noindex, #ms-cui-ribbonTopBars, #s4-titlerow, #s4-pr s4-notdlg s4-titlerowhidetitle, #s4-leftpanel-content {display:none !important;}
    .s4-ca{margin-left:0px !important; margin-right:0px !important;}
</style>
This will hide the elements and only the content will be shown.
Note : If you use this code in SharePoint Site Pages with Content Editor Webpart then you can't check in the page since the toolbar goes hidden.
If you still want to use this code on Site Pages then add Content Editor Webpart and paste the above code. When you want to make other changes then open the page in browser with parameters [ ?Contents=1 ] which opens the page in WebPart maintenance mode. Remove the content editor webpart and re-open the page. Make the changes and add content editor webpart at last along the CSS Code. To check in the page use Site Pages Library.