Monday, 24 April 2017


Add Solution
Add-SPSolution <literal path of wsp file>                                                                        
Deploy Solution
Install-SPSolution -Identity <solution_file (WSP Name)> -GACDeployment
Uninstall Solution
Uninstall-SPSolution –Identity "solution_file (WSP Name)".wsp –WebApplication "Site URL"
Update/Upgrade Solution
The Update-SPSolution cmdlet upgrades a deployed SharePoint solution in the farm. Use this cmdlet only if a new solution contains the same set of files and features as the deployed solution. If files and features are different, the solution must be retracted and redeployed by using the Uninstall-SPSolution and Install-SPSolution cmdlets, respectively
Update-SPSolution -Identity "solution_file (WSP Name)" -LiteralPath <literal path of wsp file> -GACDeployment
Install Feature
Install-SPFeature -path <literal path to the 15\Template\Features directory.> -CompatibilityLevel 15
Uninstall Feature
Uninstall-SPFeature -Identity <Feature Name>
Enable Feature
Enable-SPFeature -identity <Feature Guid> -URL "Site URL"
Get the list of features from site sorted by ID
get-spfeature -site "Site URL" | Sort Id
Get the list of features from site sorted by Name
get-spfeature -site "Site URL" | Sort Displayname
Get the list of features from site sorted by ID
get-spfeature -site "Site URL" | Sort Id
Get the list of features from site sorted by Name
get-spfeature -site "Site URL" | Sort Displayname
Take Site Backup
backup-spsite -identity <Site URL> -path "literal path to save backup file"
Restore Site Backup
Restore-SPSite -Identity <Site URL> -Path <literal path to save Backup file> [-DatabaseServer <Database server name>] [-DatabaseName <Content database name>] [-HostHeader <Host header>] [-Force] [-GradualDelete] [-Verbose]
Synchronise the AD User Data with User Profiles in SP Site
Get-SPUser –Web http://SharePointServer | Set-SPUser –SyncFromAD
Backing Up an Entire Web Application
backup-spfarm –BackupMethod Full –Directory C:\Backup\ -Item http://server
Backing Up the Farm Configuration
backup-spfarm –BackupMethod Full –Directory C:\Backup\ -ConfigurationOnly
Create a Web
New-SPWeb –URL "Web URL" -Verbose
Export a Web
export-spweb -identity "Web URL" -path "<literal path>\<backup file name>.cmp"
Import a Web
Import-SPWeb -Identity "Web URL" -Path "<literal path>\<backup file name>.cmp" -IncludeUserSecurity -UpdateVersions Overwrite
Export a List
export-spweb -identity "Web URL" -path "<literal path>\<backup file name>.cmp" -itemurl "/<listname>"
Import a List
Import-SPWeb -Identity "Web URL" -Path "<literal path>\<backup file name>.cmp" -IncludeUserSecurity -UpdateVersions Overwrite
Find List Name from Id
Get-SPSite "Site URL" | Get-SPWeb  -Limit ALL | %{$_.Lists} | ?{$_.ID –eq "<List ID>"} | ft Title, ParentWebURL, RootFolder
Assign User as Site Collection Administrator
Get-SPSite -Identity "Site URL" | %{Set-SPSite $_ -OwnerAlias "username" -SecondaryOwnerAlias "username"}
Get list of deployed solutions
$SPfarm = [Microsoft.SharePoint.Administration.SPFarm]::get_Local()
$SPfarm.get_Solutions()
Download the WSP that you have deployed in a SharePoint farm
$frm = Get-SPFarm
$file = $frm.Solutions.Item("Name of Solution i.e.WSP file name").SolutionFile
$file.SaveAs("literal path to save wsp file")
Get User Info
Get-SPUser -Web "Site URL" |  Where { $_.UserLogin -LIKE "*|domain\username" } |  Select ID, UserLogin, DisplayName
Get SharePoint Groups from Site Collection
Get-SPSite "Site URL" |  Select -ExpandProperty RootWeb | Select -ExpandProperty Groups |  Select {$_.ParentWeb.Url}, Name
Get All Users from SharePoint Group
Get-SPSite "Site URL" |  Select -ExpandProperty RootWeb |  Select -ExpandProperty Groups |  Where {$_.Name -EQ "<Group Name>"} |  Select -ExpandProperty Users |  Select Name, Email
Get SharePoint Groups of given user$user = Get-SPUser -Web "Site URL" |  Where {$_.LoginName -LIKE "*|domain\username"}
Get All Site Owners and All Site Collection Administrators
Get All Site Owners:
$web = Get-SPWeb "Site URL"
$web.AssociatedOwnerGroup.Users
Get  All Site Collection Administrators:
Get-SPSite -Limit All | Select Url, Owner, SecondaryContact

