Monday, June 9, 2014

Tips and Trick for SharePoint

Fix “Connect-SPOService : The term ‘Connect-SPOService’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.” Error

1. You can download and install SharePoint Online Management Shell to your client machine
   https://www.microsoft.com/en-us/download/details.aspx?id=35588

follow below steps
1. Navigate to “C:\Windows\Microsoft.NET\assembly\GAC_MSIL”
2. Select all folders starting with name “Microsoft.SharePoint.Client” and delete them all!
3. Finally, Install the PowerShell Module for SharePoint Online: Install-Module Microsoft.Online.SharePoint.PowerShell -force

for more details:
Get-Module -Name Microsoft.Online.SharePoint.PowerShell -ListAvailable | Select Name,Version 
Install-Module Microsoft.Online.SharePoint.PowerShell 
Uninstall-Module -Name Microsoft.Online.SharePoint.PowerShell -AllVersions -Force
===
Additions to this Web site have been blocked. Please contact the administrator to resolve this problem.
Troubleshoot issues with Microsoft SharePoint Foundation.

Solution:-
Open SharePoint 2010 Management Shell.
Get-SPSite <site collection url> | select ReadOnly,Readlocked,WriteLocked,LockIssue | ft –autosize
Set-SPSite <site collection url> -LockState Unlock
------------------------------------------------------------------------------------------------------------
SharePoint:DateTimeControl make it as read only in SharePoint

<script type="text/javascript" src="../SiteAssets/jquery-1.11.0.js"></script>
$(document).ready(InIEvent);
    function InIEvent() {
              var x = document.getElementsByTagName("INPUT");
for (var i = 0; i < x.length; i++) {
if (x(i).id.indexOf("DateReceived") > 0) {
x(i).setAttribute('readonly', 'readonly');
}
}
}
<SharePoint:DateTimeControl ID="DateReceived" runat="server" EnableViewState="true" DateOnly="true" />
------------------------------------------------------------------------------------------------------------
Restore-SPSite : The operation that you are attempting to perform cannot be completed successfully.  No content databases in the web application were available to store your site collection.  The existing content databases may have reached the maximum number of site collections, or be set to read-only, or be offline, or may already contain a copy of this site collection.  Create another content database for the Web application and then try the operation again.
At line:1 char:15
+ Restore-SPSite <<<<   -Path \\server-123\23-June-2014\hr_prod.dat -Force
    + CategoryInfo          : InvalidData: (Microsoft.Share...dletRestoreSite:
   SPCmdletRestoreSite) [Restore-SPSite], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletRestoreS
   ite

solution:-
1. first delete this site collection "http://server-123:2014/sites/hrsite"
2. $site = Get-SPSite http://server-123:2014/sites/hrsite
   $siteguid = $site.id
   echo $siteguid
  
3. Remove-SPDeletedSite -Identity b233ba86-a9f9-476d-99ac-6ba6815f85fc
4. Now create a new site collection.
5. Perform Restore-SPSite operation
------------------------------------------------------------------------------------------------------------
Open PowerShell and type syntax as follows....
1.  PS C:\Users\Administrator> get-splogevent |?{$_.correlation -eq "e2455748-780d-4387-8b6d-812419a6403a"}|select area,cate
gory, level, eventid, message|format-list

2.  PS C:\Users\Administrator>get-splogevent | ?{$_.Correlation -eq "2872bd2d-a0a5-4cac-b218-f504a7d2a4c5"} | ft Category, Message -Autosize
Tools: 1. UlsViewer
          2. SPLogViewer
------------------------------------------------------------------------------------------------------------

Issue:
Invalid data has been used to update the list item. The field you are trying to update may be read only.
I am getting above error when i use below code...

           ClientContext clientContext = new ClientContext("SPHostUrl");
            clientContext.Load(clientContext.Web);
            clientContext.Load(clientContext.Web, w1 => w1.ServerRelativeUrl, w1 => w1.Url);
            clientContext.ExecuteQuery();
Solution:-
When i replace with below code issue resolved....
            ClientContext clientContext = new ClientContext("SPHostUrl");
            Web web = clientContext.Web;
            clientContext.Load(web, w1 => w1.ServerRelativeUrl, w1 => w1.Url);
            clientContext.ExecuteQuery();
------------------------------------------------------------------------------------------------------------
Add XsltListViewWebPart WebPart into aspx page.
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <WebPartPages:WebPartZone ID="Main" Title="Main Web Part Zone" FrameType="TitleBarOnly" runat="server">
        <ZoneTemplate>
            <WebPartPages:XsltListViewWebPart
                runat="server"
                ID="ProductsWebPart"
                Title="Products"
                ListUrl="Lists/Products"
                ChromeType="None"
                InplaceSearchEnabled="true">
            </WebPartPages:XsltListViewWebPart>
        </ZoneTemplate>
    </WebPartPages:WebPartZone>
</asp:Content>
------------------------------------------------------------------------------------------------------------
SharePoint Designer Clear all Cache
%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache
%APPDATA%\Microsoft\Web Server Extensions\Cache
%APPDATA%\Microsoft\SharePoint Designer\ProxyAssemblyCache

SharePoint Designer -> Run as different user
C:\Program Files (x86)\Microsoft Office\Office15\SPDESIGN.exe
------------------------------------------------------------------------------------------------------------
The default size limit for a site template is 50 MB. To increase the limit to the maximum allowed, use the following Stsadm command syntax.

