About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.
Showing posts with label update. Show all posts
Showing posts with label update. Show all posts

Monday, 25 August 2014

Powershell Script - Modify Sharepoint web.config file entries

The following script will add/update SharePoint web.config file entries. The script accepts following input parameters. 

1. WebAppUrl - SharePoint web application url
2.WebConfigPath - Path for the SharePoint web application virtual directory

 Points to be noted
1. The following script backup existing web.config and add entries under configuration/appSettings & configuration/connectionStrings
 2. Provide input data in the form of .csv file with the separator as "$" with following header
 Configuration$Key$Value    
 Configuration is nothing but - the node where you want to add entries
3. The csv file should be in the same directory


Steps involved

1. Save following script as psUpdateSPWebApp.config.ps1


Param([Parameter(Mandatory=$true)]
      [String]
      $WebAppUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $WebConfigPath
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}

$objShell = New-Object -Com Shell.Application
$folder = $objShell.BrowseForFolder(0,"Please select the folder containing your CSV file:",0)
$pathfld = $folder.Self.Path
$fullpath = Join-Path $pathfld "xxxxx.csv"

# Show Farm BuildVersion to ensure the SharePoint .net library is loaded
$localFarm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$localFarm.BuildVersion

# store some settings and objects in variables
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppUrl)
$farmServices = @($webapp.Farm.Services | where-object { $_.TypeName -eq "Microsoft SharePoint Foundation Web Application" } )[0]


$currentDate = Get-Date -format MM-dd-yyyy-hh_mm_s # month-day-year - hours_mins_seconds
$backup = $WebConfigPath + "_$currentDate" + ".bak"

# Get the content of the config file and cast it to XML and save a backup copy labeled .bak followed by the date
$xml = [xml](get-content $WebConfigPath)
#save a backup copy
$xml.Save($backup)

$connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")

        if ($connectionStringsNode -eq $null)
        {        
        Write-Host "connectionStrings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $connectionStringsNode = $xml.CreateNode('element',"connectionStrings","")
        $configurationNode = $xml.configuration.AppendChild($connectionStringsNode)
        $connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created connectionStrings node" -ForegroundColor Green           
        }

$appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")

        if ($appSettingsNode -eq $null)
        {        
        Write-Host "appSettings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $appSettingsNode = $xml.CreateNode('element',"appSettings","")
        $configurationNode1 = $xml.configuration.AppendChild($appSettingsNode)
        $appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created appSettings node:" -ForegroundColor Green
        }

Import-Csv -Delimiter "$" -Path $fullpath | % {

if($_.Configuration -eq "appSettings")
{
    $appSettings = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
    $appSettings.Path = “/configuration/appSettings”;

    $appSettings.Name = [system.string]::format(“add[@key=""{0}""]“, $_.Key);
    $appSettings.Value = [system.string]::format(“<add key=”"{0}”" value=”"{1}”" />”, $_.Key, $_.Value);

   
    $appSettings.Sequence = 0
    $appSettings.Owner = “SharePoint”
    $appSettings.Type = 0

    $webapp = Get-SPWebApplication $WebAppUrl
    $webapp.WebConfigModifications.Add($appSettings)
    $webapp.Update()
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created appSettings key:" $_.Key -ForegroundColor Green
}

elseif($_.Configuration -eq "connectionStrings")
{
    $value = $_.Value
    $connectionString = New-Object "Microsoft.SharePoint.Administration.SPWebConfigModification"
    $connectionString.Path = "configuration/connectionStrings"
    $connectionString.Name = "ECConnectionString"
    $connectionString.Sequence = 0 
    $connectionString.Type = 0 
    $connectionString.Owner = "ECConnectionStringOwner"
    $connectionString.Value = $value
    $webapp.WebConfigModifications.Add($connectionString)  #Update the Web Application and apply all existing web.config modifications 
    $webapp.Update() 
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created connectionStrings key:" $_.Key -ForegroundColor Green
}

}# end of second import


Step2: Create batch file to run the script. Save file in .bat format.
cd /d %~dp0
powershell -file ./psUpdateSPWebApp.config.ps1 -WebAppUrl "xxxxx" -WebConfigPath "C:\inetpub\wwwroot\wss\VirtualDirectories\443\web.config"
pause
 

Happy powershell coding... please feel free to comment...

Wednesday, 11 December 2013

How to insert, update and delete items in SharePoint list

Introduction
SharePoint Provide many out of the box features. There is no need to write the code for inserting, updating or deleting the items in SharePoint lists or libraries. But sometimes we need to write the code for these tasks as per business requirements. For this SharePoint provides SDK to access the SharePoint objects and classes. This article describe you the way to insert, update or delete the items in SharePoint List.

Assumption

I presumed that you already have a basic background on how to write code using SDK. In this example, this time I used my own SharePoint List called Assignees which contains the following field columns:

ID (Auto Generated By SharePoint)
Title
Created (Auto Entered By SharePoint)
Created By (Auto Entered By SharePoint)

Code Snippet

First we need to create a object of SPWeb using the currently running site url:
   private const string _listName = "Assignees"; 
   private SPWeb _objWebsite; 
   private SPWeb ObjWebsite 
   { 
      get 
      { 
         if (_objWebsite == null) 
         { 
            SPSecurity.RunWithElevatedPrivileges(delegate() 
            { 
               using (SPSite oSite = new SPSite(SPContext.Current.Web.Url)) 
               { 
                  _objWebsite = oSite.OpenWeb(); 
               } 
            }); 
         } 
         return _objWebsite; 
      } 
   } 

Insert Item:
Use the following code to insert the item.

   public void InsertAssignee(string assigneeName) 
   { 
      SPListItemCollection objListItems = default(SPListItemCollection); 
      SPListItem objAssigneeItem = default(SPListItem); 
      SPQuery query = new SPQuery(); 
      query.Query = "<Where>" + 
                     "<Eq>" + 
                     "<FieldRef Name='Title' />" + 
                     "<Value Type='Text'>" + assigneeName.Trim() + "</Value>" + 
                     "</Eq>" + 
                     "</Where>"; 
      objListItems = ObjWebsite.Lists[_listName].GetItems(query); 
      if (objListItems == null || objListItems.Count <= 0) 
      { 
         objAssigneeItem = ObjWebsite.Lists[_listName].Items.Add(); 
         objAssigneeItem["Title"] = assigneeName.Trim(); 
         ObjWebsite.AllowUnsafeUpdates = true; 
         objAssigneeItem.Update(); 
         ObjWebsite.AllowUnsafeUpdates = false; 
      } 
   }




Update Item:
Use the following code to update the item.

   public void UpdateAssignee(string assigneeName, int id) 
   { 
      SPListItem objAssigneeItem = ObjWebsite.Lists[_listName].GetItemById(id); 
      if (objAssigneeItem != null) 
      { 
         objAssigneeItem["Title"] = assigneeName.Trim(); 
         ObjWebsite.AllowUnsafeUpdates = true; 
         objAssigneeItem.Update(); 
         ObjWebsite.AllowUnsafeUpdates = false; 
      } 
   }
Delete Item:

Use the following code to delete the item.

   public void DeleteAssignee(int id) 
   { 
      ObjWebsite.AllowUnsafeUpdates = true; 
      ObjWebsite.Lists[_listName].Items.DeleteItemById(id);
      ObjWebsite.AllowUnsafeUpdates = false; 

   }

I have used only one column while inserting item. You can use more columns as per your need.