2017年11月22日 星期三

How to push value into structured array in Angularjs v1.x

How to push value into structured array in Angularjs v1.x 

Background
- angularjs v1.x
          
  // define $scope variables for store result
  $scope.roles = [];

        var getSomething = function () {            
            return $http({
                method: 'GET',
                url: 'http://www.somewhere.com/GetSomething'
            }).then(function successCallback(response) {
    // Assume return value is something like "ValueA, ValueB, ValueC, ValueD"
                angular.forEach(response.data, function(value, key){
     
     //target structure like this
     //  roles [ 
     //   {
     //   value : "ValueA",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueB",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueC",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueD",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   }     
     //       ]    
                    $scope.roles.push( {value:value, attr1:false, attr2:"attr2 value"} )
                });                
            }, function errorCallback(response) {                
            });
        };

2017年11月16日 星期四

How to call Modal Dialog (Custom html view) on Umbraco AngularJs

How to call Modal Dialog (Custom html view) on Umbraco AngularJs 


Background
- angularjs v1.x


view.html

<div ng-controller="myController">
    <div>
    <a class="btn" ng-disabled="actionInProgress" ng-click="toggleModal(functionA())" prevent-default>
        functionA
    </a>
    <a class="btn" ng-disabled="actionInProgress" ng-click="toggleModal(functionB())" prevent-default>
        functionB
    </a>
    <a class="btn" ng-disabled="actionInProgress" ng-click="toggleModal(functionC())" prevent-default>
        functionC
    </a>

    <modal-dialog callback-fn='actionName' show='modalShown' width='200px' height='15%'><p>Are you sure to proceed action?</p>
</div>


directive

'use strict';
var umbracoApp = angular.module('umbraco.directives');

umbracoApp.directive('modalDialog', function () {
    return {
        restrict: 'E',
        scope: {
            show: '=',
            actionName: '&callbackFn'            
        },
        replace: true, // Replace with the template below
        transclude: true, // we want to insert custom content inside the directive
        link: function (scope, element, attrs) {            
            scope.dialogStyle = {};
            if (attrs.width) {
                scope.dialogStyle.width = attrs.width;
            };
            if (attrs.height) {
                scope.dialogStyle.height = attrs.height;
            };
            scope.hideModal = function () {
                scope.show = false;
            };
            scope.confirmedClick = function () {
                scope.$eval(scope.actionName());                
                scope.show = false;
            };
        },
        templateUrl: "/App_Plugins/ThreewoodActiveDirectory/template/modal.dialog.html"        
    };
});

controller

'use strict';

(function () {
    // Create controller variable
    function myController($scope, $http, $injector, userService, notificationsService) {        

     $scope.modalShown = false;
        $scope.actionName = "";
        $scope.toggleModal = function (action) {
            $scope.actionName = action;
            $scope.modalShown = !$scope.modalShown;
        };

        $scope.functionA = function () {
            var fn = function () {
                alert("functionA");
            }
            return fn;
        };

        $scope.functionB = function () {
            var fn = function () {
                alert("functionB");
            }
            return fn;
        };

        $scope.functionC = function () {
            var fn = function () {
                alert("functionC");
            }
            return fn;
        };
               
    };


    // Register the controller    
    angular.module("umbraco").controller("myController", myController);
})();


modal dialog view

<div class='ng-modal' ng-show='show'>
    <div class='ng-modal-overlay' ng-click='hideModal()'></div>
    <div class='ng-modal-dialog' ng-style='dialogStyle'>                
        <div class='ng-modal-dialog-content' ng-transclude></div>                
        <div class="ng-modal-dialog-button">
            <button id="no" class="btn btn-warning" ng-click='hideModal()'>No</button>
            <button id="yes" class="btn" confirmed-action="actionName()" ng-click="confirmedClick()">Yes</button>
        </div>        
    </div>
</div>


modal dialog css

.ng-modal-overlay {
  /* A dark translucent div that covers the whole screen */
  position:absolute;
  z-index:9999;
  top:0;
  left:0;
  width:100%;
  height:100%;
  background-color:#000000;
  opacity: 0.8;
}
.ng-modal-dialog {
  /* A centered div above the overlay with a box shadow. */
  z-index:10000;
  position: absolute;
  width: 50%; /* Default */

  /* Center the dialog */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);

  background-color: #fff;
  box-shadow: 4px 4px 80px #000;
  text-align: center;
  border-radius: 10px;
}
.ng-modal-dialog-content {
  padding:10px;
  text-align: center;
  font-weight: bold;
}
.ng-modal-close {
  position: absolute;
  top: 3px;
  right: 5px;
  padding: 5px;
  cursor: pointer;
  font-size: 120%;
  display: inline-block;
  font-weight: bold;
  font-family: 'arial', 'sans-serif';
}

