Thursday, 19 November 2020

Apply currency filter to the input field in angularjs

 <!DOCTYPE html>

<html>

<head>
    <script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script src="https:///maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

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

    <link rel="stylesheet" href="style.css" />
    <script>
        // Code goes here
        var app = angular.module('testapp', []);
        app.controller('appController'function($scope) {

            $scope.positiveNumber = 0;
            $scope.negativeNumber = 0;
            $scope.decimal = 0;
            $scope.decimalUpto = 0
            $scope.negativedecimal = 0;
            $scope.negativedecimalUpto = 0
            $scope.total = 0;
        });
        angular.module('testapp').directive('validNumber'function() {
            return {
                require: '?ngModel',
                link: function(scopeelementattrsngModelCtrl) {

                    element.on('keydown'function(event) {
                            var keyCode = []
                            if (attrs.allowNegative == "true") {
                                keyCode = [893635373946484950515253545556,
                                    5796979899100101102103104105109110173,
                                    190189
                                ];
                            } else {
                                var keyCode = [8936353739464849505152535455,
                                    565796979899100101102103104105110173,
                                    190
                                ];
                            }


                            if (attrs.allowDecimal == "false") {

                                var index = keyCode.indexOf(190);


                                if (index > -1) {
                                    keyCode.splice(index1);
                                }

                            }

                            if ($.inArray(event.whichkeyCode) == -1event.preventDefault();
                            else {
                                console.log(2);
                                var oVal = ngModelCtrl.$modelValue || '';
                                if ($.inArray(event.which, [109173]) > -1 && oVal.indexOf('-') > -1)
                                    event.preventDefault();
                                else if ($.inArray(event.which, [110190]) > -1 && oVal.indexOf('.') >
                                    -1event.preventDefault();
                            }
                        })
                        .on('blur'function() {

                            if (element.val() == '' || parseFloat(element.val()) == 0.0 || element
                                .val() == '-') {
                                ngModelCtrl.$setViewValue('0.00');
                            } else if (attrs.allowDecimal == "false") {
                                ngModelCtrl.$setViewValue(element.val());
                            } else {
                                if (attrs.decimalUpto) {
                                    var fixedValue = parseFloat(element.val()).toFixed(attrs
                                        .decimalUpto);
                                } else {
                                    var fixedValue = parseFloat(element.val()).toFixed(2);
                                }
                                ngModelCtrl.$setViewValue(fixedValue);
                            }



                            ngModelCtrl.$render();
                            scope.$apply();
                        });

                    ngModelCtrl.$parsers.push(function(text) {
                        var oVal = ngModelCtrl.$modelValue;
                        var nVal = ngModelCtrl.$viewValue;
                        console.log(nVal);
                        if (parseFloat(nVal) != nVal) {

                            if (nVal === null || nVal === undefined || nVal == '' || nVal == '-')
                                oVal = nVal;

                            ngModelCtrl.$setViewValue(oVal);
                            ngModelCtrl.$render();
                            return oVal;
                        } else {
                            var decimalCheck = nVal.split('.');
                            if (!angular.isUndefined(decimalCheck[1])) {
                                if (attrs.decimalUpto)
                                    decimalCheck[1] = decimalCheck[1].slice(0attrs.decimalUpto);
                                else
                                    decimalCheck[1] = decimalCheck[1].slice(02);
                                nVal = decimalCheck[0] + '.' + decimalCheck[1];
                            }

                            ngModelCtrl.$setViewValue(nVal);
                            ngModelCtrl.$render();
                            return nVal;
                        }
                    });

                    ngModelCtrl.$formatters.push(function(text) {
                        if (text == '0' || text == null && attrs.allowDecimal == "false")
                            return '0';
                        else if (text == '0' || text == null && attrs.allowDecimal != "false" &&
                            attrs.decimalUpto == undefinedreturn '0.00';
                        else if (text == '0' || text == null && attrs.allowDecimal != "false" &&
                            attrs.decimalUpto != undefinedreturn parseFloat(0).toFixed(attrs
                            .decimalUpto);
                        else if (attrs.allowDecimal != "false" && attrs.decimalUpto != undefined)
                            return parseFloat(text).toFixed(attrs.decimalUpto);
                        else return parseFloat(text).toFixed(2);
                    });
                }
            };
        });
        app.directive('format', ['$filter'function($filter) {
            return {
                require: '?ngModel',
                link: function(scopeelemattrsctrl) {
                    if (!ctrlreturn;

                    ctrl.$formatters.unshift(function(a) {
                        return $filter(attrs.format)(ctrl.$modelValue)
                    });

                    elem.bind('blur'function(event) {
                        var plainNumber = elem.val().replace(/[^\d|\-+|\.+]/g'');
                        elem.val($filter(attrs.format)(plainNumber));
                    });
                }
            };
        }]);
    </script>
</head>

<body>
    <div data-ng-app="testapp">

        <form class="col-md-6">
            <div class="form-group">
                <label for="exampleInputEmail1">Positive Number</label>
                <input class="form-control" valid-number ng-model="positiveNumber" placeholder="" allow-decimal="false" allow-negative="false" type="text" format="currency">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail1">Negative Number</label>
                <input class="form-control" valid-number ng-model="negativeNumber" placeholder="" allow-decimal="false" allow-negative="true" type="text" format="currency">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail1">Positive Decimal Numbers Default Decimal-Upto 2</label>
                <input class="form-control" valid-number ng-model="decimal" placeholder="" allow-decimal="true" allow-negative="false" type="text">
            </div>

            <div class="form-group">
                <label for="exampleInputEmail1">Positive Decimal Numbers Decimal-Upto 3</label>
                <input class="form-control" valid-number ng-model="decimalUpto" placeholder="" allow-decimal="true" allow-negative="false" decimal-upto="3" type="text">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail1">Negative Decimal Numbers Default Decimal-Upto 2</label>
                <input class="form-control" valid-number ng-model="negativdecimal" placeholder="" allow-decimal="true" allow-negative="true" type="text">
            </div>

            <div class="form-group">
                <label for="exampleInputEmail1">Negative Decimal Numbers Decimal-Upto 3</label>
                <input class="form-control" valid-number ng-model="negativdecimalUpto" placeholder="" allow-decimal="true" allow-negative="true" decimal-upto="3" type="text">
            </div>
            <input type="text" ng-model="test" format="number" />
            <input type="text" ng-model="test" format="currency" />



        </form>

    </div>
</body>

</html>

Monday, 16 November 2020

add min date and max date validation in angular ui-bootstrap datepicker when using ui-bootstrap version 1.3.3

Date is returning one day less when using REST Api

https://social.technet.microsoft.com/Forums/sharepoint/en-US/ba54d2d7-2279-4d52-baff-1c343fc910c1/date-is-returning-one-day-less-when-using-rest-api?forum=sharepointdevelopment

 <!doctype html>

<html ng-app="ui.bootstrap.demo">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
   <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
         <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> 
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.js"></script>
         <style>
     
 .registration-form .form-control{

     border-radius:2px;

 }



.registration-form .has-error .form-control.registration-form .has-error .form-control:hover.registration-form .has-error .form-control:active{

        border-colorred;
   box-shadownone !important;

}

.has-error input[type="text"]:focus,
.has-error input[type="password"]:focus,
.has-error input[type="number"]:focus{
   background-colorred !important
}
.registration-form label{
    font-weightnormal;
}

.registration-form .form-group input[type="text"]:focus,
.registration-form .form-group input[type="password"]:focus,
.registration-form .form-group input[type="number"]:focus{
 
     outlinenone;
    box-shadow:none !important;
    background-color:#18b6d6;
  

 }
 
 
.error_message_text{
color:red;
}
.glyphicon{
vertical-alignbottom;
    floatright;}
  
  
  
.dob-select-container{
    margin0px;
    padding0px;

}

.dob-select-container .dd .ddTitle .ddTitleText {
    width100%;
}

.styled-select {
     displayinline-block
     height33px
     margin-right10px
}

.styled-select  .ddcommon  {
    width78px !important;
}

</style>
    
    <script>
      angular.module('ui.bootstrap.demo', ['ngAnimate''ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('DatepickerPopupDemoCtrl'function ($scope) {
  $scope.today = function() {
    $scope.dt = new Date();
  };
 //$scope.today();
  $scope.dt = new Date();
  $scope.clear = function() {
    $scope.dt = null;
  };

  $scope.inlineOptions = {
    customClass: getDayClass,
   // minDate: new Date(),
    showWeeks: true
  };

  $scope.dateOptions = {
    dateDisabled: disabled,
    formatYear: 'yy',

    startingDay: 1
  };

  // Disable weekend selection
  function disabled(data) {
    var date = data.date,
      mode = data.mode;
    return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
  }

$scope.toggleMin = function() {
    var date = new Date();
    date.setDate((new Date()).getDate() - 30);
    $scope.dateOptions.minDate = date;
  };
  $scope.toggleMin();
  $scope.setMin = function() {
    var date = new Date($scope.dt);
    alert("gg");
    date.setDate((date).getDate() - 30);
    $scope.dateOptions.minDate = date;
  };

var date1 = new Date();
date1.setDate((new Date()).getDate() + 30);
$scope.dateOptions.maxDate = date1;
  
  $scope.open1 = function() {
    $scope.popup1.opened = true;
  };

  $scope.open2 = function() {
    $scope.popup2.opened = true;
  };

  $scope.setDate = function(yearmonthday) {
    $scope.dt = new Date(yearmonthday);
  };

  $scope.formats = ['dd-MMMM-yyyy''yyyy/MM/dd''dd.MM.yyyy''shortDate','dd/MM/yyyy'];
  $scope.format = $scope.formats[0];
  //$scope.altInputFormats = ['M!/d!/yyyy'];

  $scope.popup1 = {
    opened: false
  };

  $scope.popup2 = {
    opened: false
  };

  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  var afterTomorrow = new Date();
  afterTomorrow.setDate(tomorrow.getDate() + 1);
  $scope.events = [
    {
      date: tomorrow,
      status: 'full'
    },
    {
      date: afterTomorrow,
      status: 'partially'
    }
  ];

  function getDayClass(data) {
    var date = data.date,
      mode = data.mode;
    if (mode === 'day') {
      var dayToCheck = new Date(date).setHours(0,0,0,0);

      for (var i = 0i < $scope.events.lengthi++) {
        var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);

        if (dayToCheck === currentDay) {
          return $scope.events[i].status;
        }
      }
    }

    return '';
  }
});
    </script>
  
  </head>
  <body>
  <div class="container registration-form">
      <form name="memberForm" class="form-inline" novalidate>
<div ng-controller="DatepickerPopupDemoCtrl">
    

    <h4>Popup</h4>
 
       <div class="form-group" ng-class="{ 'has-error' : memberForm.dateOfBirth.$invalid && (memberForm.dateOfBirth.$touched || memberForm.$submitted) }">
                    <label for="Date of Birth"  class="" ng-hide="memberForm.dateOfBirth.$invalid && (memberForm.dateOfBirth.$touched || memberForm.$submitted)">Date of Birth(dd/mm/yyyy)*</label>
                    <label class="error_message_text" ng-show="memberForm.dateOfBirth.$invalid && (memberForm.dateOfBirth.$touched || memberForm.$submitted)"> Date of birth is required </label>
                      <p class="input-group" style="width:270px;" >
          <input type="text" class="form-control" name="dateOfBirth" 
          uib-datepicker-popup="MM/dd/yyyy" ng-model="dt" 
          is-open="popup1.opened" datepicker-options="dateOptions" 
          min-date="minDate" max-date="maxDate" 
          ng-required="true" close-text="Close" alt-input-formats="altInputFormats" ng-change="setMin()" ng-readonly="true"/>
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
          </span>
        </p>                 
         </div>
    
    <button type="submit" class="btn btn-blue-1">Submit</button>
  
  </form>
  </div>
  </body>
</html>

Tuesday, 3 November 2020

Programatically Copy all SharePoint List Items to Another List from Another Site with Attachments

 private static void MigrateItems(string ListName, string sourceSiteUrl, string destSiteUrl)

        {

            string sourceAccessToken = GetToken(sourceSiteUrl);

            try

            {

                using (ClientContext sourcecontext = 

                  TokenHelper.GetClientContextWithAccessToken(sourceSiteUrl, sourceAccessToken))

                {

                    MigrateListItemsWithAttachments(ListName, sourcecontext, destSiteUrl);

                }

            }

            catch (Exception ex)

            {

                //log exception

            }

        }


 private static void MigrateListItemsWithAttachments

(string listName, ClientContext sourceContext, string destSite)

        {

            List sourceList = null;

            ListItemCollection itemsToMigrate = null;

            List destinationList = null;            

            string siteUserName = "";

            try

            {

                sourceList = sourceContext.Web.Lists.GetByTitle(listName);

                itemsToMigrate = sourceList.GetItems(CamlQuery.CreateAllItemsQuery());

                sourceContext.Load(itemsToMigrate);

                sourceContext.ExecuteQuery();


                string sitePassword = Convert.ToString

                                      (ConfigurationManager.AppSettings["SharePointPassword"]);

                SecureString securePassword = new SecureString();

                foreach (char c in sitePassword) { securePassword.AppendChar(c); }

                using (ClientContext destContext = new ClientContext(destSite))

                {

                    destContext.Credentials = new SharePointOnlineCredentials

                                              (siteUserName, securePassword);

                    destinationList = destContext.Web.Lists.GetByTitle(listName);

                    destContext.Load(destinationList.Fields);

                    destContext.ExecuteQuery();

                    //Migrating data.

                    foreach (ListItem item in itemsToMigrate)

                    {

                        ListItemCreationInformation itemInfo = new ListItemCreationInformation();

                        ListItem itemToCreate = destinationList.AddItem(itemInfo);

                        AttachmentCollection attachmentCollection = item.AttachmentFiles;

                        foreach (Field field in destinationList.Fields)

                        {

                            if (!field.ReadOnlyField && !field.Hidden && 

                                 field.InternalName != "Attachments")

                            {

                                try

                                {

                                    itemToCreate[field.InternalName] = item[field.InternalName];

                                }

                                catch (Exception ex)

                                {

                                    //Log exception

                                }

                            }

                        }

                        itemToCreate.Update();

                        destContext.ExecuteQuery();

                        UpdateAttachments

                           (sourceContext, destContext, item.Id, itemToCreate.Id, listName);

                    }

                }

            }

            catch (Exception ex)

            {

                //Log exception               

            }

        }


        private static void UpdateAttachments(ClientContext srccontext, 

              ClientContext dstcontext, int srcItemID, int destItemID, string listName)

        {

            try

            {

                //getting attachment from files

                Web srcweb = srccontext.Web;

                srccontext.Load(srcweb);

                srccontext.ExecuteQuery();

                string src = string.Format("{0}/lists/{1}/Attachments/{2}", 

                                  srcweb.Url, listName, srcItemID);

                Folder attachmentsFolder = srcweb.GetFolderByServerRelativeUrl(src);

                srccontext.Load(attachmentsFolder);

                FileCollection attachments = attachmentsFolder.Files;

                srccontext.Load(attachments);

                srccontext.ExecuteQuery();


                if (attachments.Count > 0)

                {

                    foreach (Microsoft.SharePoint.Client.File attachment in attachments)

                    {                       

                        ClientResult<Stream> clientResultStream = attachment.OpenBinaryStream();

                        srccontext.ExecuteQuery();

                        var stream = clientResultStream.Value;


                        AttachmentCreationInformation attachFileInfo = 

                                                     new AttachmentCreationInformation();

                        Byte[] buffer = new Byte[attachment.Length];

                        int bytesRead = stream.Read(buffer, 0, buffer.Length);

                        System.IO.MemoryStream stream2 = new System.IO.MemoryStream(buffer);

                        attachFileInfo.ContentStream = stream2;

                        attachFileInfo.FileName = attachment.Name;                     


                        Web destweb = dstcontext.Web;

                        List destlist = destweb.Lists.GetByTitle(listName);

                        ListItem destitem = destlist.GetItemById(destItemID);

                        dstcontext.Load(destitem);

                        dstcontext.ExecuteQuery();

                        Attachment a = destitem.AttachmentFiles.Add(attachFileInfo);

                        dstcontext.Load(a);

                        dstcontext.ExecuteQuery();

                        stream2.Close();

                    }

                }

            }

            catch (Exception ex)

            {

               //Log exception

            }

        }