stsadm -o setproperty -pn max-template-document-size -pv 524288000
------------------------------------------------------------------------------------------------------------
Configuring Office Web Apps for SharePoint 2013:-
Office web apps are browser based versions of Word, PowerPoint, Excel and OneNote that allows users to view and edit documents.  With services provided by Office Web Apps, users do not need the Office clients installed on their computers.

Disconnect Office Web Apps for SharePoint 2013:-
Open "SharePoint 2013 Management Shell" with run as administrator.
1. Remove-SPWopiBinding -All
2. IISRESET

Connect Office Web Apps for SharePoint 2013:-
1. New-SPWopiBinding –ServerName <SharePoint_Server_Name> -allowhttp
2. Set-SPWopiZone -Zone "internal-https"
3. IISRESET
------------------------------------------------------------------------------------------------------------
The Enterprise licensing category provides access to Enterprise CAL features to include:-
1. InfoPath Form Web part
2. Excel Web Access
3. Visio Web Access
4. PerformancePoint Filter
5. PerformancePoint Report
6. PerformancePoint Scorecard
7. PerformancePoint Stack Selector
8. Taxonomy Refinement Panel
9. Catalog-Item Reuse
10. Search-Driven Content (all web parts in this category)
11. Business Data Actions
12. Business Data Connectivity Filter
13. Business Data Item
14. Business Data Item Builder
15. Business Data List
16. Business Data Related List

The feature categories are Unlicensed, Standard, and Enterprise.
The licensable entities include:-
1. AccessServices
2. BCS
3. Duet
4. InfoPath
5. PPS
6. Project
7. EntSearch
8. VisioServices
9. WAC
10. ExcelServices
11. MySites

User License Enforcement cmdlets:-
Cmdlet name : Description
Get-SPUserLicensing : Returns the state of user-license enforcement.
Enable-SPUserLicensing : Enables user license enforcement.
Disable-SPUserLicensing : Disables user-license enforcement.
Get-SPUserLicense : Returns the list of supported SharePoint user licenses.
Get-SPUserLicenseMapping : Returns the claim-to-user license mappings.
New-SPUserLicenseMapping : Creates a license mapping object.
Add-SPUserLicenseMapping : Maps a security group, forms-based role, or claim to a SharePoint user license.
Remove-SPUserLicenseMapping : Removes a claim-to-SharePoint user license mapping.

Enabling and Disabling User License Enforcement:-
Opne "SharePoint 2013 Management Shell" as a administrator.
1. Get-SPUserLicensing
2. Disable-SPUserLicensing //<Disabling User Licensing>
3. Enable-SPUserLicensing //<Enabling User Licensing>

Creating and Removing User License Mapping Objects:-
1. Get-SPUserLicense
2. Get-ADGroup –filter 'GroupCategory –eq "Security" –and GroupScope –eq "Global"'

Mapping a security group to a SharePoint User License:-
1. $a = New-SPUserLicenseMapping -SecurityGroup <SecurityGroupName_a> –License Enterprise
2. $b = New-SPUserLicenseMapping –SecurityGroup <SecurityGroupName_b> –License Standard
3. Add-SPUserLicenseMapping –Mapping $a
4. Add-SPUserLicenseMapping –Mapping $b

Creating a new User License Mapping Object:-
1. New-SPUserLicenseMapping –License Enterprise –SecurityGroup <SecurityGroupName_a> –WebApplication <SharePoint_Site_URL>
2. NEW-SPUserLicenseMapping –License Standard –SecurityGroup <SecurityGroupName_b> –WebApplication <SharePoint_Site_URL>
3. Get-SPUserLicenseMapping –WebApplication <SharePoint_Site_URL>

Remove a SharePoint User License Mapping Object:-
1. Get-SPUserLicenseMapping –WebApplication <SharePoint_Site_URL>
2. Remove-SPUserLicenseMapping –Identity <GUID>
3. Get-SPUserLicenseMapping –WebApplication <SharePoint_Site_URL>

Verify Users with Standard and Enterprise User Licenses:-
1. In the Web Parts Categories, click on Business Data.  We’ll notice "Indicator Details" Web Part available to user.

