Thursday, 29 June 2017

Parse date from string to any date format

Parsing date from string  to cultural format



string timeFrameFromDate=date;

 lstItem["FromDate"] = DateTime.ParseExact(timeFrameFromDate, "dd/M/yyyy", CultureInfo.InvariantCulture);

Date Format Output will be  like this      31/12/2017



And Use below code to convert date in different format

function getFormattedDate(formatedDate) {
    var year = formatedDate.getFullYear();
    var month = (1 + formatedDate.getMonth()).toString();
    month = month.length > 1 ? month : '0' + month;
    var day = formatedDate.getDate().toString();
    day = day.length > 1 ? day : '0' + day;
    return day + '/' + month + '/' + year;

}




Friday, 16 June 2017

Get AD User Using WCF Service and Ajax Call

1. Create WCF Service Application Project

2. Copy below code and paste in IService1 interface class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ActiveDirectoryDetails
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetADUsers/?domain={domain}&userid={userid}&password={password}")]
        List<Users> GetADUsers(string domain, string userid, string password);
    }

    [DataContract]
    public class Users
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string MiddleName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public string FullName { get; set; }
        [DataMember]
        public string LogonName { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public string Department { get; set; }
        [DataMember]
        public string Designation { get; set; }
        [DataMember]
        public string Company { get; set; }
        [DataMember]
        public string GroupName { get; set; }
        [DataMember]
        public string Manager { get; set; }
        [DataMember]
        public string Reporting { get; set; }
        [DataMember]
        public string MobileNumber { get; set; }
        [DataMember]
        public string Status { get; set; }
        [DataMember]
        public string PostalAddresses { get; set; }
        [DataMember]
        public string Country { get; set; }
        [DataMember]
        public string StateProvince { get; set; }
        [DataMember]
        public string City { get; set; }
        [DataMember]
        public string ZIPPostalCode { get; set; }
        [DataMember]
        public string HomeAddress { get; set; }
        [DataMember]
        public string StreetAddress { get; set; }
        [DataMember]
        public string CountryAbbreviation { get; set; }
        [DataMember]
        public string HomePhone { get; set; }
        [DataMember]
        public string OfficeLocation { get; set; }
        [DataMember]
        public string ExtensionName { get; set; }
        [DataMember]
        public string OtherEMailAddress { get; set; }
        [DataMember]
        public string OtherMobileNumber { get; set; }

    }


}


