Wednesday, 2 August 2017

Create Dynamic HTML Table with edit functionality using jquery

1.


 <table class="table table-bordered matrixTable" id="uniqueTableMatrix">
                                                                            <thead class="matrixTableHeader">
                                                                                <tr>
                                                                                    <td rowspan='2'>Content Area</td>
                                                                                    <td rowspan='2'>No of Item</td>
                                                                                    <td rowspan='2'>Sub Area</td>
                                                                                    <td rowspan='2'>No of Item</td>
                                                                                    <td colspan='3'>Difficulty Level 1</td>
                                                                                    <td colspan='3'>Difficulty Level 2</td>
                                                                                    <td colspan='3'>Difficulty Level 3</td>
                                                                                    <td rowspan='2'>Action</td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td>C 1</td>
                                                                                    <td>C 2</td>
                                                                                    <td>C 3</td>
                                                                                    <td>C 1</td>
                                                                                    <td>C 2</td>
                                                                                    <td>C 3</td>
                                                                                    <td>C 1</td>
                                                                                    <td>C 2</td>
                                                                                    <td>C 3</td>
                                                                                </tr>
                                                                            </thead>
                                                                            <tbody id="tblBodyMatrix"></tbody>

                                                                            <tfoot class="matrixTableFooter" id="questionsMatrixTableFooter">
                                                                                <tr class="totalColumn">
                                                                                    <td class="totalCol">Total:</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol"></td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol">0</td>
                                                                                    <td class="totalCol"></td>
                                                                                </tr>
                                                                            </tfoot>
                                                                        </table>







2.


$(document).ready(function () {
  uniqeQuestions.AddMore();
    uniqeQuestions.CellChangeTotal();
    uniqeQuestions.CellMaxLengthValodation();
});



3.

