Why is it bad to use exceptions for handling this type of validation? It seems like it makes the code so much cleaner

I’m working on a .NET Core REST API and I’m writing a service class to create new user accounts. I have the following code:

    public async Task<UserDto> RegisterNewUserAccount(CreateAccountDto userInfo)     {         EnsureUserDoesNotAlreadyExist(userInfo);         EnsureRfidCardIsNotAlreadyClaimed(userInfo);          var user = new UserDto()         {             Email = userInfo.EmailAddress.ToLower(),             FirstAndLastName = userInfo.FirstAndLastName,             Rank = 1200,             JoinedTimestamp = DateTime.UtcNow.ToString()         };          await _usersRepository.CreateUser(user);          var passwordHasher = new PasswordHasher<AccountCredentials>();         var credentials = new AccountCredentials()         {             Email = userInfo.EmailAddress.ToLower(),             HashedPassword = passwordHasher.HashPassword(null, userInfo.Password)         };          await _accountCredentialsRepository.InsertNewUserCredentials(credentials);         await _emailSender.SendNewUserWelcomeEmail(userInfo);          return await _usersRepository.GetUserWithEmail(user.Email);     }      private void EnsureUserDoesNotAlreadyExist(CreateAccountDto userInfo)     {         if (_usersRepository.GetUserWithEmail(userInfo.EmailAddress) != null)         {             throw new ResourceAlreadyExistsException("Email already in use.");         }     }      private void EnsureRfidCardIsNotAlreadyClaimed(CreateAccountDto userInfo)     {         if (_usersRepository.GetUserWithRfid(userInfo.RfidNumber) != null)         {             throw new ResourceAlreadyExistsException("RFID card already in use.");         }     } 

To me, this code is clean, readable, and obvious in what it does. However, it seems like a lot of people are strictly against using exceptions for this type of logic. I know exceptions shouldn’t be used for normal control flow, but for something like this, it seems so natural. The one thing I’ve considered changing is renaming the two helper methods to ThrowIfUserAlreadyExists and ThrowIfRfidCardIsAlreadyClaimed, to make it more clear that these private helper methods serve no purpose other than to throw an exception if a condition is met.

Obviously, I wouldn’t want to use exceptions for validating general user input, such as making sure their password meets the requirements, etc., but in cases like this the line seems blurred.

If you believe this is bad practice, how would you write code such as this instead? Why is it bad to do it the way I have?

Exception Handling in Class

I have read a few sites on how to handle exceptions and I think I understand it better. Here is how I plan to handle it going forward. I used a lot of the guidelines here, https://isocpp.org/wiki/faq/exceptions.

Is this a sensible to handle it with c++14 as I’m using visual studio 2015. Would it be different with C++17?

#include <iostream> #include <exception> #include <string>  #define THROWFOORTE(what) throw FooRuntimeException(what, __FILE__, __func__, __LINE__) #define THROWFOORE(what) throw FooRangeError(what, __FILE__, __func__, __LINE__)  struct FooRuntimeException     : public std::runtime_error {     FooRuntimeException(const char* what,          const char* file, const char* func, int line)         : runtime_error(std::string(file) +":" +              std::string(func) + ":" + std::to_string(line)              + " " + std::string(what)) {} };  struct FooRangeError     : public std::range_error {     FooRangeError(const char* what,         const char* file, const char* func, int line)         : range_error(std::string(file) + ":" +             std::string(func) + ":" + std::to_string(line)             + " " + std::string(what)) {} };  class Foo { public:     Foo() = default;     ~Foo() {};      void throwRunTimeException()     {         THROWFOORTE("Runtime Error");     }     void throwRangeError()     {         THROWFOORE("Range Error");     } };  void HandleException() {     try { throw; }     catch (const FooRuntimeException &e)     {         std::cerr << e.what() << '\n'; // catches standard error message     }     catch (const FooRangeError&e)     {         std::cerr << e.what() << '\n';; // catches standard error message     }     return; }  int main() {     try     {         auto foo = Foo();         foo.throwRunTimeException();     }     catch (...) {         HandleException();     }        try     {         auto foo = Foo();         foo.throwRangeError();     }     catch (...) {         HandleException();     }      return 0; } 