3. Copy below code and paste in Service1 class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.DirectoryServices;
//using Microsoft.Web.Hosting.Administration;
namespace ActiveDirectoryDetails
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {

        public List<Users> GetADUsers(string domain, string userid, string password)
        {
            List<Users> lstADUsers = new List<Users>();
            try
            {
                string domainName = domain;
                DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + domainName, null, null);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";
                searchRoot.Username = userid;
                searchRoot.Password = password;
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");
                search.PropertiesToLoad.Add("department");
                search.PropertiesToLoad.Add("manager");
                search.PropertiesToLoad.Add("userAccountControl");
                search.PropertiesToLoad.Add("company");
                search.PropertiesToLoad.Add("givenName");
                search.PropertiesToLoad.Add("sn");
                search.PropertiesToLoad.Add("c");
                search.PropertiesToLoad.Add("co");
                search.PropertiesToLoad.Add("homePostalAddress");
                search.PropertiesToLoad.Add("l");
                search.PropertiesToLoad.Add("postalCode");
                search.PropertiesToLoad.Add("st");
                search.PropertiesToLoad.Add("streetAddress");
                search.PropertiesToLoad.Add("postalAddress");
                search.PropertiesToLoad.Add("homePhone");
                search.PropertiesToLoad.Add("mobile");
                search.PropertiesToLoad.Add("middleName");
                search.PropertiesToLoad.Add("Title");
                search.PropertiesToLoad.Add("directReports");
                search.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                search.PropertiesToLoad.Add("extensionName");
                search.PropertiesToLoad.Add("otherMailbox");
                search.PropertiesToLoad.Add("otherMobile");
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        Users objSurveyUsers = new Users();
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname"))
                        {
                            objSurveyUsers.LogonName = (String)result.Properties["samaccountname"][0];
                        }
                        if (result.Properties.Contains("mail"))
                        {
                            objSurveyUsers.Email = (String)result.Properties["mail"][0];
                        }
                        if (result.Properties.Contains("displayname"))
                        {
                            objSurveyUsers.FullName = (String)result.Properties["displayname"][0];
                        }
                        if (result.Properties.Contains("department"))
                        {
                            objSurveyUsers.Department = (String)result.Properties["department"][0];
                        }
                        if (result.Properties.Contains("manager"))
                        {
                            objSurveyUsers.Manager = (String)result.Properties["manager"][0];
                        }

                        if (result.Properties.Contains("userAccountControl"))
                        {

                            objSurveyUsers.Status = IsActive(Convert.ToInt32((int)result.Properties["userAccountControl"][0]));
                        }
                        if (result.Properties.Contains("givenName"))
                        {

                            objSurveyUsers.FirstName = (String)result.Properties["givenName"][0];
                        }
                        if (result.Properties.Contains("usergroup"))
                        {

                            objSurveyUsers.GroupName = (String)result.Properties["usergroup"][0];
                        }
                        if (result.Properties.Contains("sn"))
                        {

                            objSurveyUsers.LastName = (String)result.Properties["sn"][0];
                        }
                        if (result.Properties.Contains("c"))
                        {

                            objSurveyUsers.CountryAbbreviation = (String)result.Properties["c"][0];
                        }
                        if (result.Properties.Contains("co"))
                        {

                            objSurveyUsers.Country = (String)result.Properties["co"][0];
                        }
                        if (result.Properties.Contains("homePostalAddress"))
                        {

                            objSurveyUsers.HomeAddress = (String)result.Properties["homePostalAddress"][0];
                        }
                        if (result.Properties.Contains("l"))
                        {

                            objSurveyUsers.City = (String)result.Properties["l"][0];
                        }
                        if (result.Properties.Contains("postalCode"))
                        {

                            objSurveyUsers.ZIPPostalCode = (String)result.Properties["postalCode"][0];
                        }
                        if (result.Properties.Contains("st"))
                        {

                            objSurveyUsers.StateProvince = (String)result.Properties["st"][0];
                        }
                        if (result.Properties.Contains("streetAddress"))
                        {

                            objSurveyUsers.StreetAddress = (String)result.Properties["streetAddress"][0];
                        }
                        if (result.Properties.Contains("postalAddress"))
                        {

                            objSurveyUsers.PostalAddresses = (String)result.Properties["postalAddress"][0];
                        }
                        if (result.Properties.Contains("homePhone"))
                        {

                            objSurveyUsers.HomePhone = (String)result.Properties["homePhone"][0];
                        }
                        if (result.Properties.Contains("mobile"))
                        {

                            objSurveyUsers.MobileNumber = (String)result.Properties["mobile"][0];
                        }
                        if (result.Properties.Contains("middleName"))
                        {

                            objSurveyUsers.MiddleName = (String)result.Properties["middleName"][0];
                        }
                        if (result.Properties.Contains("Title"))
                        {

                            objSurveyUsers.Designation = (String)result.Properties["Title"][0];
                        }
                        if (result.Properties.Contains("directReports"))
                        {

                            objSurveyUsers.Reporting = (String)result.Properties["directReports"][0];
                        }
                        if (result.Properties.Contains("physicalDeliveryOfficeName"))
                        {

                            objSurveyUsers.OfficeLocation = (String)result.Properties["physicalDeliveryOfficeName"][0];
                        }
                        if (result.Properties.Contains("extensionName"))
                        {

                            objSurveyUsers.ExtensionName = (String)result.Properties["extensionName"][0];
                        }
                        if (result.Properties.Contains("otherMailbox"))
                        {

                            objSurveyUsers.OtherEMailAddress = (String)result.Properties["otherMailbox"][0];
                        }
                        if (result.Properties.Contains("otherMobile"))
                        {

                            objSurveyUsers.OtherMobileNumber = (String)result.Properties["otherMobile"][0];
                        }
                        if (result.Properties.Contains("company"))
                        {

                            objSurveyUsers.Company = (String)result.Properties["company"][0];
                        }

                        lstADUsers.Add(objSurveyUsers);

                    }
                }
            }
            catch (Exception ex)
            {

            }
            return lstADUsers;
        }
        public string IsActive(int value)
        {
            string status = string.Empty;
            if (value == 66050)
            {
                status = "DeActive";
            }
            else
            {
                status = "Active";
            }
            return status;
        }
    }
}



4. Copy below web.config code in your web.config



<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
 
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

    <services>

      <service name="ActiveDirectoryDetails.Service1" behaviorConfiguration="ServiceBehaviour">

        <endpoint address ="" binding="webHttpBinding" contract="ActiveDirectoryDetails.IService1" behaviorConfiguration="web">

        </endpoint>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehaviour">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="1" />

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>
  </system.webServer>