var uniqeQuestions ={
AddMore:function () {
    uniqeQuestions.RemoveMatrixRow();
        $('#btnAddmoreMatrix').click(function () {
            if ($("#ddlContentArea").prop('selectedIndex') != 0) {
                var contentareaID = $('#ddlContentArea').val();
                var rowIndex = uniqeQuestions.FindRowContent(contentareaID);
                var contentItem = $('#txtAreaItem').val();
                if (uniqeQuestions.ContentAreaitemValueValidation(rowIndex, contentItem)) {
                    contentItem = $('#txtAreaItem').val();
                    if (uniqeQuestions.ValidateMatrixTotalRequiedItems()) {
                        if (uniqeQuestions.ValidateDuplicateContentAreaSubContentArea()) {
                            var contentarea = $("#ddlContentArea option:selected").text();


                            var subArea = $("#ddlSubArea option:selected").text();
                            var subAreaID = $('#ddlSubArea').val();
                            if (rowIndex.length >= 1 || rowIndex.length == null)//Content area exist in matrix
                            {

                                var trRow = "<tr class='single'><td class='rowDataSd'><label class='contentAreaID' style='display:none;'>" + contentareaID + "</label><label class='contentAreaText' style='display:none;'>" + contentarea + "</label></td><td class='rowDataSd'>" + contentItem + "</td><td class='rowDataSd'><label class='subAreaID' style='display:none;'>" + subAreaID + "</label>" + subArea + "</td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c3'  /></td><td><a href='#' class='remove_MatrixRow'>Remove</a></td></tr>";
                                $('#uniqueTableMatrix > tbody > tr').eq(rowIndex).after(trRow);
                            }
                            else //else if content area does not exist in matrix
                            {
                                var trRow = "<tr class='single'><td class='rowDataSd'><label class='contentAreaID' style='display:none;'>" + contentareaID + "</label><label class='contentAreaText'>" + contentarea + "</label></td><td class='rowDataSd'>" + contentItem + "</td><td class='rowDataSd'><label class='subAreaID' style='display:none;'>" + subAreaID + "</label>" + subArea + "</td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d1c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d2c3'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c1'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c2'  /></td><td class='rowDataSd'><input  type='number'  min='1' max='30'  class='commontextBox matrixQuestionNo cellValidation d3c3'  /></td><td><a href='#' class='remove_MatrixRow'>Remove</a></td></tr>";
                                $('#tblBodyMatrix').append(trRow);
                            }
                            uniqeQuestions.RemoveMatrixRow();
                            uniqeQuestions.CellChangeTotal();
                            uniqeQuestions.CellMaxLengthValodation();
                            uniqeQuestions.TotalRowFooter();
                         
                        }
                    }
                }
            }
            else {
                alert('Please select content area !');
            }

        });
    },
ContentAreaitemValueValidation: function (rowIndex, contentItem)
{
var flag = true;
if (rowIndex.length >= 1 || rowIndex.length == null)
{
    $('#txtAreaItem').val('');
}
else
{
    if(contentItem==null || contentItem=="")
    {
        alert('Please enter content area item value !');
        flag = false;
    }
}
return flag;
},
RemoveMatrixRow:function()
{

    $(".remove_MatrixRow").unbind().click(function ()
    {
        if (!uniqeQuestions.ShiftRowDataNextRow($(this).closest(".single")))
        {
            $(this).closest(".single").remove();
        }
        else {
            $(this).closest(".single").remove();
        }
        uniqeQuestions.ResetAllTableData();
        uniqeQuestions.TotalRowFooter();
    });

},
ShiftRowDataNextRow:function (singleRow)
{
    var cellContentAreaCell = singleRow.find('.contentAreaText');
    var cellContentAreaId = singleRow.find('.contentAreaID').text();
    var currentCellValue = singleRow.find('td')[1].innerText;
    var flag = false;
    if (!$(cellContentAreaCell).is(':hidden'))
    {    
        var nextRow = $(singleRow).next('tr.single');
        var nextContentAreaId = nextRow.find('.contentAreaID').text();
        if (nextContentAreaId == cellContentAreaId)
        {
            $(singleRow).next('tr.single').find('.contentAreaText').show();//show the content area
            var s = $(singleRow).next('tr.single').find('td'); //Shuffle  the value of Content AreaItem
            s[1].innerText = currentCellValue;
        }
        flag = true;
    }
    return flag;
},
FindRowContent:function (conterntAreaId)
{
    var rowIndex = "";
    $("#tblBodyMatrix tr").each(function ()
    {
        if (conterntAreaId ==$(this).find('.contentAreaID').html())
        {
            rowIndex = $(this).index();
        }
    });
    return rowIndex;
},
CellMaxLengthValodation:function ()
{
    $(document).on('input', '.cellValidation', function ()
    {
        var allowedDigits = 2;
        var length = $(this).val().length;
        var max = parseInt($(this).attr("max"));
        if ($(this).val() == "") {
            $(this).val("");
        }
        if ($(this).val().indexOf('.') != -1) {
            allowedDigits = 3;
        }
        if (length > allowedDigits) {
            $(this).val($(this).val().substring(1));
        }
        if ($(this).val() > max && max > 0)
        {
            $(this).val($(this).val().substring(1));
        }


    });
},
CellChangeTotal:function ()
{
    $(".matrixQuestionNo").unbind().change(function ()
    {

        var $row = jQuery(this).closest('tr');
        var $columns = $row.find('td');
        ////To Check the limit of SubArea Item and total of difficulty &complexity ///////
        var subAreaItemLimit = 0;
        var sumSubAreaItem = 0;
        var contentAreaID = "";
        var subContentAreaId = "";
        jQuery.each($columns, function (i, item)
        {
            if (i == 0)
            {
                contentAreaID = $(item).find('.contentAreaID').text();
            }
            if (i == 2)
            {
                subContentAreaId = $(item).find('.subAreaID').text();
            }
            if ($(item).find('input').length != 0)
            {
                if (i == 3)
                {
                    var itemValue = $(item).find('input').val();
                    if (itemValue == "" || itemValue == null)
                    {
                        itemValue = 0;
                    }
                    subAreaItemLimit = parseInt(itemValue);
                     
                }
                else
                {
                    var itemValue = $(item).find('input').val();
                    if (itemValue == "" || itemValue == null)
                    {
                        itemValue = 0;
                    }
                    sumSubAreaItem = parseInt(sumSubAreaItem) + parseInt(itemValue);
                }
            }
        });
        if (sumSubAreaItem > subAreaItemLimit)
        {
            if ($(this).parent('td').index() == 3)
            {
                var tableRow = $(this).parent('td').parent('tr');
                uniqeQuestions.OnSubAreaLimitChange(tableRow);
                uniqeQuestions.ResetAllTableData();
            }
            else
            {
                alert('Please check sub area item limit :' + subAreaItemLimit);
                $(this).val('');
                $(this).focus();
            }
        }
        if (sumSubAreaItem <= subAreaItemLimit)
        {
            uniqeQuestions.ValidateSubAreaItemsTotal();
            uniqeQuestions.ResetAllTableData();
        }
        uniqeQuestions.TotalRowFooter();
    });
},
FinalValidation:function ()
{
    var contentItemsTotal = 0;
    var contentSubAreaItemsTotal = 0;
    var matrixItemsTotal = 0;
    var flag = true;
    $("#uniqueTableMatrix td.totalCol").each(function (i)
    {
        if (i ==1)
        {
            if ($(this).html() != "" )
            {
                contentItemsTotal = parseInt($(this).html());
            }
        }
        if (i == 3)
        {
            if ($(this).html() != "") {
                contentSubAreaItemsTotal = parseInt($(this).html());
            }
        }
        if (i == 13)
        {
            if ($(this).html() != "") {
                matrixItemsTotal = parseInt($(this).html());
            }
        }

    });
    if(contentSubAreaItemsTotal<contentItemsTotal)
    {
        alert('Sub area item total is less than the content area item total !');
        flag = false;
    }
    else if(matrixItemsTotal<contentSubAreaItemsTotal)
    {
        alert('Your selected items is less than required items !');
        flag = false;
    }
    else if (matrixItemsTotal == 0)
    {
        alert('There is no item added in matrix table !');
        flag = false;
    }
    return flag;
},
OnSubAreaLimitChange:function (tableRow)
{
    $(tableRow).each(function ()
    {
        $('td', this).each(function ()
        {
            if ($(this).index() != 3)
            {
                $(this).find('input').val('');
            }
        });
    });
},
ResetAllTableData:function ()
{
    unique_formSetsQuations = [];
    var contentAreaId = "";
    var subContentAreaId = "";
    $("#tblBodyMatrix tr td").each(function ()
    {
        if ($(this).index() == 0)
        {
            contentAreaId = $(this).find('.contentAreaID').text();
        }
        if ($(this).index() == 2)
        {
            subContentAreaId = $(this).find('.subAreaID').text();
        }
        if ($(this).index() > 3 && $(this).index() < 13)
        {
            var difficulityComplexity = $(this).find('input').attr('class').split(' ')[3];
            var cellValue = $(this).find('input').val();
            var difficulityLevelComplexityLevel = uniqeQuestions.GetDifficulityComplexity(difficulityComplexity);
            var difficulity = difficulityLevelComplexityLevel.split('#')[0];
            var complexity = difficulityLevelComplexityLevel.split('#')[1];
            if (cellValue == null || cellValue == "")
            {
                cellValue = "";
            }
            if (cellValue != "")
            {
                var result = uniqeQuestions.MatrixRule(contentAreaId, subContentAreaId, difficulity, complexity, cellValue);
                if(result==1)
                {
                    $(this).find('input').val('');
                }
            }
        }    
    });
},
ValidateSubAreaItemsTotal:function ()
{

    var contentAreaId = "";
    var subContentAreaId = "";
    var itemsTotal = 0;
    var cellValueItemSum = 0;
    var valueChanged = false;
    var eventStop = true;
    $("#tblBodyMatrix tr").each(function ()
    {
        $('td', this).each(function ()
        {        
            if ($(this).index() == 0)
            {
                if (contentAreaId != $(this).find('.contentAreaID').text())
                {
                    itemsTotal = 0;
                    cellValueItemSum = 0;
                }  
                contentAreaId = $(this).find('.contentAreaID').text();
            }
            if ($(this).index() == 1)
            {

                if ($(this).html() != "")
                {
                    itemsTotal = parseInt($(this).html());            
                }
            }
            if ($(this).index() ==3)
            {

                var cellValue = $(this).find('input').val();
                if (cellValue == null || cellValue == "")
                {
                    cellValue = "";
                }
                if (cellValue != "")
                {
                    cellValueItemSum = cellValueItemSum + parseInt(cellValue);
                }
            }
        });
        if (itemsTotal < cellValueItemSum)
        {
            if (eventStop == true)
            {
                alert("Content sub area total can't be more than content area total ! ")
                uniqeQuestions.ClearCurrentRowCellsValue(this);
                eventStop = false;
            }
        }
     
    });
},
ClearCurrentRowCellsValue:function (tableRow)
{
    $(tableRow).each(function ()
    {
        $('td', this).each(function ()
        {
            $(this).find('input').val('');
        });
    });
},
ValidateDuplicateContentAreaSubContentArea:function ()
{
    var validationflag = true;
    var contentAreaId = "";
    var subContentAreaId = "";
    var ddlContentArea = $('#ddlContentArea').val();
    var ddlSubArea = $('#ddlSubArea').val();
    $("#tblBodyMatrix tr td").each(function ()
    {
        if ($(this).index() == 0)
        {      
            contentAreaId = $(this).find('.contentAreaID').text();
            subContentAreaId = "";
        }
        if ($(this).index() == 2)
        {
         
            subContentAreaId = $(this).find('.subAreaID').text();
        }
        if (contentAreaId == ddlContentArea && subContentAreaId == ddlSubArea)
        {
            if (validationflag)
            {
                alert("This content area and sub content area is already added in matrix  !");
                validationflag = false;
                contentAreaId = "";
            }
        }
    });
    return validationflag;
},
ValidateMatrixTotalRequiedItems:function ()
{
    var validationflag = true;
    var totalRequiredItems = parseInt($('#txtUnique').val());
    var txtAreaItem = $('#txtAreaItem').val();
    var getFooterTableTotal = 0;
    $("#questionsMatrixTableFooter tr td").each(function ()
    {
        if ($(this).index() == 1)
        {
            if ($(this).html() != "") {
                getFooterTableTotal = parseInt($(this).html());
            }
        }
     
    });
    var total = parseInt(getFooterTableTotal) + parseInt(txtAreaItem);
    if(total > totalRequiredItems)
    {
        alert("Please check the required items limit and matrix items ,You are trying to add more items than the required items !");
        validationflag = false;
    }
    return validationflag;
},
TotalRowFooter:function ()
{
    var totals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    var $dataRows = $("#tblBodyMatrix tr:not('.totalColumn, .titlerow')");
    $dataRows.each(function () {

        $(this).find('.rowDataSd').each(function (i) {

            var s = $(this).find('input').val();
            if ($(this).find('input').length == 0)
            {
                s = $(this).html();
            }
            if ($.isNumeric(parseInt(s))) {
           
                totals[i] += parseInt(s);
            }
        });
    });
    var itemsSum = 0;
    $("#uniqueTableMatrix td.totalCol").each(function (i)
    {
        if (i != 0 && i != 1 && i != 2 && i != 3 && i !=13)
        {
            itemsSum = itemsSum + parseInt(totals[i]);
        }
        if (i == 0)
        {
            $(this).html("Total :");
        }
        else
        {
            if (i == 2 || i ==13)
            {
                if (i == 13)
                {

                    $(this).html(itemsSum);
                }
                else
                {
                    $(this).html('');
                }
            }
            else
            {
             
                $(this).html(totals[i]);
            }
        }
     
    });

}}

Below will be result




Monday, 31 July 2017

Color picker in jquery and HTML









Below is reference







<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"></link>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script>
  $(document).ready(function(){
  $('#btnSubmit').click(function(){
 alert( $('#colorId').val());
});
 

  });

  </script>
  <input type="button" id='btnSubmit' class="btn btn-default" value='Get Color Code' />
     <input type="color" class="form-control" id="colorId">

Thursday, 29 June 2017

How to make a list of Object in JavaScript



How to make a list of Object  in JavaScript


<script>
 var cityObject= GetCityObjectArray();
for(var i=0;i<cityObject.length;i++)
{    
       alert(cityObject[i].Name);
}
 function GetCityObjectArray()
 {
        var cities = new Array();    
        for(var i=0;i<=10;i++)
        {  var city = {};
           city.Name = i;
           city.Population = i;
           cities.push(city);
        }
       console.log(cities);
       return cities;
  }
</script>



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  
        }

}