Saturday, September 27, 2014

Retrieve the web.config modifications

The following powerhsell script will retrieve the web.cofig modifications for sharepoint Web application.

Script:

$webApp = Get-SPWebApplication -Identity http://sharepointsite
$webApp.WebConfigModifications

Programmatically converting login name to claim and vice versa

SharePoint 2010 introduced Claims Based Authentication. One of the consequences of this is the fact that in order to use Forms Based Authentication (FBA) you need to configure your Web Application to use Claims instead of Classic Authentication. One of the many changes that you notice while working with claims are different login names: while in SharePoint 2007 you used something like myprovider:myuser, SharePoint 2010 makes the claims-soup of it: i:0#.f|myprovider|myuser. And while this is something you can take into account for newly created solutions, it can get confusing when upgrading SharePoint 2007 solutions to SharePoint 2010, especially if all you need is the user name. So is String.Replace the only way to get it out or is there a better way?
It turns out that retrieving the user name from its claims representation is pretty straight forward and can be done using the following code snippet:

Script:

string userName = null;
SPClaimProviderManager mgr = SPClaimProviderManager.Local;if (mgr != null){    userName = mgr.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).Value;}

Claims back and forth

string userName = null;
SPClaimProviderManager mgr = SPClaimProviderManager.Local;
if (mgr != null)
{
    SPClaim claim = new SPClaim(SPClaimTypes.UserLogonName, "myuser", "http://www.w3.org/2001/XMLSchema#string", SPOriginalIssuers.Format(SPOriginalIssuerType.Forms, "myprovider"));
    userName = mgr.EncodeClaim(claim);
}

In some scenario’s you might want to do the exact opposite: you might be starting off with a login name and will need to turn it over into the claims-based name. Just like in the previous scenario this can be easily done using the SPClaimProviderManager:

First we retrieve a reference to the Claims Provider Manager configured with the current Web Application. Then, using the DecodeClaim(string) method, we convert the string into SPClaim and retrieve its value, which contains the login name of the current user.
So, assuming you were logged in with the myuser account and the value of the SPContext.Current.Web.CurrentUser.LoginName property was something similar to i:0#.f|myprovider|myuser, calling the code snippet above would return myuser.

In some scenario’s you might want to do the exact opposite: you might be starting off with a login name and will need to turn it over into the claims-based name. Just like in the previous scenario this can be easily done using the SPClaimProviderManager.

Preserve the “Last modified” and “Modified by” field values for the SharePoint list

What is the general approach we follow when we try to add / edit a SPListItem using the SharePoint object model? Yes I know it! Almost everybody will have a common answer to this (which is something similar to what is provided below).

SPListItem item = SPList.Items.Add();
item["Column1"] = "value for column 1";
item["Column2"] = "value for column 2";
item.Update();

The last line in the code above "item.Update()" does the final task of updating all the assigned value for that specific item within the SPList.
But is this the only way to update an item? No, we can also update the same item using
item.SystemUpdate();

Then what is the difference between the two?

With item.Update(), we update the changes that are made to the list item. Is that all what it does? No, internally it also updates the "ModifiedBy" and "ModifiedOn" fields as per the current logged in user and current server time. Optionally it also updates the version of the item if the Versioning option is turned on for that specific list.
So, at any point if we wish not to update these extra things i.e. the "ModifiedOn", "ModifiedBy" and the "Item Version", then the solution for it is to use item.SystemUpdate() instead of item.Update(). This will help you in updating only those fields which are specified within your code blocks.

Query Suggestions Webpart in SharePoint 2013

SharePoint Search suggestions are automatically generated: When users have clicked any of the search results for that query at least six times, then that query will be automatically added to search suggestions.Technically, on a daily basis, the SharePoint timer job titled "Prepare Query Suggestions" handles compiling them. So the automatic query suggestions can be different for different result sources and site collections.

We cannot retrieve those details in any OOB webpart.
For this , we need to create querysuggestion webpart programmatically:

Script:

<script src="/sites/Test/Style%20Library/JS/jquery-1.3.2.min.js" type="text/javascript"></script><!-- Load our custom Rest Search script file --><script src="/sites/Test/Style%20Library/JS/restSearch.js" type="text/javascript"></script><script type="text/javascript">
    $(document).ready(function () {
        var query = "test";
        $.ajax({
            type: "GET",
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/suggest?querytext='" + query + "'&fprequerysuggestions='true'",
            headers:
                    {
                        "accept": "application/json;odata=verbose",
                    },
            success: function (data) {
                var results = data.getElementsByTagName("d:Query");
                var html = "<div class='results'>";
                for (var i = 0; i < results.length; i++) {
                    var resultValue = (results[i].nodeTypedValue).replace(/[</B>]/ig, "")
                    html += "<div class='result-row' style='padding-bottom:5px;'>";
                    var clickableLink = "<a href='/sites/Test/Pages/searcgtest.aspx?k=" + resultValue + "'>" + resultValue + "</a><br/>";
                    html += clickableLink;
                    html += "</div>";
                }

                $("#suggestResults").html(html);
            },
            error: function (err) {
                $("#suggestResults").html("<h3>An error occured</h3><br/>" + JSON.stringify(err));
            }
        });
       
    });
</script>
   <div id="suggestResults">
   </div>

Get and Update the web property of a sharepoint site

The following powershell script updates the web properties of a sharepoint site.

Script:
$wa = get-spweb -identity "http://sharepointsite"
$wa.AllProperties["EmployeeListName"] = "Employees"
$wa.update();

Some times, the above script will not work, then i have used the below script to retrieve and update the web property.

Script:
$web = get-spweb 'http://sharepointsite'
$web.GetProperty('EmployeeListName')
$web.SetProperty('EmployeeListName', 'Employees')
$web.Update()

The following powershell script will retrieve the web properties,

Script:
$web = get-web  –identity  http://sharepointsite
$web.properties()
$web.AllProperties()

Update the Site Logo using PowerShell script

The following script updates the site logo url to the new url.

Script:
$sites=(get-spsite http://sharepointsite).AllWebs
$sites| foreach {
$var=$_.SiteLogoUrl;
if($var.Contains("http://testsite/"))
{
$var1=$var.Replace("http://testsite/", "http://newsite/");
$_.SiteLogoUrl = $var1;
$_.Update()
}
}

Retrieve the List Item Count using PowerShell script


The following script will get the SharePoint List Item count for each list under each site collection. This script generated the output as CSV file.

Script:

cls
$ListsInfo = @()

$spsite= Get-SPSite -Limit All
foreach ($spsiteitem in $spsite)
{

$TotalItems = 0

ForEach ($Site in $spsiteitem.AllWebs)
{
    ForEach ($List in $Site.Lists)
    {
        $ListInfo=  New-Object System.Object
        $ListInfo | Add-Member -MemberType NoteProperty -Name "Site_Url" -Value $Site.Url -Force
        $ListInfo | Add-Member -MemberType NoteProperty -Name "List_Name" -Value $List.Title  -Force
        $ListInfo | Add-Member -MemberType NoteProperty -Name "Item_Count" -Value $List.ItemCount -Force
        $ListsInfo += $ListInfo
    }

}

$ListsInfo | Export-Csv -NoTypeInformation -Path "C:\ListData.csv"

}