</configuration>


5. Create your Client Application and paste below Ajax Call Method



    <script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
      GetUsersDetails();
      function GetUsersDetails() {
          $.ajax({
              url: "http://localhost:80/Service1.svc/GetADUsers/?domain=sfsd&userid=wjrkj&password=4728346",
              data: {
                  format: 'json'
              },
              type: 'GET',
              dataType: 'json',
              success: function (data) {
                  console.log(data.GetADUsersResult);
              }, error: function () {
                  console.log("Error....");
              }
          });
      }
});

</script>
4. Finally below will be result




Thursday, 15 June 2017

Search On ListViewWebPart

Search On ListVIewWebPart Using Javascript

Copy and Paste below given script in CQWP

<script type="text/javascript">
    function RedirectUrl() {
        var tb = document.getElementById("tbSearch").value;
        var cs = document.getElementById("sfield").value;
        var url = "";

        if (tb != "") {
            if (cs == "Column2" || cs == "Column3" || cs == "Column4" || cs == "Column5") {
                url = "FilterField1=" + cs + "&FilterValue1=" + tb;
                window.location.href = "AllItems.aspx?" + url;
            }
            else {
                url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
                window.location.href = "AllItems.aspx?" + url;
            }
        }
        else {
            return false;
        }
    }
    function ClearUrl() {
        window.location.href = "AllItems.aspx";
    }
        </script>Search Field:
<select id="sfield"><option value="FirstName">FirstName</option><option value="FirstName">LastName</option><option value="Company">Department</option><option value="Email">Email</option></select>   Search text:
<input id="tbSearch" type="text"/><input id="btnSearch" onclick="return RedirectUrl();" type="button" value="Search"/><input id="btnClear" onclick="return ClearUrl();" type="button" value="Clear"/>​​​​​




Tuesday, 23 May 2017

AngularJS Crude Operation In Sharepoint

HTML side



<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
     <script src="http://code.angularjs.org/1.4.8/angular-resource.js"></script>
     <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

    <script src="/_layouts/15/angularjs/Apps.js"></script>
    <style>
     .odd {
       background-color: antiquewhite;
       color: #008b8b;
     }
     td th {
       height: 30px;
       min-width: 100px;
     }
     thead {
       background-color: darkgray;
       color: white;
       height: 30px;
     }
   </style>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div  ng-app="myApp" >
        <div ng-controller="myCtrl">
            <br />
            <br />
            <input id="getData" type="button" value="GetData" ng-click="ButtonClick()" />
            <input id="txtSearch" type="text" placeholder="Search by FirstName"  ng-model="searchText.Name"/>
            <br />
         
   <table border="1">
       <tr>
         <td>
                <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
         </td> <td>Id</td><td>Salutation</td> <td>FirstName</td> <td>LastName</td>
       </tr>
         <tr ng-repeat="x in showData | filter: searchText">
             <td>
                   <input type="checkbox" ng-model="x.Selected" />
             </td>
           <td>{{x.ID | uppercase }}</td>
           <td>{{x.Title | uppercase }}</td>
           <td>{{x.Name | lowercase}}</td>
           <td>{{x.Class | lowercase }}</td>
           <td><input  type="button" value="Edit" ng-click="GetItem(x.ID)" style="background-color:red;color:white"  />  </td>
           <td><input  type="button" value="Delete" ng-click="Delete(x.ID)" style="background-color:red;color:white"  />  </td>
       </tr>
   </table>
            <br />
      <table border="1">
          <tr>
             <td>Id:</td><td> <input id="txtUserId" type="text" ng-model="student.Id" /></td>
          </tr>
           <tr>
              <td> Salutation: </td><td>
     <select name="singleSelect" ng-model="student.salutation">
      <option value="Mr.">Mr.</option>
      <option value="Mrs.">Mrs.</option>
    </select>
                                    </td>
          </tr>
          <tr>
              <td> FirstName: </td><td><input id="txtName" type="text" ng-model="student.Name" /></td>
          </tr>
          <tr>
              <td>LastName:</td><td> <input id="txtIsUsed" type="text" ng-model="student.Class" /></td>
          </tr>
      </table>    
            <br />
            <input id="btnInsert" type="button" value="Insert" ng-click="InsertData()" />
            <input id="btnUpdate" type="button" value="Update" ng-click="UpdateData()" />
            <input id="btnDelete" type="button" value="Delete" ng-click="Delete('')" style="background-color:red;color:white" />
            <input id="btnDeleteAll" type="button" value="DeleteAll" ng-click="removeAll()" style="background-color:red;color:white" />            
        </div>
    </div>

