Thursday, June 12, 2014

Copy/Move/Update/Save the List items from Source List to Destination List using ProcessBatchData in SharePoint

Copy/Move/Update/Save the List items from Source List to Destination List using ProcessBatchData in SharePoint.
In list1, list2 column name should be same like Title, USER_NAME, PLACE. column name are case sensitive.
in .aspx page:-
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="test.Layouts.test.test"
    DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">  
            <td align="center">
                <asp:Button ID="btnClose" Font-Bold="true" runat="server" Text="Move Items from list1 to list2"
                    OnClick="btnMove_Click" />
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Application Page
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
    My Application Page


In .aspx.cs page:-
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using System.Data;
using System.Web;

namespace test.Layouts.test
    public partial class test : LayoutsPageBase
        protected void Page_Load(object sender, EventArgs e)
        protected void btnMove_Click(object sender, EventArgs e)
                SPWeb web = SPContext.Current.Web;
                SPList source_list = web.Lists["list1"];
                SPList destination_list = web.Lists["list2"];

                SPQuery query = new SPQuery();
                query.RowLimit = 2000;
                StringBuilder sbQuery = new StringBuilder();
                sbQuery.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                string command =
                    "<Method>" +
                        "<SetList Scope=\"Request\">{0}</SetList>" +
                        "<SetVar Name=\"ID\">New</SetVar>" +
                        "<SetVar Name=\"Cmd\">Save</SetVar>" +
                        "<SetVar Name=\"urn:schemas-microsoft-com:office:office#Title\">{1}</SetVar>" +
                        "<SetVar Name=\"urn:schemas-microsoft-com:office:office#USER_NAME\">{2}</SetVar>" +
                        "<SetVar Name=\"urn:schemas-microsoft-com:office:office#PLACE\">{3}</SetVar>" +

                string deleteCommand =
                    "<Method>" +
                        "<SetList Scope=\"Request\">{0}</SetList>" +
                        "<SetVar Name=\"ID\">{1}</SetVar>" +
                        "<SetVar Name=\"Cmd\">Delete</SetVar>" +

                //string CopyCommand =
                //   "<Method>" +
                //       "<SetList Scope=\"Request\">{0}</SetList>" +
                //       "<SetVar Name=\"ID\">{1}</SetVar>" +
                //       "<SetVar Name=\"Cmd\">Copy</SetVar>" +
                //   "</Method>";

                SPListItemCollection itmColl;
                    itmColl = source_list.GetItems(query);
                    if (itmColl.Count >= 0)
                    query.ListItemCollectionPosition = itmColl.ListItemCollectionPosition;
                    DataTable dtData = new DataTable();
                    dtData = itmColl.GetDataTable();
                    foreach (DataRow dr in dtData.Rows)
                        sbQuery.AppendFormat(command, destination_list.ID, Convert.ToString(dr["Title"]), Convert.ToString(dr["USER_NAME"]), Convert.ToString(dr["PLACE"]));
                        sbQuery.AppendFormat(deleteCommand, source_list.ID, Convert.ToString(dr["ID"]));
                        //sbQuery.AppendFormat(CopyCommand, source_list.ID, Convert.ToString(dr["ID"]));

                } while (query.ListItemCollectionPosition != null);

            catch (Exception ex)

Monday, June 9, 2014

Tips and Trick for SharePoint

Additions to this Web site have been blocked. Please contact the administrator to resolve this problem.
Troubleshoot issues with Microsoft SharePoint Foundation.

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>
    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

1. first delete this site collection "http://server-123:2014/sites/hrsite"
2. $site = Get-SPSite http://server-123:2014/sites/hrsite
   $siteguid = $
   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

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, w1 => w1.ServerRelativeUrl, w1 => w1.Url);
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);
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">
SharePoint Designer Clear all Cache
%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

Connect Office Web Apps for SharePoint 2013:-
1. New-SPWopiBinding –ServerName <SharePoint_Server_Name> -allowhttp
2. Set-SPWopiZone -Zone "internal-https"
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}
        Write-Host "Folder $TargetFolder Does not exist! Check folder path"
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 = $
    $Title = $user.title
    $department = $user.department
    $Office = $user.Office
    $DisplayName = $LastName + ", " + $FirstName
    $UserName = $FirstName + "." + $LastName + ""
    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 = "" + $site.SiteUrl
    $Title = $Site.SiteName
    $Owner = $Site.Owner
    New-SPSite -Url $url -Name $Title -OwnerAlias $Owner -Template STS#0