UDP socket error handling best practices

I have many UDP Clients (from different endpoints/machines) that send data to a single server.
The current code is legacy, it basically use open source SyslogUdpSender.

There is a wrapper class for SyslogUdpSender, but, for each client endpoint there is 1 instance of wrapper, there is no error handling mechanism, if exception is thrown from socket, it will log exception and then wait for next call (next execution of .Send(..) method).
I need to fix this bad behavior, if socket is not functioning anymore, i want to reopen and fix its state. so i could continue sending data, current code basically abuse the same socket over and over.

From what I understand, basically, The client endpoint machine, create only 1 UDP Socket, and use the same open socket over and over, the socket is only opened when instance is created, and never closed. So when it gets to a faulted state, there is no attempt to reopen it.

I thought about adding the following logic:

  1. call SyslogUdpSender.Send(), if SocketException is catched:
    Try X times with Y Halt between attempts, usually 3 times with 100 MS delay.
    If this fails also, Close the socket and re-open it, If reopening the socket does not work for X times, then halt the entire client from sending for Z seconds (maybe server is down, or OS is so overloaded it cannot even open new UDP Socket).

  2. Create SyslogUdpSender pool, Create 10 (configurable) clients for each machine, and send the message to the pool, this way, we decrease the load on the same socket.

Are there any best practices to use socket (especially UDP) ?

Thanks

Handling multiple request at the same time on same resource [on hold]

I got some new case for me so there is an item A in database that has a quantity 1 and we got 2 user that want to checkout 1 Item A at the same time. How should the API response for these type of multiple request should we handling one of them and what is the approach for handling multiple request like this ??

C# Class for handling Player Movement and / or similar behaviour

I am currently developing a unity-based multiplatform game (PC, IOS, Android) in a small team. This is the code we have created for the Character Actions inside the game. I am looking for feedback on the code itself as well as tips on how some Unity features could be used better. This is my first time developing a game with Unity.

The Game is also aimed for Mobile platforms as state above, so tips on optimization are welcome.