.ng-modal-dialog-button {

}


AngularJs Pass function to directive without execute it.

HAngularJs Pass function to directive without execute it

Background
- angularjs v1.x


view

<div ng-controller="myController">
 <a class="btn" ng-click="someMethod(myFunction())" prevent-default></a>
</div>


controller

'use strict';

(function () {
    // Create controller variable
    function myController($scope) {        

       $scope.someMethod = function (action) {
          $scope.actionName = action;            
       };

       $scope.myFunction = function () {
       var fn = function () {
            alert("Hello There!");
          };
       return fn;
       }; 
    };

    // Register the controller    
    angular.module("umbraco").controller("myController", myController);
})();

Explantion

put the you own logic inside

var fn = function () {
    alert("Hello There!");
};

replace the alert by your own logic.

at last return the fn

and when pass the function

ng-click="someMethod(myFunction())"

myFunction must be include bracket (),

declare the function and assign a variable fn for that, it will not execute while parsing when the website startup. It just expression, it will execute it when you evaluate the expression in where you want to.

$eval($scope.actionName()); 

P.S The declaration of function very very critical, and end of the function must return fn

How to call Modal Dialog (Window) on Umbraco AngularJs

How to call Modal Dialog (Window) on Umbraco AngularJs 


Background
- angularjs v1.x


view.html

<div ng-controller="myController">
    <div>
        <button ng-confirm-click="Custom Message" class="btn" confirmed-click='confirmclick()' cancel-click='cancelClick()' >Test</button>        
    </div>
</div>


directive

'use strict';
var umbracoApp = angular.module('umbraco.directives');

umbracoApp.directive('ngConfirmClick', function () {
    return {        
        link: function (scope, element, attrs) {
            var msg = attrs.ngConfirmClick || "Are you sure?";
            var confirmClickAction = attrs.confirmedClick;
            var cancelClickAction = attrs.cancelClick;
            element.bind('click', function (event) {
                if (window.confirm(msg)) {
                    scope.$eval(confirmClickAction)                    
                }
                else
                {
                    scope.$eval(cancelClickAction)
                }
            });
        }        
    };
});

controller

'use strict';