Wednesday, 19 April 2017

culture info client side by server code

function culturalFucntion() {
        var lcid = "<%=System.Threading.Thread.CurrentThread.CurrentUICulture.LCID %>";
     

        if (lcid == "1033") {
          //Language Local
        }
        else
        {
         //Default Language  
        }

}

Monday, 20 February 2017

Calling AngularJs Method on button click

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<sctirp>
var app = angular.module("myApp", []);
app.controller('myCtrl', function ($scope, $http)
{
    $scope.ButtonClick = function ()
    {
        $scope.CommonMethod();
    }
    $scope.CommonMethod = function () {
        var webAbsoluteURL = _spPageContextInfo.webAbsoluteUrl;
        var methodURL = webAbsoluteURL + "/_layouts/15/MainDashBoad/WebMethod.aspx/BindTasks";
        var param = {};
        param.localCulturalId = "1033";
        param.taskBox = "Inbox";
        param.days = "All";
        param.WebURL = webAbsoluteURL;
        var mYData = $http({
            method: "POST",
            url: methodURL,
            dataType: 'json',
            data: param,
            headers: {
                "Content-Type": "application/json"
            }
        });
        mYData.success(function (data, status) {
            $scope.showData = JSON.parse(data.d);//data.d;
            console.log(JSON.parse(data.d));
        });
        mYData.error(function (data, status) {
            $scope.status = status;
            console.log(status);
        });
    }
});

</script>

   <div  ng-app="myApp" >
        <div ng-controller="myCtrl">
             <input id="getData" type="button" value="GetData" ng-click="ButtonClick()" />
   <table border="1">
       <tr ng-repeat="x in showData">
           <td>{{x.ProcessName}}</td>
           <td>{{x.ProjectName}}</td>
       </tr>
   </table>
         
        </div>
     
    </div>

AngularJS Calling webservices or Webmethod

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div  ng-app="myApp" >
        <div ng-controller="myCtrl">
   <table>
       <tr ng-repeat="x in showData">
           <td>{{x.ProcessName}}</td>
           <td>{{x.ProjectName}}</td>
       </tr>
   </table>

        </div>
    </div>


<script>
var app = angular.module("myApp", []);
app.controller('myCtrl', function ($scope, $http)
{
    var webAbsoluteURL = _spPageContextInfo.webAbsoluteUrl;
    var methodURL = webAbsoluteURL + "/_layouts/15/MainDashBoad/WebMethod.aspx/BindTasks";
    var param = {};
    param.localCulturalId ="1033";
    param.taskBox = "Inbox";
    param.days = "All";
    param.WebURL = webAbsoluteURL;
    $http({
        method: "POST",
        url: methodURL,
        dataType: 'json',
        data:param,
        headers: {
            "Content-Type": "application/json"
        }
    }).success(function (data, status)
    {
        $scope.showData = JSON.parse(data.d);//data.d;
     //   console.log(JSON.parse(data.d));
    })
    .error(function (data, status)
    {
        $scope.status = status;
        console.log(status);
    });
});
</script>

Monday, 16 January 2017

Bar Code in Sharepoint

Bar Code Feature :- We have two option to enable Bar Code Feature in Document library 

1. Out Of the Box Feature 
2. Custom Programmatically

1. Use the Information Management Policy Feature to enable bar code on documents by Out Of the Box Feature

 Go to Document Library >>Library Settings>>Click on Information Management Policy >>
there are many option >> Select BarCode Checkbox >> Click Ok >> ModifiView >> Add Two Bar Codes Columns in View >>Click OK

Now Add documents in documents library Bar Code will  come automatically.


2. Using Programmatically

Enable the Feature On Document Library and use the below code for custom Bar Codes






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Drawing;
using Microsoft.Office.RecordsManagement.PolicyFeatures;