Verify Enterprise CAL Features for Danield:-
1.  In the Web Parts Categories, click on Business Data.  We’ll notice that User has the Several Web Parts available.  These additional web parts are only available to users with the Enterprise CAL.
------------------------------------------------------------------------------------------------------------
Find SharePoint Version:
open site in chrome -> press F12 -> Network tab
------------------------------------------------------------------------------------------------------------
Log File Cleanup:-
Function SPLogsCleanup
{
    $Days = "90"
    $FileType = "*.log"
    $TargetFolder = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS"
    if (Test-Path $TargetFolder)
    {
        $Now = Get-Date
        $LastWrite = $Now.AddDays(-$days)
        $Files = get-childitem $TargetFolder -include $FileType -recurse | Where {$_.LastWriteTime -le "$LastWrite"}
        foreach ($File in $Files)
        {
            write-host "Deleting file $File" -foregroundcolor "Yellow"; Remove-Item $File | out-null}
    }
    Else
    {
        Write-Host "Folder $TargetFolder Does not exist! Check folder path"
    }
}
SPLogsCleanup
------------------------------------------------------------------------------------------------------------
error: {"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"A type named 'SP.Data.temp01ListItem' could not be resolved by the model. When a model is available, each type name must resolve to a valid type."}}}

Ans: SharePoint List name should not end with number. In my case List name is "temp01", so I receive error message. To avoid this error recreate the list with no numbers in last.
------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
Get-Process | Export-Csv C:\Windows\Temp\process.csv
-------
Get-Process | Get-Member
Get-Process | Select Name,Path,Company | Export-Csv C:\Windows\Temp\FilteredProcess.csv
-------
Get-Process | Select Name, Path, Company | Export-Csv C:\Windows\Temp\FilteredProcessNTI.csv -NoTypeInformation
-------
Get-Process | Select Name, Path, Company | Export-Csv -Path "C:\Windows\Temp\FilteredProcessSemiColumn.csv" –NoTypeInformation -Delimiter ';'
-------
Get-Process | Select Name, Path, Company | Export-Csv C:\Windows\Temp\FilteredProcessNTIUniCode.csv –NoTypeInformation -Encoding "Unicode"
-------
get-aduser -filter *  -properties department, Name, Manager,Title  | where {$_.department -eq "Marketing"} | Select UserPrincipalName,Name,Title,@{N='Manager';Expression={(Get-ADUser $_.Manager).Name}} | Export-CSV C:\Windows\Temp\MarketingUsers.csv -NoTypeInformation
-------
Get-WmiObject Win32_logicaldisk -ComputerName LocalHost `
| Select `
@{Name="Drive Letter";Expression={($_.DeviceID)}},`
@{Name="Size(GB)";Expression={[decimal]("{0:N2}" -f($_.size/1gb))}}, `
@{Name="Free Space(GB)";Expression={[decimal]("{0:N2}" -f($_.freespace/1gb))}}, `
@{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} `
| Export-CSV C:\Windows\Temp\FreeDiskInformation.csv -NoTypeInformation
-------
Get-MsolUser -All | where {$_.isLicensed -eq $true}| Select UserPrincipalName,DisplayName,Department,@{N='License';Expression={$_.Licenses.AccountSkuId}} | Export-CSV C:\Windows\Temp\licenses.csv -NoTypeInformation -Delimiter ";"
-------
$users = import-csv Users.csv
foreach ($user in $users)
{
     $UserName = $user.Name
     $UserDept = $user.Department
     $UserTitle = $user.title
     Write-host "$username is a $usertitle in the $userdept department."
}
-------
$users = import-csv Users.csv
foreach ($user in $users)
{
    $FirstName = $user.FirstName
    $LastName = $user.LastName
    $Country = $user.Country
    $City = $user.city
    $Title = $user.title
    $department = $user.department
    $Office = $user.Office
    $DisplayName = $LastName + ", " + $FirstName
    $UserName = $FirstName + "." + $LastName + "@globomantics.org"
    New-MsolUser -DisplayName $DisplayName -UserPrinciPalName $UserName -FirstName $FirstName -LastName $LastName -Country $Country -City $city -Title $title -Department $department -Office $office -UsageLocation $Country -LicenseAssignment "globomanticsorg:ENTERPRISEPACK" -State $user.state
}
-------
$SC = Import-CSV SiteInput.csv
foreach ($site in $SC)
{
    $url = "https://sharepointonline.sharepoint.com/sites/" + $site.SiteUrl
    $Title = $Site.SiteName
    $Owner = $Site.Owner
    New-SPSite -Url $url -Name $Title -OwnerAlias $Owner -Template STS#0
}
-----------------------------------------------------------------------------------------------------------------------------------
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="../_layouts/15/clientpeoplepicker.js"></script>
    <style type="text/css">
        * html .ui-autocomplete {
            height200px !important;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            AutoComplete_SP_List_Name();
            SP.SOD.executeOrDelayUntilScriptLoaded(AutoPopulate_SP_List_Name"SP.js");
        });

        function AutoComplete_SP_List_Name() {
            var url = _spPageContextInfo.webAbsoluteUrl +
                "/_api/web/lists/GetByTitle('SP_List_Name')/items?$filter=substringof('" +
                request.term + "',LinkTitle)&$top=100&$select=LinkTitle,ID";
            $($("input[id^='Name_Of_Employee']")[0]).autocomplete({
                source: function(requestresponse) {
                    $.ajax({
                        url: url,
                        type: "GET",
                        headers: {
                            Accept: "application/json;odata=verbose"
                        },
                        async: false,
                        cache: false,
                        beforeSend: function() {
                            //console.log("beforeSend");
                        },
                        success: function(datastatusxhr) {
                            arraySP_List_Name = [];
                            for (i = 0i < data.d.results.lengthi++) {
                                arraySP_List_Name.push(data.d.results[i]["LinkTitle"]);
                            }
                            arraySP_List_Name = $.unique(arraySP_List_Name);
                            response(arraySP_List_Name);
                            //console.log("success");
                        },
                        error: function(xhrstatuserror) {
                            console.log("error: " + xhr.responseText);
                        },
                        complete: function() {
                            //console.log("complete");
                        }
                    });
                },
                minLength: 2
            });
        }

        function AutoPopulate_SP_List_Name() {
            var url = _spPageContextInfo.webAbsoluteUrl +
                "/_api/web/lists/GetByTitle('SP_List_Name')/items?$filter=substringof('" +
                $("input[id^='Name_Of_Employee']").val().trim() +
                "',LinkTitle)&$top=1&$select=ID,LinkTitle,User_Approver_1/EMail&$expand=User_Approver_1";
            $($("input[id^='Name_Of_Employee']")[0]).blur(function() {
                if ($("input[id^='Name_Of_Employee']").val().trim() != "") {
                    $.ajax({
                        url: url,
                        type: "GET",
                        headers: {
                            Accept: "application/json;odata=verbose"
                        },
                        async: false,
                        cache: false,
                        beforeSend: function() {
                            //console.log("beforeSend");
                        },
                        success: function(datastatusxhr) {
                            if (data.d.results.length > 0) {
                                for (i = 0i < data.d.results.lengthi++) {
                                    $("input[id^='Name_Of_Employee_']").val(data.d.results[i]["LinkTitle"]);
                                    var loginName_Approver_1 = data.d.results[i]["User_Approver_1"]["EMail"]
                                    var controlName_Approver_1 = "Aapprover list column display title";
                                    var ppDiv_Approver_1 = $("[id$='ClientPeoplePicker'][title^='" + controlName_Approver_1 + "']");
                                    var ppEditor_Approver_1 = ppDiv_Approver_1.find("[title^='" + controlName_Approver_1 + "']");
                                    var spPP_Approver_1 = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv_Approver_1[0].id];
                                    var usersobject_Approver_1 = spPP_Approver_1.GetAllUserInfo();
                                    usersobject_Approver_1.forEach(function(index) {
                                        spPP_Approver_1.DeleteProcessedUser(usersobject_Approver_1[index]);
                                    });
                                    ppEditor_Approver_1.val(loginName_Approver_1);
                                    spPP_Approver_1.AddUnresolvedUserFromEditor(true);
                                }
                                //console.log("success");
                            } else {
                                $("input[id^='Name_Of_Employee_']").val("");
                                var controlName_Approver_1 = "Aapprover list column display title";
                                var getIDPeoplePicker_Approver_1 = $("div[Title^='" + controlName_Approver_1 + "']").attr("id");
                                var ppobject_Approver_1 = SPClientPeoplePicker.SPClientPeoplePickerDict[getIDPeoplePicker_Approver_1];
                                var usersobject_Approver_1 = ppobject_Approver_1.GetAllUserInfo();
                                usersobject_Approver_1.forEach(function(index) {
                                    ppobject_Approver_1.DeleteProcessedUser(usersobject_Approver_1[index]);
                                });
                            }
                        },
                        error: function(xhrstatuserror) {
                            console.log("error: " + xhr.responseText);
                        },
                        complete: function() {
                            //console.log("complete");
                        }
                    });
                }
            });
        }
    </script>