(function () {
    // Create controller variable
    function MyController($scope) {        

        $scope.confirmclick = function (element) {
            alert("confirm clicked");
        };

        $scope.cancelClick = function (element) {            
            alert("cancel clicked");
        };        

    // Register the controller    
    angular.module("umbraco").controller("myController", MyController);
})();

2017年11月13日 星期一

2017年11月9日 星期四

Umbraco Language for Packages

Environment
- Umbraco version 7.7.4
- Applies to version 7.3.0 and newer


en-GB.xml sample file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<language alias="en-GB" intName="English (US)" localName="English (US)" lcid="" culture="en-US">
  <creator>
    <name>{Your Name}</name>
    <link>{Your Website}</link>
  </creator>
  <area alias="{Your Alias Name}">
    <!-- DASHBOARD -->
    <key alias="Dashboard.Title"><![CDATA[Welcome to Dashboard]]></key>
    <key alias="Dashboard.SubTitle"><![CDATA[Dashboard Subtitle.]]></key>
    <key alias="Dashboard.Description">
      <![CDATA[ Dashboard Description ]]>
    </key>
    <key alias="Dashboard.LatestChanges"><![CDATA[]]></key>
    <key alias="Dashboard.VersionHistory"><![CDATA[]]></key>
    <key alias="Dashboard.LoadButton">Load</key>
  </area>
</language>

<area alias="{Your Alias Name}">

For example:
<area alias="MyAlias">


dashboard.html sample
<div class="welcome-dashboard" ng-controller="My.Dashboard.ViewController">
    <div class="row-fluid">
        <div class="umb-sub-header">
   <h3 class="title"><localize key="MyAlias_Dashboard.Title"></localize></h3> 
   <div class="subtitle"><localize key="MyAlias_Dashboard.SubTitle"></localize></div>
   <div class="description"><localize key="MyAlias_Dashboard.Description"></localize></div>
        </div>
    </div>    

    <div class="row-fluid">
        <div class="btn-group">
            <a class="btn" href="#">                
                <localize key="MyAlias_Dashboard.LoadButton"></localize>         
            </a>           
        </div>
    </div>
</div>



Place the file under /app_plugins/mypackage/lang/en-GB.xml

naming convention of the key

{Area alias}_{Key alias}

Example : title

Area alias =  MyAlias
Key alias = Dashboard.Title

=> MyAlias_Dashboard.Title

P.S Please check and touch web.config file to reload the umbraco caches(NOT browser caches) in case the text displayed which is not expected (refreshed).


Reference:
Umbraco Official KB

2017年11月8日 星期三

LDAP simple query and C# approach

Find All user

(&(objectClass=user)(objectClass=person))

Find All active user 

(&(objectClass=user)(objectClass=person)(!userAccountControl:1.2.840.113556.1.4.803:=2))

Find All active user without empty email and display Name

(&(objectClass=user)(objectClass=person)(!userAccountControl:1.2.840.113556.1.4.803:=2)(mail=*)(displayName=*))


C# approach


public List<UserProfile> GetAllUser(string ldapQueryString)
        {
            try
            {
                using (HostingEnvironment.Impersonate())
                {
                    _directoryEntry = null;
                    DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                    directorySearch.Filter = string.Format("(&(objectClass=user)(objectClass=person){0})", ldapQueryString);
                    directorySearch.PageSize = 500;
                    SearchResultCollection allUsers = directorySearch.FindAll();

                    if (allUsers != null)
                    {
                        List<UserProfile> users = new List<UserProfile>();
                        foreach (SearchResult u in allUsers)
                        {
                            DirectoryEntry de = new DirectoryEntry(u.Path);
                            users.Add(UserProfile.GetUser(de));
                        }
                        return users;
                    }
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error<ActiveDirectoryHelper>("GetUserByFullName Exception: ", ex);
                return null;
            }
        }

UserProfile Class
public class UserProfile
    {
        private Guid _guid;
        private String _distinguishedName;
        private String _displayName;
        private String _firstName;
        private String _middleName;
        private String _lastName;
        private String _loginName;
        private String _loginNameWithDomain;
        private String _streetAddress;
        private String _city;
        private String _state;
        private String _postalCode;
        private String _country;
        private String _homePhone;
        private String _extension;
        private String _mobile;
        private String _fax;
        private String _emailAddress;
        private String _title;
        private String _company;
        private String _manager;
        private String _managerName;
        private String _department;

        public Guid GUID
        {
            get { return _guid; }
        }

        public string DistinguishedName
        {
            get { return _distinguishedName; }
        }             

        public String Department
        {
            get { return _department; }
        }

        public String FirstName
        {
            get { return _firstName; }
        }

        public String MiddleName
        {
            get { return _middleName; }
        }

        public String LastName
        {
            get { return _lastName; }
        }

        public String DisplayName
        {
            get { return _displayName; }
        }

        public String LoginName
        {
            get { return _loginName; }
        }

        public String LoginNameWithDomain
        {
            get { return _loginNameWithDomain; }
        }

        public String StreetAddress
        {
            get { return _streetAddress; }
        }

        public String City
        {
            get { return _city; }
        }

        public String State
        {
            get { return _state; }
        }

        public String PostalCode
        {
            get { return _postalCode; }
        }

        public String Country
        {
            get { return _country; }
        }

        public String HomePhone
        {
            get { return _homePhone; }
        }

        public String Extension
        {
            get { return _extension; }
        }

        public String Mobile
        {
            get { return _mobile; }
        }

        public String Fax
        {
            get { return _fax; }
        }

        public String EmailAddress
        {
            get { return _emailAddress; }
        }

        public String Title
        {
            get { return _title; }
        }

        public String Company
        {
            get { return _company; }
        }

        public UserProfile Manager
        {
            get
            {
                if (!String.IsNullOrEmpty(_managerName))
                {
                    ActiveDirectoryHelper activeDirectoryHelper = new ActiveDirectoryHelper();
                    return activeDirectoryHelper.GetUserByFullName(_managerName);
                }
                return null;
            }
        }

        public String ManagerName
        {
            get { return _managerName; }
        }


        private UserProfile(DirectoryEntry directoryUser)
        {

            String domainAddress;
            String domainName;

            _guid = directoryUser.Guid;
            _distinguishedName = GetProperty(directoryUser, Properties.DISTINGUISHEDNAME);
            _firstName = GetProperty(directoryUser, Properties.FIRSTNAME);
            _middleName = GetProperty(directoryUser, Properties.MIDDLENAME);
            _lastName = GetProperty(directoryUser, Properties.LASTNAME);
            _displayName = GetProperty(directoryUser, Properties.DISPLAYNAME);
            _loginName = GetProperty(directoryUser, Properties.LOGINNAME);
            String userPrincipalName = GetProperty(directoryUser, Properties.USERPRINCIPALNAME);

            if (!string.IsNullOrEmpty(userPrincipalName))
            {
                domainAddress = userPrincipalName.Split('@')[1];
            }
            else
            {
                domainAddress = String.Empty;
            }

            if (!string.IsNullOrEmpty(domainAddress))
            {
                domainName = domainAddress.Split('.').First();
            }
            else
            {
                domainName = String.Empty;
            }

            _loginNameWithDomain = String.Format(@"{0}\{1}", domainName, _loginName);
            _streetAddress = GetProperty(directoryUser, Properties.STREETADDRESS);
            _city = GetProperty(directoryUser, Properties.CITY);
            _state = GetProperty(directoryUser, Properties.STATE);
            _postalCode = GetProperty(directoryUser, Properties.POSTALCODE);
            _country = GetProperty(directoryUser, Properties.COUNTRY);
            _company = GetProperty(directoryUser, Properties.COMPANY);
            _department = GetProperty(directoryUser, Properties.DEPARTMENT);
            _homePhone = GetProperty(directoryUser, Properties.HOMEPHONE);
            _extension = GetProperty(directoryUser, Properties.EXTENSION);
            _mobile = GetProperty(directoryUser, Properties.MOBILE);
            _fax = GetProperty(directoryUser, Properties.FAX);
            _emailAddress = GetProperty(directoryUser, Properties.EMAILADDRESS);
            _title = GetProperty(directoryUser, Properties.TITLE);
            _manager = GetProperty(directoryUser, Properties.MANAGER);

            if (!String.IsNullOrEmpty(_manager))
            {
                String[] managerArray = _manager.Split(',');
                _managerName = managerArray[0].Replace("CN=", "");
            }
        }


        private static String GetProperty(DirectoryEntry userDetail, String propertyName)
        {
            if (userDetail.Properties.Contains(propertyName))
            {
                return userDetail.Properties[propertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public static UserProfile GetUser(DirectoryEntry directoryUser)
        {
            return new UserProfile(directoryUser);
        }
    }


Reference
LDAP Query Basics
KB for query disabled user

2017年11月7日 星期二

How to save the Umbraco member password via code

Environment
- Umbraco version 7.7.4


public static int CreateMember(string usernameWithDomain, string name, string email, string password = null, List<string> roleNames = null, List<KeyValuePair<string, string>> properties = null, string memberType = "Member")
        {            
            try
            {
                IMember member = ApplicationContext.Current.Services.MemberService.CreateMember(usernameWithDomain, email, name, memberType);

                member.IsApproved = true;
                if (properties != null)
                {
                    foreach (var property in properties)
                    {
                        member.SetValue(property.Key, property.Value);
                    }
                }

                ApplicationContext.Current.Services.MemberService.Save(member);

                if (string.IsNullOrEmpty(password))
                {
                    password = Guid.NewGuid().ToString().Substring(0, 8);
                }
                ApplicationContext.Current.Services.MemberService.SavePassword(member, password);
                
                if (roleNames != null)
                {
                    foreach (string roleName in roleNames)
                    {
                        if (!String.IsNullOrEmpty(roleName))
                        {
                            ApplicationContext.Current.Services.MemberService.AssignRole(member.Id, roleName);
                        }
                    }
                }

                LogHelper.Info<MemberHelper>(string.Format("{0}(name) created, {1}(id)", name, member.Id));
                return member.Id;
            }
            catch (Exception ex)
            {
                LogHelper.Error<MemberHelper>("CreateMember exception: ", ex);
                return -1;
            }
        }

web.config

allowManuallyChangingPassword="true"