namespace SetBarCodeValue
{
    class Program
    {
        static void Main(string[] args)
        {
            //Define the parameter values: Site collection URL
            string siteURL = "http://example/sites/siteCOllectionName";

            using(SPSite site=new SPSite(siteURL))
            {
                using (SPWeb web = site.RootWeb)
                  {
                      //Get a document library
                      SPList list = web.Lists["Design Documents"];
                      //Get an Item
                      SPListItem item = list.Items[0];

                      //Set Bar code value
                      Image img;
                      string barCodeValue = "700";
                      Barcode.ProvisionBarcodeWithValue(item, true, ref barCodeValue, out img);
                      Barcode.SetBarcodePreview(item);
                      item.Update();                    

                     //Print a message
                     Console.WriteLine("Bar code has been Updated!");
                   }
            }

            //Pause
            Console.ReadLine();
        }
    }
}

Thursday, 25 August 2016

Progress/Loading with Simple HTML

<HTML>
 <HEAD>
  <TITLE>Popup div with disabled background</TITLE>
  <style>
   .ontop {
    z-index: 999;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: none;
    position: absolute;  
    background-color: #cccccc;
    color: #aaaaaa;
    opacity: .4;
    filter: alpha(opacity = 50);
   }
   #popup {
 
    position: absolute;
    color: #000000;
 
    /* To align popup window at the center of screen*/
    top: 50%;
    left: 50%;
 
 
   }
  </style>
  <script type="text/javascript">
   function pop(div) {
    document.getElementById(div).style.display = 'block';
   }
//call this method when this have to close
   function hide(div) {
    document.getElementById(div).style.display = 'none';
   }
  window.setTimeout("hide('popDiv')",10000);
  </script>
 </HEAD>
 <BODY>
  <div id="popDiv" class="ontop">
  <div id='popup'> <img id="img-spinner" src="https://raw.githubusercontent.com/niklausgerber/PreLoadMe/master/img/status.gif" alt="Loading"/> </div>
     
  </div>
   <a href="#" onClick="pop('popDiv')">open</a>
 </BODY>
</HTML>

Sunday, 31 July 2016

Exception calling "ChangeDatabaseInstance" with "1" argument(s)

PS C:\Users\admin> $db.ChangeDatabaseInstance("DBNAME")
Exception calling "ChangeDatabaseInstance" with "1" argument(s): "An update
conflict has occurred, and you must re-try this action. The object SPServer
Name=SERVERNAME was updated by admin, in the powershell (2572)
process, on machine SERVERNAME.  View the tracing log for more information
about the conflict."
At line:1 char:1



Solution: Clear the Cache

Run the below script

Add-PSSnapin -Name Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

Stop-Service SPTimerV4
$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
foreach ($folder in $folders)
    {
    $items = Get-ChildItem $folder.FullName -Recurse
    foreach ($item in $items)
        {
            if ($item.Name.ToLower() -eq "cache.ini")
                {
                    $cachefolder = $folder.FullName
                }
               
        }
    }
$cachefolderitems = Get-ChildItem $cachefolder -Recurse
    foreach ($cachefolderitem in $cachefolderitems)
        {
            if ($cachefolderitem -like "*.xml")
                {
                   $cachefolderitem.Delete()
                }
       
        }
       
$a = Get-Content  $cachefolder\cache.ini
$a  = 1
Set-Content $a -Path $cachefolder\cache.ini


Sunday, 24 July 2016

Could not load file or assembly '$SharePoint.Project.AssemblyFullName$' or one of its dependencies

Error=Could not load file or assembly '$SharePoint.Project.AssemblyFullName$' or one of its dependencies. The system cannot find the file specified.



Solution:--


The fix is simple, do the following:

1.  Open your project file .csproj  Edit the .csproj file in NotePad
2.  Find the PropertyGroup nodes.
3.  Add a new PropertyGroup node.
<PropertyGroup>
<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
</PropertyGroup>
4.  Re-Open your project file

HTTPHandler in Sharepoint

1.Create empty project
2.Add HTTPHandler class from Teamplate if not exist then create manually
3.Open .asxh file paste the below code as per you project Name and Class name

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ WebHandler Language="C#" CodeBehind="FileUploader.ashx.cs" Class="SharePointProject1Test.Layouts.SharePointProject1Test.FileUploader" %>