Add Code in JS file Apps.js



SP.SOD.executeFunc('sp.js', 'SP.ClientContext', readyFucntion);

function readyFucntion()
{
}

var app = angular.module("myApp", []);
app.controller('myCtrl', function ($scope, $http)
{
    $scope.ButtonClick = function ()
    {
   
       $scope.CommonMethod();
   
    }
    $scope.CommonMethod = function ()
    {
        $http({
            url: "/_api/web/lists/GetByTitle('AngularJS')/items",
            method: "GET",
            headers: { "Accept": "application/json;odata=verbose" }
        }).success(function (data) {


            $scope.showData = data.d.results;
       
         
        }).error(function (sender, args) {


            console.log(args.get_message());

            });
 
    }
    $scope.ClearAll=function()
    {

        $scope.student.Id = "";
        $scope.student.Name = "";
        $scope.student.Class = "";
    }
    $scope.GetItem = function (itemId) {

        $http({
            url:"/_api/web/lists/getbytitle('AngularJS')/items(" + itemId + ")",
            method: "GET",
            headers: { "Accept": "application/json;odata=verbose" }
        }).success(function (data)
        {
            $scope.student.Id=data.d.ID;
            $scope.student.Name=data.d.Name;
            $scope.student.Class=data.d.Class;
            $scope.student.salutation = data.d.Title;

        }).error(function (sender, args) {


            console.log(args.get_message());

        });

    }
    $scope.checkAll = function ()
    {
        if ($scope.selectedAll) {
            $scope.selectedAll = true;
        } else {
            $scope.selectedAll = false;
        }
        angular.forEach($scope.showData, function (item) {
            item.Selected = $scope.selectedAll;
        });
    }
    $scope.removeAll = function ()
    {
        alert("Feature is comming soon !OOPS");
    }
    $scope.student = { Id: "",Name: "", Class: "" };
    $scope.InsertData = function ()
    {
        var stu = $scope.student;
        var clientContext = new SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var list = web.get_lists().getByTitle('AngularJS');
        var listItemInfo = new SP.ListItemCreationInformation();
        var listItem = list.addItem(listItemInfo);
        listItem.set_item('Title', stu.salutation);
        listItem.set_item('Name', stu.Name);
        listItem.set_item('Class', stu.Class);
        listItem.update();
        clientContext.executeQueryAsync($scope.onQuerySucceededInsert, Function.createDelegate(this, onQueryFailed));
    }
    $scope.UpdateData = function () {

        var stu = $scope.student;
        var clientContext = new SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var list = web.get_lists().getByTitle('AngularJS');
        var listItem = list.getItemById(stu.Id);
        listItem.set_item('Title', 'Mr');
        listItem.set_item('Name', stu.Name);
        listItem.set_item('Class', stu.Class);
        listItem.update();
        clientContext.executeQueryAsync($scope.onQuerySucceededUpdated, Function.createDelegate(this, onQueryFailed));

    }
    $scope.Delete = function (itemId)
    {
        var stu = $scope.student;
     
        if (itemId.length == 0) {
            itemId = stu.Id;
        }
        var clientContext = new SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var list = web.get_lists().getByTitle('AngularJS');
        var listItem = list.getItemById(itemId);
        listItem.deleteObject();
        clientContext.executeQueryAsync($scope.onQuerySucceededDeleted, Function.createDelegate(this, onQueryFailed));
    }
    $scope.DeleteAll = function (itemId) {
        var stu = $scope.student;

        if (itemId.length == 0) {
            itemId = stu.Id;
        }
        var clientContext = new SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var list = web.get_lists().getByTitle('AngularJS');
        var listItem = list.getItemById(itemId);
        listItem.deleteObject();
        clientContext.executeQueryAsync($scope.onQuerySucceededDeleted, Function.createDelegate(this, onQueryFailed));
    }
    $scope.onQuerySucceededInsert = function () {
        alert('Item Added Successfully');
        $scope.CommonMethod();
        $scope.ClearAll();

    }
    $scope.onQuerySucceededUpdated = function () {
        alert('Item Updated Successfully');
        $scope.CommonMethod();
        $scope.ClearAll();
    }
    $scope.onQuerySucceededDeleted = function () {
        alert('Item Deleted Successfully');
        $scope.CommonMethod();
        $scope.ClearAll();
    }
});
onQueryFailed = function (sender, args)
{ alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); }





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>