﻿<?xml version="1.0"?>
<AlvaoApplication xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ModelVersion="1">
  <Applications>
    <Application id="31">
      <Name>CheckPhoneNumberFormat</Name>
      <Description>Check the format of the new Phone Number property value.</Description>
      <Scripts>
        <Script id="59">
          <Name>CheckPhoneNumberFormat</Name>
          <Code>using System;
using System.Data;
using Microsoft.Data.SqlClient;
using Alvao.Apps.API;
using Dapper;

class ObjectPropertyAutoAction : IObjectPropertyAutoAction
{
    public Tuple&lt;bool, string&gt; OnObjectPropertyModifying(SqlConnection con, int propertyId, int personId, string newValue)
    {
        // Is the Phone Number being edited?
        Settings.isPhoneNumber = con.QueryFirstOrDefault&lt;bool&gt;(@"
            select 1
            from tblProperty p
            join tblKind k on k.intKindId = p.lintKindId
            where p.intPropertyId=@propertyId and k.txtName=@propName",
            new { propertyId, propName = Settings.propName });
        
        if (!Settings.isPhoneNumber)
        {
            return Tuple.Create(true, (string)null);
        }

        // Value was empty.
        if (string.IsNullOrEmpty(newValue))
        {
            return Tuple.Create(true, (string)null);
        }

        // Check formatting.
        var matches = Settings.rx.Matches(newValue);
   
        if (matches.Count == 0)
        {
            return Tuple.Create(false, Settings.errorMessage);
        }

        // The number was entered in a valid format.
        return Tuple.Create(true, (string)null);
    }

    public void OnObjectPropertyModified(SqlConnection con, int propertyId, int personId)
    {
        throw new NotImplementedException();
    }
}</Code>
          <IsLibCode>false</IsLibCode>
        </Script>
        <Script id="61">
          <Name>Settings</Name>
          <Code>
using System.Text.RegularExpressions;

public class Settings 
{
    /*
     * The action to check the format of the new Phone Number property value.
     */

    public static readonly string propName = "Phone Number"; // Specify the property name you want to check.
    public static readonly Regex rx = new Regex(@"^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$", RegexOptions.Compiled | RegexOptions.IgnoreCase); // Phone number format in regex.
    public static readonly string errorMessage = "The value you entered is not a phone number. Enter the phone number in the correct format, etc. +(039) 123 456 789."; // Error message if the new value is not in correct format.

    // Do not change this value.
    public static bool isPhoneNumber = false; 
}</Code>
          <IsLibCode>true</IsLibCode>
        </Script>
      </Scripts>
    </Application>
  </Applications>
</AlvaoApplication>