</head>

<body>
</body>

</html>
-----------------------------------------------------------------------------------------------------------------------------------

Monday, May 19, 2014

Customise 'XSL Editor' Search Core Result WebPart in SharePoint 2010

------------------------------------------------------------------------------
Step 1: Deselect Check Box
------------------------------------------------------------------------------
Step 2: Add Custom column below formate with 2 spaceses.

<Columns>  <Column Name="WorkId"/>  <Column Name="Rank"/>  <Column Name="Title"/>  <Column Name="Author"/>  <Column Name="Size"/>  <Column Name="Path"/>  <Column Name="Description"/>  <Column Name="Write"/>  <Column Name="SiteName"/>  <Column Name="CollapsingStatus"/>  <Column Name="HitHighlightedSummary"/>  <Column Name="HitHighlightedProperties"/>  <Column Name="ContentClass"/>  <Column Name="IsDocument"/>  <Column Name="PictureThumbnailURL"/>  <Column Name="PopularSocialTags"/>  <Column Name="PictureWidth"/>  <Column Name="PictureHeight"/>  <Column Name="DatePictureTaken"/>  <Column Name="ServerRedirectedURL"/>  </Columns>
------------------------------------------------------------------------------
Step 2: Click 'XSL Edit' to add below code. remember 'fieldname' always should be in small letters.