and .ashx.cs code like below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Microsoft.SharePoint;
namespace SharePointProject1Test.Layouts.SharePointProject1Test
{
    /// <summary>
    /// Summary description for FileUploader
    /// </summary>
    ///
 
    public class FileUploader : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
         
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                    AddFile(file.InputStream,file.FileName);
                 
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("File Uploaded Successfully!");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        public static void AddFile(Stream inputStream,string fileName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate() {

            using (SPSite site = new SPSite("http://siteName"))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    byte[] bytes = StreamToByteArray(inputStream);
                    SPFolder myLibrary = web.Folders["Documents_test"];
                    SPFile spfile = myLibrary.Files.Add(fileName, bytes, true);
                    myLibrary.Update();
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;

            }
            });
        }
        public static byte[] StreamToByteArray(Stream inputStream)
        {
            byte[] bytes = new byte[16384];
            using (MemoryStream memoryStream = new MemoryStream())
            {
                int count;
                while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
                {
                    memoryStream.Write(bytes, 0, count);
                }
                return memoryStream.ToArray();
            }
        }
    }
}



4.In the Solution Explorer, click the .ashx file and in the Properties pane, set the Build Action to Content.
5. In the Solution Explorer, click the .ashx.cs file and in the Properties pane, set the Build Action to Compile.
6. Now we need to Save and Close the solution.
7. Edit the .csproj file and add the following text to a PropertyGroup,

<PropertyGroup>
<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
</PropertyGroup>

8. and reload your project in Visual Studio.
9. test the HTTPHandler open browser and paste url like below
 http://SiteName/_Layouts/15/SharePointProject1Test/FileUploader.ashx
9. now HTTPHandler will catch the event and give a message
10. To call HTTPHandler in JQuery/JavaScript paste the code in your Visua webpart / applicationpage / in Content Editor Webpart like below

<script src="/_layouts/15/SharePointProject1Test/jquery-1.4.1.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnUpload").click(function () {

            uploadfile();


        });
    });

    function uploadfile() {
        var bannerImage = $("#fupload").val();

        if (bannerImage) {
            var file = document.getElementById('fupload').files[0];
            var formData = new FormData();
            formData.append(file.name, file);
            var xhr = new XMLHttpRequest();
            var url = "/_Layouts/15/SharePointProject1Test/FileUploader.ashx";
            xhr.open('POST', url, true);
            xhr.onload = function (e) {
                var response = $.parseJSON(e.target.response);
alert(response);
           
            };

            xhr.send(formData);  // multipart/form-data

        }
    }
</script>

 <h3>Upload file Using HTTPHandler in SharePoint</h3>
    <table>
        <tr>  
        <td>
            <input id="fupload" type="file"/><br />
            </td>
 
        </tr>
        <tr>
 
        <td><input id="btnUpload"  value="Upload Selected File" type="button" /></td>
        </tr>
    </table>


Start A workflow programtically in sharepoint

private void StartWorkflowInstance()
        {
           
       
            try
            {

                //SPWorkflowManager objWorkflowManager = listItem.Web.Site.WorkflowManager;
                SPWorkflowManager objWorkflowManager = SPContext.Current.Web.Site.WorkflowManager;
                SPList _list = SPContext.Current.Web.Lists["listname"];
                SPListItem _listItem = _list.GetItemById(listItem.ID);

                if (objWorkflowManager.GetItemWorkflows(_listItem).Count == 0)
                {
                    SPWorkflowAssociationCollection objWorkflowAssociationCollection = _listItem.ParentList.WorkflowAssociations;

                    foreach (SPWorkflowAssociation objWorkflowAssociation in objWorkflowAssociationCollection)
                    {
                        if (objWorkflowAssociation.Name == rbClassificationOfOutgoingDocument.SelectedItem.Text  + " "+ ProcessModelOneConstants.FullAdHocWrokflowName)
                        {
                            SPWorkflow activeWorkflow = objWorkflowManager.StartWorkflow(_listItem, objWorkflowAssociation, objWorkflowAssociation.AssociationData, true);
                            SPUser initiator = activeWorkflow.AuthorUser;
                            string initName = initiator.Name;
                        }
                    }
                }
            }
            catch (Exception exception)
            {

            }
        }