using AI.Enemy; using UnityEngine;  namespace Player.Script.Miru {     public class MiruScript : MonoBehaviour     {     public float Health;     public float MoveSpeed;     public float JumpHeight;      public float EvadeSpeed;     public float DefendCooldownTimer;     public float NormalDamage;     public float Cooldown;     public float Stamina;     public float HealthRegenerationRate;     public float StaminaRegenerationRate;      private bool _IsFacingForward;     private bool _IsGrounded;     private Rigidbody2D _RigidBody;     private RaycastHit2D _GroundDetector;     private RaycastHit2D _RightRayCast;     private RaycastHit2D _LeftRayCast;     private MinionScript _MinionScript;      private void Start() //Temporary values     {         MoveSpeed = 4f * Time.deltaTime;         JumpHeight = 10f;         EvadeSpeed = 5f;         DefendCooldownTimer = 0f;         NormalDamage = 50f;         Cooldown = 1f;         Stamina = 100f;         Health = 100f;         HealthRegenerationRate = 0.5f;         StaminaRegenerationRate = 10f;         _RigidBody = GetComponent<Rigidbody2D>();         _MinionScript = GetComponent<MinionScript>();     }      private void Update()     {         MoveRight(MoveSpeed);         MoveLeft(MoveSpeed);         Jump(JumpHeight);         Evade(EvadeSpeed);         Attack(NormalDamage);         DistanceFromObject();         AttackCooldown();         Defend();     }      private bool AttackCooldown()     {         if (Cooldown < 1f)         {             Cooldown += Time.deltaTime;             return true;         }          return false;     }      public int DamageDealt(float _damageDealt)     {         Health -= _damageDealt;          if (Health <= 0)             Destroy(gameObject);          return 0;     }      private int DistanceFromObject()     {         _RightRayCast = Physics2D.Raycast(transform.position, Vector2.right);         _LeftRayCast = Physics2D.Raycast(transform.position, Vector2.left);          if (_RightRayCast.distance < 1.5f && _LeftRayCast.distance < 1.5f)             return 3;          if (_RightRayCast.distance < 1.5f)             return 1;          if (_LeftRayCast.distance < 1.5f)             return 2;          return 0;     }      private int Attack(float _damageDealt)     {         if (_IsFacingForward && Input.GetKeyDown(KeyCode.X) && _RightRayCast.distance <= 1.5f && !AttackCooldown())         {             _MinionScript = _RightRayCast.collider.gameObject.GetComponent<MinionScript>();             _MinionScript.DamageDealt(_damageDealt);             Cooldown = 0;             return 1;         }          if (_IsFacingForward == false && Input.GetKeyDown(KeyCode.X) && _LeftRayCast.distance <= 1.5f && !AttackCooldown())         {             _MinionScript = _LeftRayCast.collider.gameObject.GetComponent<MinionScript>();             _MinionScript.DamageDealt(_damageDealt);             Cooldown = 0;             return 2;         }          return 0;     }      private int MoveRight(float _moveSpeed)     {         if (Input.GetKey(KeyCode.RightArrow) && Defend() == 0)         {             transform.Translate(_moveSpeed, 0, 0);             _IsFacingForward = true;             return 1;         }          return 0;     }      private int MoveLeft(float _moveSpeed)     {         if (Input.GetKey(KeyCode.LeftArrow) && Defend() == 0)         {             transform.Translate(-_moveSpeed, 0, 0);             _IsFacingForward = false;             return 1;         }          return 0;     }      private int Jump(float _height)     {         _GroundDetector = Physics2D.Raycast(transform.position, Vector2.down);          if (Input.GetKeyDown(KeyCode.Z) && _IsGrounded)         {             _RigidBody.AddForce(Vector2.up * _height, ForceMode2D.Impulse);             return 1;         }          if (_GroundDetector.distance > 0.6f)         {             _IsGrounded = false;             return 2;         }          _IsGrounded = true;         return 0;     }      private int Evade(float _evadeSpeed)     {         if (Input.GetKeyDown(KeyCode.Space) && _IsGrounded)             switch (DistanceFromObject())             {                 case 1:                     _RigidBody.AddForce(Vector2.up * _evadeSpeed, ForceMode2D.Impulse);                     _RigidBody.AddForce(Vector2.left * _evadeSpeed, ForceMode2D.Impulse);                     return 1;                  case 2:                     _RigidBody.AddForce(Vector2.up * _evadeSpeed, ForceMode2D.Impulse);                     _RigidBody.AddForce(Vector2.right * _evadeSpeed, ForceMode2D.Impulse);                     return 2;                  case 3:                     _RigidBody.AddForce(Vector2.up * _evadeSpeed * 3, ForceMode2D.Impulse);                     return 3;             }          return 0;     }      private int Defend()     {         if (Input.GetKey(KeyCode.Space) && _IsGrounded)         {             DefendCooldownTimer += Time.deltaTime;             if (DefendCooldownTimer >= 0.5f)             {                 return 1;             }         }         else             DefendCooldownTimer = 0f;          return 0;     } } } 

User class: Getting user data, Loggin in, secure CSRF session handling, Logout – A class working example followed by a re-write attempt

I wrote this class a few months ago and noticed from a few examples that it’s better to break down these classes and separate them. I am not so sure what is the proper way to break if to parts.

It currently includes a creation of a System_user obj based on user id (fetching user data), login validation, logout, storing user data to session(more specifically CSRF), and I think that’s all..

This is my working code:

<?php namespace MyApp\Models;  use \Exception; use MyApp\Core\Database; use MyApp\Core\Config; use MyApp\Helpers\Session; use MyApp\Helpers\Cookie; use MyApp\Helpers\Token; use MyApp\Helpers\General; use MyApp\Helpers\Hash;    /**  *  *  System User Class  *  */ class System_user {  /*================================= =            Variables            = =================================*/      # @object database Database instance      private $  db;      # Users data     private $  data;      # User user ID name     public $  user_id;      # User first name     public $  first_name;      # User last name     public $  last_name;      # Username     public $  user_name;      # User Email       public $  email;      # User Last logged in       public $  last_login;      # is user logged in     public $  isLoggedIn;      # is user logged in     public $  login_timestamp;      # is user IP     private $  user_ip;   /*=============================== =            Methods            = ================================*/      /**      *      *  Construct      *      */     public function __construct($  system_user = NULL)     {         # Get database instance         $  this->db           = Database::getInstance();          # If system_user isn't passed as a variable          if ( !$  system_user ) {              # ...so check if there is a session user id set              if (Session::exists(Config::$  session_name)) {                  # Insert session data to system_user variable                 $  system_user = Session::get(Config::$  session_name);                  # Get user data                 $  this->find($  system_user);             }          } else {             $  this->find($  system_user);         }     }       /**      *      *  Find method: Find user by id or by username       *  @param      $  user   String/Init     A username or user ID      *      */     public function find($  system_user = NULL)     {         if ($  system_user) {              // Enable search for a system_user by a string name or if numeric - so by id.              $  field  = ( is_numeric($  system_user) ) ? 'system_user_id' : 'uname';              // Search for the system_user in the Database 'system_users' table.              $  data   = $  this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$  field} = :sys_user", array('sys_user' => $  system_user));              // If there is a result             if ( $  data ) {                 // Set data                  $  this->setUserData($  data);                  return $  this;             } else {                 return false;             }         }         else{             return false;         }     }       /**      *      *  Check if user exist in 'system_users' table      *  @param      $  username       String              Get a username user input      *  @param      $  password       String              Get a password user input      *  @throws                     Array/Boolian       Is this a signed System user?      *      */     private function system_user_login_validation($  username, $  password)     {         $  user_data = $  this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' => $  username, 'password' => sha1($  password)));          if ($  user_data)             return $  user_data;          else             return false;      }       /**      *      *  Login method      *  @param      $  customer_name  String      Get a customer_name user input      *  @param      $  username       String      Get a username user input      *  @param      $  password       String      Get a password user input      *  @throws                     Boolian     Is this a signed System user?      *      */     public function login($  customer_name, $  username, $  password)     {          # Create a Customer Obj         $  customer = new \MyApp\Models\Customer($  customer_name);          try {             # Check if the result is an array             # OR there is no row result:              if ( (!isset($  customer)) || (!isset($  customer->dbName)) || (!isset($  customer->host)) )                 throw new \MyApp\Core\Exception\Handler\LoginException("Bad company name: {$  customer_name}");             # Change localhost string to 127.0.0.1 (prevent dns lookup)            $  customer->host = ($  customer->host === 'localhost') ? '127.0.0.1' : $  customer->host;              # Connect to new database             $  new_connection = $  this->db->customer_connect($  customer->host, $  customer->dbName);              # If status is connected              if ($  new_connection) {                  # Check for user credentials data                  $  user_data = $  this->system_user_login_validation($  username, $  password);                   # If the result isn't a valid array - EXEPTION                   if ( (!is_array($  user_data)) || (empty($  user_data)) )                     throw new \MyApp\Core\Exception\Handler\LoginException("Customer: '{$  customer_name}' - Invalid username ({$  username}) or password ({$  password})");                  # Store Customer in the sesison                 Session::put(Config::$  customer, serialize($  customer));                  # Update host and db for the db object                 # $  this->db->update_host_and_db($  customer->host, $  customer->dbName);                  # Set data for this System_user object                 $  this->setUserData($  user_data);                  # Set a login session for the user id:                  Session::put(Config::$  session_name, $  this->user_id);                  # Set logged in user sessions                 $  this->set_loggedin_user_sessions();                  return $  this;              } else {                 # Connect back to backoffice (current db set)                 $  this->db->connect_to_current_set_db();                 throw new \MyApp\Core\Exception\Handler\LoginException('User does not exist');                 return false;             }          } catch (\MyApp\Core\Exception\Handler\LoginException $  e) {             $  e->log($  e);             return false;             // die(General::toJson(array( 'status' => false, 'message' => 'Bad login credentials.' )));         }     }       /**      *      *  Set sessions for the logged in user.       *  Tutorial: http://forums.devshed.com/php-faqs-stickies/953373-php-sessions-secure-post2921620.html      *        */     public function set_loggedin_user_sessions()     {         # Generate security sessions         $  this->generate_security_sessions();          # Set login timestamp          Session::put(Config::$  login_timestamp, $  this->login_timestamp);          # Set login flag to true         Session::put(Config::$  is_logged_in, true);          # Set login IP          Session::put(Config::$  login_user_ip, $  this->user_ip);     }       /**      *      *  Generate system user security sessions      *  @param      $  new_session        Boolean         (optinal) Dedices if to delete the cookie session id [default is set to true]      *      */     public function generate_security_sessions($  new_session = true)     {         if ($  new_session)             # Generate a new session ID             session_regenerate_id(true);          # Fetch cookie session ID          $  session_id = session_id();         # Set the session id to the session         Session::put(Config::$  session_id, $  session_id);          # Create a secret token          # Set it in session (does them both)         $  secret     = Token::generate_login_token();          # Combine secret and session_id and create a hash         $  combined   = Hash::make_from_array(array($  secret, $  session_id, $  this->user_ip));         # Add combined to session         Session::put(Config::$  combined, $  combined);     }       /**      *      *  Check if there is a logged in user      *      */     public function check_logged_in()     {         if ( Session::exists(Config::$  secret)       &&  # Secret session exists              Session::exists(Config::$  session_id)   &&  # Session_id session exists              Session::exists(Config::$  session_name) &&  # User session exists               Session::exists(Config::$  is_logged_in) &&  # Check if 'logged in' session exists              Session::exists(Config::$  session_name)     # Check if sys_user id is set in session             )         {             # Get users ip             $  ip = $  this->get_system_user_ip();              # if the saved bombined session              if (                   (Session::get(Config::$  combined) === Hash::make_from_array(array(Session::get(Config::$  secret), session_id()), $  ip)) &&                   (Session::get(Config::$  is_logged_in) === true )                  )             {                 # Set ip to system user object                 $  this->user_ip = $  ip;                  return true;              } else {                 return false;             }         }         else {             return false;          }     }       /**      *      *  Check if loggin session is timeout      *      */     public function check_timeout()     {         if (Session::exists(Config::$  login_timestamp)){              # Calculate time              $  session_lifetime_seconds = time() - Session::get(Config::$  login_timestamp) ;               if ($  session_lifetime_seconds > Config::MAX_TIME){                 $  this->logout();                 return true;             } else {                 return false;             }          } else {             $  this->logout();             return false;         }     }       /**      *      *  Get user IP       *      */     private function get_system_user_ip()     {         if (!empty($  _SERVER['HTTP_CLIENT_IP']))             $  ip = $  _SERVER['HTTP_CLIENT_IP'];         elseif (!empty($  _SERVER['HTTP_X_FORWARDED_FOR']))              $  ip = $  _SERVER['HTTP_X_FORWARDED_FOR'];         else             $  ip = $  _SERVER['REMOTE_ADDR'];          return $  ip;     }       /**      *      *  Set User data to (this) System_user object      *  @param      $  user_data      Array   User data fetched from the db (usually by the find method)      *      */     private function setUserData($  user_data)      {         // Set data for this user object         $  this->user_id              = $  user_data['system_user_id'];         $  this->first_name           = $  user_data['fname'];         $  this->last_name            = $  user_data['lname'];         $  this->user_name            = $  user_data['uname'];         $  this->email                = $  user_data['email'];         $  this->last_login           = $  user_data['last_login'];          $  this->isLoggedIn           = true;         $  this->user_ip              = $  this->get_system_user_ip();         $  this->login_timestamp      = time();     }       /**      *      *  Logout: Now guess what this method does..       *      */     public function logout()     {         $  this->isLoggedIn   = false;         Cookie::eat_cookies();         Session::kill_session();         session_destroy();         session_write_close();     }  } 

I would like to get suggestions about my current code, and if possible, about structuring it differently with more than one class. (class SystemUser, class systemUserLogin, class systemUserAuthenticator, ect’)

ps: In general, the webapp by default logs in to a general database. when a user inserts his company_name, username and password, I check if the company name actually exist, if if does, I disconnect from the general db and connect to the customers database and validate his username & password.

This is the new class I started writing (not tested, so I cant assure this is a working code) with more classes following this example & inspired by this post I found, while tring to follow the SOLID principals and PSR standards, focusing on the structure and architecture.

<?php namespace MyApp\Models;  use MyApp\Core\Config; use MyApp\Helpers\Session; use \Exception; use MyApp\Core\Database; use MyApp\Helpers\Cookie; use MyApp\Helpers\Token; use MyApp\Helpers\General; use MyApp\Helpers\Hash;    /**  *  *  System User Class  *  */ class SystemUser {  /*================================= =            Variables            = =================================*/      # @obj SystemUser profile information (fullname, profile picture... etc')     protected $  systemUserDetatils;     # @obj SystemUser Login data     protected $  systemUserLogin;     # @obj SystemUser Authenticator     protected $  systemUserAuthenticator;   /*=============================== =            Methods            = ================================*/       /**      *      *  Construct      *      */     public function __construct($  systemUserId = NULL)     {         # If system_user passed         if ( $  systemUserId ) {              # Create systemUserDedatils obj             $  this->systemUserDetatils = new MyApp\Models\SystemUser\SystemUserDetatils();              # Get SysUser data             $  this->systemUserDetatils->get($  systemUserId);          } else {              # Check for sysUser id in the session:             $  systemUserId = $  this->systemUserDetatils->getUserFromSession();              # Get user data from session              if ( $  systemUserId ) {                  # Create systemUserDedatils obj                 $  this->systemUserDetatils = new MyApp\Models\SystemUser\SystemUserDetatils();                  # Get SysUser data                 $  this->systemUserDetatils->get($  systemUserId);             }         }     }       /**      *      *  Set Login: Sets the SystemUserLogin object to $  systemUserLogin variable       *  @param     $  _systemUserLogin   SystemUserLogin     Gets a SystemUserLogin object      *      */     public function setSystemUserLogin(SystemUserLogin $  _systemUserLogin)     {         $  this->systemUserLogin = $  _systemUserLogin;      }       /**      *      *  Login       *      */     public function login()     {         $  this->systemUserAuthenticator($  this);     }   }         <?php  namespace MyApp\Models\SystemUser;  use MyApp\Core\Config; use MyApp\Helpers\Session;  /**  *  *  System User Details Class  *  */ class SystemUserDetails  {  /*================================= =            Variables            = =================================*/      # @object database Database instance      private $  db;      # Users data     private $  data;      # User user ID name     public $  userId;      # User first name     public $  firstName;      # User last name     public $  lastName;      # Username     public $  userName;      # User Email       public $  email;      # User Last logged in       public $  lastLogin;      /*# is user logged in     public $  isLoggedIn;      # is user logged in     public $  login_timestamp;*/      # is user IP     private $  user_ip;   /*=============================== =            Methods            = ================================*/      /**      *      *  Construct      *      */     public function __construct()     {         # Get database instance         $  this->db           = Database::getInstance();     }       /**      *      *  Find method: Find user by id or by username       *  @param      $  user   String / Init     A username or user ID      *  @return       *      */     public function get(Int $  systemUserId)     {         if ($  systemUserId) {              # Enable search for a system_user by a string name or if numeric - so by id.              $  field  = ( is_numeric($  systemUserId) ) ? 'system_user_id' : 'uname';              # Search for the system_user in the Database 'system_users' table.              $  data   = $  this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$  field} = :sys_user", array('sys_user' => $  systemUserId));              # If there is a result             if ( $  data ) {                  # Set data                  $  this->setUserData($  data);                  return $  this;             } else {                 return false;             }         }         else {             return false;         }     }       /**      *      *  Set User data to $  this obj      *  @param      $  userData       Array   User data fetched from the db (usually by the find method)      *  @return        *      */     public function set(Array $  userData)     {         // Set data for this user object         $  this->userId               = $  userData['system_user_id'];         $  this->firstName            = $  userData['fname'];         $  this->lastName             = $  userData['lname'];         $  this->userName             = $  userData['uname'];         $  this->email                = $  userData['email'];         $  this->lastLogin            = $  userData['last_login'];     }       /**      *      *  Get User from session      *  @param       *  @return       *      */     public function getUserFromSession()     {         # Check if there is a session user id set          if (Session::exists(Config::$  session_name)) {              # Insert session data to system_user variable             return Session::get(Config::$  session_name);          } else {             # Returning false cause there is no user id session             return false;          }     } }      <?php  namespace MyApp\Models\SystemUser;   /**  *  *  System User Details Class  *  */ class systemUserLogin  {  /*================================= =            Variables            = =================================*/      # @str Customer name      public $  customerName;      # @str UserName     public $  userName;      # @str Password     public $  password;      # @str user IP     public $  userIp;   /*=============================== =            Methods            = ================================*/       /**      *      *  Construct - Set customer, username and password      *  @param      $  _customerName      String      *  @param      $  _userName          String      *  @param      $  _password          String      *      */     public function __construct(String $  _customerName, String $  _userName, String $  _password)     {         $  this->customerName = $  _customerName;         $  this->userName     = $  _userName;         $  this->password     = $  _password;         $  this->userIp       = $  this->getSystemUserIp();     }       /**      *      *  Get user IP       *  @return     String      Returns the user IP that is trying to connect.       *      */     private function getSystemUserIp()     {         if (!empty($  _SERVER['HTTP_CLIENT_IP']))             $  ip = $  _SERVER['HTTP_CLIENT_IP'];         elseif (!empty($  _SERVER['HTTP_X_FORWARDED_FOR']))              $  ip = $  _SERVER['HTTP_X_FORWARDED_FOR'];         else             $  ip = $  _SERVER['REMOTE_ADDR'];          return $  ip;     }  }      <?php  namespace MyApp\Models\SystemUser;   /**  *  *  System User Details Class  *  */ class systemUserAuthenticator  {  /*================================= =            Variables            = =================================*/      # @object Database instance      private $  db;      # @bool Is logged in     public $  isLoggedIn = false;      # @str Login Timestamp      public $  loginTimestamp;   /*=============================== =            Methods            = ================================*/       /**      *      *  Construct      *      */     public function __construct()     {         # Get database instance         $  this->db           = Database::getInstance();     }       /**      *      *  Login method      *  @param      $  customer_name  String      Get a customer_name user input      *  @param      $  username       String      Get a username user input      *  @param      $  password       String      Get a password user input      *  @throws                     Boolian     Is this a signed System user?      *      */     public function login(User $  user)     {         # Create a Customer Obj         $  customer = new \MyApp\Models\Customer($  user->SystemUserLogin->customerName);          try {             # Check if the result is an array             # OR there is no row result:              if ( (!isset($  customer)) || (!isset($  customer->dbName)) || (!isset($  customer->host)) )                 throw new \MyApp\Core\Exception\Handler\LoginException("Bad company name: {$  user->SystemUserLogin->customerName}");             # Change localhost string to 127.0.0.1 (prevent dns lookup)            $  customer->host = ($  customer->host === 'localhost') ? '127.0.0.1' : $  customer->host;              # Connect to new database             $  new_connection = $  this->db->customer_connect($  customer->host, $  customer->dbName);              # If status is connected              if ($  new_connection) {                  # Check for user credentials data                  $  user_data = $  this->system_user_login_validation($  user->SystemUserLogin->userName, $  user->SystemUserLogin->password);                   # If the result isn't a valid array - EXEPTION                   if ( (!is_array($  user_data)) || (empty($  user_data)) )                     throw new \MyApp\Core\Exception\Handler\LoginException("Customer: '{$  user->SystemUserLogin->customerName}' - Invalid username ({$  user->SystemUserLogin->userName}) or password ({$  user->SystemUserLogin->password})");                  # Store Customer in the sesison                 Session::put(Config::$  customer, serialize($  customer));                  # Update host and db for the db object                 # $  this->db->update_host_and_db($  customer->host, $  customer->dbName);                  # Set data for this System_user object                 $  this->setUserData($  user_data);                  # Set a login session for the user id:                  Session::put(Config::$  session_name, $  this->user_id);                  # Set logged in user sessions                 $  this->set_loggedin_user_sessions();                  return $  this;              } else {                 # Connect back to backoffice (current db set)                 $  this->db->connect_to_current_set_db();                 throw new \MyApp\Core\Exception\Handler\LoginException('User does not exist');                 return false;             }          } catch (\MyApp\Core\Exception\Handler\LoginException $  e) {             $  e->log($  e);             return false;             // die(General::toJson(array( 'status' => false, 'message' => 'Bad login credentials.' )));         }     }       /**      *      *  Check if user exist in 'system_users' table      *  @param      $  username       String              Get a username user input      *  @param      $  password       String              Get a password user input      *  @throws                     Array/Boolian       Is this a signed System user?      *      */     private function systemUserLoginValidation($  username, $  password)     {         $  userData = $  this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' => $  username, 'password' => sha1($  password)));          if ($  userData)             return $  userData;         else             return false;      }     } 

June 13th 2017 Microsoft blocked handling HTML markup in SharePoint calculated fields – how to get the same functionality back

On June 13th 2017 all SharePoint calculated columns with HTML markup stopped working.

Basically the fields now render text (regardless of setting the data type to number). The gist of the notice from Microsoft (Handling HTML markup in SharePoint calculated fields) is:

In Microsoft SharePoint lists and libraries, calculated fields that are running in the classic UI mode can be used to display results based on Excel-like formulas. This is a long standing capability, and is documented in Calculate data in lists or libraries.

Some users have added HTML markup or script elements to calculated fields. This is an undocumented use of the feature, and we will begin blocking execution of custom markup in calculated fields in SharePoint Online from June 13, 2017 onwards. We are also providing this as a configurable option for on-premises in SharePoint Server 2016 and SharePoint Server 2013 via the June 2017 and subsequent Public Updates.

As we don’t have on premise SharePoint (online), we have to find an immediate work around, given that this impacts our processes and thus, business.

Is anyone aware of third party applications that will allow for HTML, script markup (that works with SP online)?

Handling Dropdown conditional Dropdowns

I’m working on a material design web-app designed for a mobile/touch environment.

Naturally I’m very pushed for space and would like to know what the best-practice is for conditionally providing a sub-set of options.

I don’t really like the idea of showing two selects only when the appropriate option is selected

Example:

  • Option 01
  • Option 02
  • Option 03
  • Option 04
  • Option 05 (only this has the “sub-options” i.e. [sub1, sub2, sub3, sub4, sub5]).

example dropdown

more info about the context: these are a sort of preferences …options in this case are different kinds of visualizations but the option number five has a more detailed visualization divided by areas

(tnx cyberspark I don’t know how to thank you for edit)

Java design pattern for handling configuration options and responding to changes in them

I’m working on an overlay/HUD for a Java game, where the user should be able to enable or disable certain components and choose configuration options. One such example is a health bar, which the user can choose to either enable or disable and choose its size and color.

What would be a good design to handle this kind of scenario in Java? I’m particularly wondering how I should handle changes in configuration options, so that all HUD components could follow the same logic.