<xsl:stylesheet version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal">
  <xsl:output method="html" indent="no"/>
  <xsl:param name="dvt_adhocmode">sort</xsl:param>
  <xsl:decimal-format NaN=""/>

  <xsl:param name="FileName" />
  <xsl:param name="dvt_apos">'</xsl:param>
  <xsl:param name="dvt_fieldsort" />
  <xsl:param name="dvt_filterfield" />
  <xsl:param name="dvt_sortdir">ascending</xsl:param>
  <xsl:param name="dvt_sortfield" />
  <xsl:param name="dvt_sorttype">text</xsl:param>
  <xsl:param name="dvt_filterfields" />
  <xsl:param name="dvt_partguid" />

  <xsl:variable name="dvt_1_automode">0</xsl:variable>

  <xsl:template match="/">
    <xsl:call-template name="dvt_1"/>
    <style type="text/css">
      .ms-alternatingstrong
      {
      background-color:#e3efff;
      }
    </style>
  </xsl:template>
  <xsl:template name="dvt_1">
    <xsl:variable name="dvt_StyleName">Table</xsl:variable>
    <xsl:variable name="Rows" select="/All_Results/Result"/>
    <table border="0" width="93%" cellpadding="4" cellspacing="2" id="ResultsTable" align="right">
      <tr valign="top">
        <xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">
          <th class="ms-vh" width="1%" nowrap="nowrap"></th>
        </xsl:if>
        <th class="ms-vh" nowrap="">

        </th>
        <th class="ms-vh" nowrap="" style="width: 257px" align="left">
          <xsl:call-template name="dvt.headerfield" ddwrt:atomic="1">
            <xsl:with-param name="fieldname">title</xsl:with-param>
            <xsl:with-param name="fieldtitle">TITLE</xsl:with-param>
            <xsl:with-param name="displayname">TITLE</xsl:with-param>
            <xsl:with-param name="sortable">1</xsl:with-param>
            <xsl:with-param name="fieldtype">Text</xsl:with-param>
          </xsl:call-template>
        </th>
        <th class="ms-vh" nowrap="" align="left">
          DESCRIPTION
        </th>
        <th class="ms-vh" nowrap="" align="left">
          <xsl:call-template name="dvt.headerfield" ddwrt:atomic="1">
            <xsl:with-param name="fieldname">write</xsl:with-param>
            <xsl:with-param name="fieldtitle">PUBLISHED</xsl:with-param>
            <xsl:with-param name="displayname">PUBLISHED</xsl:with-param>
            <xsl:with-param name="sortable">1</xsl:with-param>
            <xsl:with-param name="fieldtype">Text</xsl:with-param>
          </xsl:call-template>
        </th>
      </tr>
      <xsl:call-template name="dvt_1.body">
        <xsl:with-param name="Rows" select="$Rows"/>
      </xsl:call-template>
    </table>
  </xsl:template>
  <xsl:template name="dvt_1.body">
    <xsl:param name="Rows"/>
    <xsl:for-each select="$Rows">
      <xsl:sort select="*[name() = $dvt_sortfield] | @*[name() = $dvt_sortfield] | text()[name(ancestor::*[1]) = $dvt_sortfield]" order="{$dvt_sortdir}" data-type="{$dvt_sorttype}" />
      <xsl:sort select="title" order="ascending" />
      <xsl:sort select="write" order="ascending" />
      <xsl:call-template name="dvt_1.rowview"/>

    </xsl:for-each>
  </xsl:template>
  <xsl:template name="dvt_1.rowview">
    <tr>
      <xsl:if test="position() mod 2 = 1">
        <xsl:attribute name="class">ms-alternatingstrong</xsl:attribute>
      </xsl:if>
      <xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">
        <td class="ms-vb" width="1%" nowrap="nowrap">
          <span ddwrt:amkeyfield="" ddwrt:amkeyvalue="string($XPath)" ddwrt:ammode="view"></span>
        </td>
      </xsl:if>
      <td class="ms-vb">
        <img border="0" src="{imageurl/text()}" />
      </td>
      <td class="ms-vb" style="width: 257px">
        <a href="{url}">
          <xsl:value-of select="title" />
        </a>
      </td>
      <td class="ms-vb">

        <xsl:choose>
          <xsl:when test="string-length(hithighlightedsummary/text()) &lt; 80">
            <div>
              <xsl:value-of select="hithighlightedsummary/text()" />
            </div>
          </xsl:when>
          <xsl:otherwise>
            <div>
              <xsl:value-of select="substring(hithighlightedsummary/text(),1,75)" />
            </div>
            <a href="#" onclick="javascript:moreless(this,'{hithighlightedsummary}')">more&gt;&gt;</a>
          </xsl:otherwise>
        </xsl:choose>

        <script type="text/javascript">
          function moreless(abc,fullText)
          {
          if(abc.innerText == "more&gt;&gt;")
          {
          div = abc.parentNode.getElementsByTagName('div');
          div[0].innerText = fullText;
          abc.innerText = "&lt;&lt;less";
          }
          else if(abc.innerText == "&lt;&lt;less")
          {
          div = abc.parentNode.getElementsByTagName('div');
          div[0].innerText = fullText.substring(0,75);
          abc.innerText = "more&gt;&gt;";
          }

          }
        </script>
      </td>


      <td class="ms-vb">
        <xsl:value-of select="write"/>
      </td>
    </tr>
  </xsl:template>
  <xsl:template name="dvt.headerfield">
    <xsl:param name="fieldname" />
    <xsl:param name="fieldtitle" />
    <xsl:param name="displayname" />
    <xsl:param name="sortable">1</xsl:param>
    <xsl:param name="fieldtype">0</xsl:param>
    <xsl:choose>
      <xsl:when test="($dvt_adhocmode = 'sort' or $dvt_fieldsort = '1')and $sortable='1'">
        <xsl:variable name="sortfield">
          <xsl:choose>
            <xsl:when test="substring($fieldname, string-length($fieldname) - 5) = '(text)'">
              <xsl:value-of select="substring($fieldname, 1, string-length($fieldname) - 6)" />
            </xsl:when>
            <xsl:when test="substring($fieldname, 1, 1) = '@'">
              <xsl:value-of select="substring($fieldname, 2)" />
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$fieldname" />
            </xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:variable name="linkdir">
          <xsl:choose>
            <xsl:when test="$dvt_sortfield = $sortfield and $dvt_sortdir = 'ascending'">descending</xsl:when>
            <xsl:otherwise>ascending</xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:variable name="sortText">
          <xsl:choose>
            <xsl:when test="$linkdir='descending'">&apos; + &apos;descending&apos; + &apos;</xsl:when>
            <xsl:otherwise>&apos; + &apos;ascending&apos; + &apos;</xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:variable name="separator" select="' '" />
        <xsl:variable name="connector" select="';'" />
        <table CtxNum="1" cellspacing="0" class="ms-unselectedtitle" onmouseover="OnMouseOverAdHocFilter(this, '{concat($displayname,$separator,$fieldname, $separator,$fieldtype, $connector, 1033, $separator, $dvt_partguid)}')">
          <tr>
            <td width="100%" class="ms-vb" nowrap="">
              <a>
                <xsl:attribute name="href">
                  javascript: <xsl:value-of select="ddwrt:GenFireServerEvent(concat('dvt_sortfield={',$sortfield,'};dvt_sortdir={',$sortText,'}'))" />;
                </xsl:attribute>
                <xsl:attribute name="onclick">
                  javascript: <xsl:value-of select="ddwrt:GenFireServerEvent(concat('dvt_sortfield={',$sortfield,'};dvt_sortdir={',$sortText,'}'))" />;
                </xsl:attribute>
                <xsl:choose>
                  <xsl:when test="$fieldtype = 'Attachments'">
                    <xsl:value-of select="$fieldtitle" disable-output-escaping="yes" />
                  </xsl:when>
                  <xsl:otherwise>
                    <xsl:value-of select="$fieldtitle" />
                  </xsl:otherwise>
                </xsl:choose>
                <xsl:if test="$dvt_sortfield = $sortfield">
                  <xsl:choose>
                    <xsl:when test="$dvt_sortdir = 'ascending'">
                      <img border="0" alt="Ascending" src="{ddwrt:FieldSortImageUrl('Desc')}" />
                    </xsl:when>
                    <xsl:when test="$dvt_sortdir = 'descending'">
                      <img border="0" alt="Descending" src="{ddwrt:FieldSortImageUrl('Asc')}" />
                    </xsl:when>
                  </xsl:choose>
                </xsl:if>
              </a>
              <xsl:if test="contains($dvt_filterfields, concat($fieldname, ';' ))">
                <IMG SRC="/_layouts/images/filter.gif" BORDER="0" ALT="" />
              </xsl:if>
            </td>
            <td>
              <img src="/_layouts/images/blank.gif" width="13" style="visibility: hidden" alt="" />
            </td>
          </tr>
        </table>

      </xsl:when>
      <xsl:otherwise>
        <xsl:choose>
          <xsl:when test="$fieldtype = 'Attachments'">
            <xsl:value-of select="$fieldtitle" disable-output-escaping="yes" />
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$fieldtitle" />
          </xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>
    <xsl:if test="$dvt_filterfield=$fieldname" ddwrt:cf_ignore="1">
      <img alt="Filter" src="{ddwrt:FieldFilterImageUrl('')}" />
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
------------------------------------------------------------------------------

Wednesday, April 9, 2014

Format Number as Thousands Currency and Reverse Formate into Numbers in JavaScript

<p id="p1"></p>   

var number = "1234567890.77";

document.getElementById("p1").innerHTML= formatThousands(number);

function formatThousands(number) {

 var number = '' + number;
        var array_n = number.split('.');

        if (array_n.length > 1) {
            var s = array_n[0];
            var d = array_n[1];

            if (array_n[0].length > 3) {
                var i = s.length;
                var r = '';
                var var_2 = i - 3;

                if (s.length > 3) {
                    while ((i -= 3) > 0) {
                        r = ',' + s.substr(i, 3) + r;
                        break;
                    }

                    while ((i -= 2) > 0) {
                        r = ',' + s.substr(i, 2) + r;
                    }

                    return s.substr(0, i + 2) + r + "." + d;
                }
            }
            else {
                return array_n[0] + "." + d;
            }
        }
        else {
            return array_n[0] + "." + "00";
        }
    }

    function reverse_formatThousands(amount) {

        var array_amount = "";
        var array_num = "";

        var var_decimal = "";
        var var_temp_num = "";

        var amount'' + amount;

        array_amount = amount.split(".");

        if (array_amount.length > 1) {
            var_decimal = array_amount[1];

            array_num = array_amount[0].split(",");

            for (var i = 0; i < array_num.length; i++) {
                var_temp_num += array_num[i];
            }
            return (var_temp_num + "." + var_decimal);
        }
        else {
            array_num = array_amount[0].split(",");

            for (var i = 0; i < array_num.length; i++) {
                var_temp_num += array_num[i];
            }

            return var_temp_num;
        }
    }


Wednesday, March 12, 2014

0x80070057Invalid data has been used to update the list item. The field you are trying to update may be read only. In SharePoint

<nativehr>0x80070057</nativehr><nativestack></nativestack>Invalid data has been used to update the list item. The field you are trying to update may be read only. in SharePoint


Solution:-
Item["Title"] = "Test";

don't use Item["LinkTitle"]. this is readonly field.

Thank You.

Monday, March 10, 2014

Upload Documents to Document Library using file upload control in SharePoint

In Aspx page:-
------------------
<asp:FileUpload runat="server" ID="FileUpload1"></asp:FileUpload>

<asp:ImageButton runat="server" ID="imgbtnUpdateAttachment" OnClick="fileUpload_Click"
ImageUrl="../SiteAssets/Buttons/update_attachement.png"></asp:ImageButton>

In Aspx.cs Page:-
---------------------
protected void fileUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = SPContext.Current.Site;
                    SPWeb web = SPContext.Current.Web;

                    string DocumentLibName = "Test Temp Documents";

                    web.AllowUnsafeUpdates = true;
                    if (FileUpload1.PostedFile != null)
                    {
                        Stream fStream = FileUpload1.PostedFile.InputStream;
                        byte[] content = new byte[fStream.Length];
                        fStream.Read(content, 0, (int)fStream.Length);

                        string Filename = FileUpload1.FileName;
          string destUrl = SPContext.Current.Site.Url + DocumentLibName + "/" + Filename;
                        SPFile spfile = web.Files.Add(destUrl, content, true);
                        spfile.Item["DocID"] = "1234567";
                        spfile.Item.Update();
                        fStream.Flush();
                        fStream.Close();
                        fStream.Close();
                        fStream.Dispose();
                    }
                    else
                    {
                        throw new FileNotFoundException("File Not Found");
                    }
                    web.AllowUnsafeUpdates = false;

                });
            }
        }
-----------------------------------------------------------------
Thank You

Wednesday, February 5, 2014

Authentication in SharePoint 2013

Authentication in SharePoint 2013
                                                                                        
Three types of authentication:-
1.       User authentication
2.       App authentication
3.       Server-to-Server authentication

1. User authentication:-
User authentication occurs when a user attempts to access a SharePoint resource and the user s identity is validated against an authentication provider.
There are three types of User authentications,
1.1   Windows claims-based authentication
1.2   Forms-based authentication
1.3   SAML token-based authentication

1.1 Windows claims-based authentication:-
Windows claims-based authentication uses your existing Windows authentication provider (Active Directory Domain Services [AD DS]) to validate the credentials of connecting clients. Use this authentication to allow AD DS-based accounts access to SharePoint resources. Authentication methods include NTLM, Kerberos, and Basic.
For Windows claims authentication, SharePoint 2013 uses the NTLM or Kerberos protocols to validate user credentials for users that are in forests and domains trusted by the SharePoint 2013 server.

SharePoint 2013 also supports classic-mode Windows authentication, but this is not recommended. Classic-mode Windows authentication does not support app authentication, server-to-server authentication, and Office Web Apps. To configure a web application to use classic-mode authentication, you must use the New-SPWebApplication or Set-SPWebApplication Windows PowerShell cmdlets.

1.1 Windows claims-based authentication How it Works:-
In this example, a user who does not already have a SharePoint security token accesses a secured SharePoint web page.

1)      User requests a web page.
2)      SharePoint requests Windows credentials using NTLM, Kerberos, or basic protocols.
3)      User sends the Windows credentials for the user account.
4)      SharePoint validates the user s Windows credentials with AD DS.
5)      SharePoint obtains the group membership list for the user account from AD DS. SharePoint creates a SharePoint security token, sends an authorization code and the requested web page (from 1).

1.1 Windows claims-based authentication Configuration:-
New web applications created in Central Administration are configured by default to use Windows authentication and the NTLM method:
                    I.            Modify the authentication settings for the web application in Central Administration to include Kerberos.
                  II.            Modify the settings of the web application in the IIS Manager snap-in to enable the Digest and Basic authentication methods.

1.2 Forms-based authentication:-
Forms-based authentication can be used against credentials that are stored in an authentication provider that is available through the ASP.NET interface. These include.
                     i.            AD DS.
                   ii.            A database such as a SQL Server database.
                  iii.            A Lightweight Directory Access Protocol (LDAP) data store

Forms-based authentication validates users based on credentials that users type in a login form (typically a web page). Unauthenticated requests are redirected to a login page, where a user must provide valid credentials and submit the form.Use forms-based authentication with accounts in authentication providers that are available by using the ASP.NET interface.

With forms-based claims authentication, SharePoint 2013 uses the ASP.NET interface to access membership providers and role managers to validate user credentials and obtain user roles.

1.2 Forms-based authentication How It Works:-
In this example, a user who does not already have a SharePoint security token accesses a secured SharePoint web page.

1)      User requests a web page.
2)      SharePoint sends a SharePoint forms-based login page.
3)      User sends the credentials entered in the forms-based login page.
4)      SharePoint validates the credentials with the ASP.NET membership provider.
5)      SharePoint obtains roles from the ASP.NET role provider.
6)      SharePoint creates a SharePoint security token, sends the FedAuth cookie, and web page.

1.2 Forms-based authentication Configuration:-
Configuring forms-based authentication involves the following:

                    I.            Modify the Web.config files for the Central Administration web application, the Security Token Service web site, and the web application to register the ASP.NET membership provider and role manager.
                  II.            Configure the web application with the name of the membership provider and role manager that was added to the Web.config files.
                III.            Optionally, you can also create a custom login page for forms-based authentication.

1.3 SAML token-based authentication:-
SAML token-based authentication in SharePoint 2013 requires coordination with administrators of a claims-based environment, whether it is your own internal environment or a partner environment.
A SAML token-based authentication environment includes an identity provider security token service (IP-STS). The IP-STS issues SAML tokens on behalf of users whose accounts are included in the associated authentication provider. Tokens can include any number of claims about a user, such as a user name and the groups to which the user belongs. An Active Directory Federation Services (AD FS) 2.0 server is an example of an IP-STS.

Use SAML token-based authentication to allow accounts in authentication providers that are available by using a compatible IP-STS access to SharePoint resources.

For SAML token-based claims authentication, SharePoint 2013 supports the SAML 1.1 and WS-Federation Passive Requestor Profile (WS-Federation PRP) protocols for requesting computers to obtain SAML tokens as proof of validation of user credentials and for additional claims.

1.3 SAML token-based authentication How it Works:-
In this example, a user who does not already have a SharePoint security token accesses a secured SharePoint web page.
1)      User requests a web page.
2)      SharePoint sends a redirect and the user loads a login page from the AD FS server.
3)      User sends user credentials and requests a SAML security token.
4)      AD FS validates the user credentials with AD DS (the authentication provider).
5)      AD FS sends a SAML security token.
6)      User sends a new web page request containing the SAML security token.
7)      SharePoint creates a SharePoint security token, sends the FedAuth cookie, and the requested web page.

1.3 SAML token-based authentication Configuration:-
The key elements of SAML token-based authentication are the following:

                                I.            Configure the IP-STS with the set of authentication providers (such as AD DS, databases, and others) corresponding to organization and partner accounts.
                              II.            Configure the IP-STS with the set of relying parties corresponding to the web applications that use SAML token-based authentication and claims mappings.
                            III.            Configure the SharePoint 2013 farm with the token signing certificate of the IP-STS, the corresponding claims mappings as done on the IP-STS, and the name of the IP-STS as a trusted security token issuer.
                            IV.            Configure the web application with the name of the IP-STS as a SAML identity provider.

2. App Authentication:-
App authentication occurs when an external component of an app for SharePoint attempts to access a secured SharePoint resource. App authentication is a combination of:
                    I.            Verification of a remote app for SharePoint's identity (authentication).
                  II.            Validation of the type of access through user and app permissions (authorization).

App Trust Level are Two Type, they are
2.1   Low-Trust Apps
2.2   High-Trust Apps

2.1 Low-trust Apps:-
A low-trust app relies on the Windows Azure Access Control Service (ACS) as the trusted security token issuer for access tokens that are required to obtain secured resources on a SharePoint farm. The app provider or Windows Azure can host low-trust apps. To trust low-trust apps, you must have an Office 365 subscription.

In this example, a user accesses a secured SharePoint web page containing an IFRAME that is rendered by an app hosted in Windows Azure. To render the IFRAME, the app must access a resource on the server running SharePoint 2013 on behalf of the requesting user.

1)      User requests a web page containing the Azure app s IFRAME.
2)      SharePoint obtains a context token from ACS.
3)      SharePoint sends the web page with the app s IFRAME and the context token to the user.
4)      User requests the IFRAME contents with the context token from the app.
5)      App obtains an access token from ACS.
6)      App requests the SharePoint resource using the access token.
7)      After app and user authorization, SharePoint responds with the requested resource.
8)      App sends the IFRAME contents to the user.

2.2 High-trust Apps:-
A high-trust app is an app that an intranet server or a provider's server on the Internet hosts. For high-trust apps, the app acts as the trusted security token issuer for access tokens that are required to obtain secured resources on a SharePoint farm.

In this example, a user accesses a secured SharePoint web page containing an IFRAME that is rendered by a high-trust app. To render the IFRAME, the app must access a resource on the server running SharePoint 2013 on behalf of the requesting user.

1)      User requests a web page containing the high-trust app s IFRAME.
2)      SharePoint sends the web page with the app s IFRAME.
3)      User requests the IFRAME content from the high-trust app server.
4)      App authenticates the user and generates an access token.
5)      App requests the SharePoint resource using the access token.
6)      After app and user authorization, SharePoint responds with the requested resource.
7)      App sends the IFRAME contents to the user.

3. Server-to-Server Authentication:-
Server-to-server authentication enables a new set of functionality and scenarios that utilize cross-server resource sharing and access, including the following:

                    I.            eDiscovery Discover and place holds on content in the SharePoint farm, in Exchange Server 2013, on file shares, and in other SharePoint farms.
                  II.            Exchange task synchronization Allows users to synchronize SharePoint Server 2013 and Project Server tasks with Exchange Server 2013 and have them appear in Outlook 2013.
                III.            Site mailboxes Provides SharePoint Server 2013 users with team email, hosted by Exchange Server 2013, on a SharePoint site.
                IV.            SharePoint 2013 Hybrid Federated search, Business Connectivity Services, and Duet Online between an on-premises SharePoint 2013 farm and SharePoint Online.

Server products that are capable of server-to-server authentication:-
3. Server-to-Server Authentication How It Works:-
Similar to app authentication, SharePoint 2013 allows access to the requested resource when the server making the request is verified as trusted and the type of access is authorized through validation of user and server permissions.The validation of a server's request for resources that is based on a trust relationship established between the Security Token Service (STS) of the server that runs SharePoint 2013 and the security token service (STS) of another server that supports the OAuth server-to-server protocol. Based on this trust relationship, a requesting server can access secured SharePoint resources on behalf of a specified user account, subject to server and user permissions.

3. Server-to-Server Authentication Configuration:-
Server-to-server authentication configuration consists of adding a new trusted security token issuer that corresponds to each server that will send resource requests on behalf of users.

                    I.            For on-premises SharePoint farms, you configure the JSON metadata endpoint of the other SharePoint farm.
                  II.            For your SharePoint Online farm, you configure the JSON metadata endpoint of your Office 365 subscription.
                III.            For servers running Exchange Server 2013 or Lync Server 2013, you configure the JSON metadata endpoint of the other server.

Example — How Server-to-Server Authentication works between on-premises SharePoint farms:-
In this example, Farm B has been configured to trust Farm A by using server-to-server authentication. Farm A has been configured with a result source for search that uses the Remote SharePoint protocol to get search results from the index of Farm B. To obtain search results, Farm A sends a query to Farm B.
1)      User on Farm A executes a query to get search results from the local search index and the search index of Farm B.
2)      Farm A generates an access token, identifying the user and the requested resource (a search index).
3)      Farm A sends the access token to Farm B.
4)      Farm B validates the access token, verifies authorization, and sends the search results.
5)      Farm A sends the complete set of search results from both Farm A and Farm B to the user.

Featured Post

Power Automate Desktop: Find One-to-Many Values Between Two Columns

Power Automate Desktop: Find One-to-Many Values Between Two Columns The Problem You have a table with two columns, A and B . You want to fi...

Popular posts