Ejemplo n.º 1
0
        /// <summary>
        /// Checks the status of a Verify transaction. When the code is
        /// supplied it verifies this code. The response also contains
        /// status information about the progress of the call or sms.
        /// </summary>
        /// <param name="referenceId">
        /// The reference id return in the VerifyResponse from
        /// a call to Sms or Call.
        /// </param>
        /// <param name="verifyCode">The code the user provided you to be verified.</param>
        /// <returns>
        /// A VerifyResponse object containing information about the status
        /// of the transactation and validity of the code.
        /// </returns>
        public string StatusRaw(
            string referenceId,
            string verifyCode = null)
        {
            CheckArgument.NotNullOrEmpty(referenceId, "referenceId");

            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("referenceId", referenceId);

            if (!string.IsNullOrEmpty(verifyCode))
            {
                args.Add("verify_code", verifyCode.ToString());
            }

            string resourceName = string.Format(
                RawVerifyService.VerifyResourceFormatString,
                referenceId);

            WebRequest request = this.ConstructWebRequest(
                resourceName,
                "GET",
                args);

            return(this.WebRequester.ReadResponseAsString(request));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// URL encode a string
        /// </summary>
        /// <param name="input">String to be URL encoded</param>
        /// <returns>Byte array</returns>
        public static string UrlEncode(string input)
        {
            CheckArgument.NotNull("input", input);

            const int maxLength = 32766;

            if (input.Length <= maxLength)
            {
                return(Uri.EscapeDataString(input));
            }

            StringBuilder sb    = new StringBuilder(input.Length * 2);
            int           index = 0;

            while (index < input.Length)
            {
                int    length    = Math.Min(input.Length - index, maxLength);
                string subString = input.Substring(index, length);

                sb.Append(Uri.EscapeDataString(subString));
                index += subString.Length;
            }

            return(sb.ToString());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Validates whether a verifyCode is valid to use with the TeleSign API.
        /// Null is valid and indicates the API should generate the code itself,
        /// empty strings are not valid, any non-digit characters are not valid
        /// and leading zeros are not valid.
        /// </summary>
        /// <param name="verifyCode">The code to verify.</param>
        public virtual void ValidateCodeFormat(string verifyCode)
        {
            if (verifyCode == null)
            {
                // When the code is null we generate it, so this is valid.
                return;
            }

            // Empty code is never valid
            CheckArgument.NotEmpty(verifyCode, "verifyCode");

            // Leading zeros are not allowed.
            if (verifyCode[0] == '0')
            {
                string message = string.Format(
                    "Verify code '{0}' must not have leading zeroes.",
                    verifyCode);

                throw new ArgumentException(message);
            }

            foreach (char c in verifyCode)
            {
                // Only decimal digits are allowed 0-9.
                if (!Char.IsDigit(c))
                {
                    string message = string.Format(
                        "Verify code '{0}' must only contain decimal digits [0-9]",
                        verifyCode);

                    throw new ArgumentException(message);
                }
            }
        }
Ejemplo n.º 4
0
 public void TestNotNullOrEmptyThrowsWhenPassedEmptyString()
 {
     Assert.Throws <ArgumentException>(delegate
     {
         CheckArgument.NotNullOrEmpty(string.Empty, "value");
     });
 }
Ejemplo n.º 5
0
 public void TestNotNullOrEmptyThrowsWhenPassedNull()
 {
     Assert.Throws <ArgumentNullException>(delegate
     {
         CheckArgument.NotNullOrEmpty(null, "value");
     });
 }
Ejemplo n.º 6
0
 public void TestNotNullOrEmptyStillWorksWhenNameIsNull()
 {
     Assert.Throws <ArgumentException>(delegate
     {
         CheckArgument.NotNullOrEmpty(string.Empty, null);
     });
 }
Ejemplo n.º 7
0
        public static void SendSms(string[] args)
        {
            CheckArgument.ArrayLengthAtLeast(args, 1, "args");

            string phoneNumber = args[0];

            string code = null;

            if (args.Length >= 2)
            {
                code = args[1];
            }

            string language = "en";

            if (args.Length >= 3)
            {
                language = args[2];
            }

            try
            {
                VerifyService  verify         = new VerifyService(GetConfiguration());
                VerifyResponse verifyResponse = null;
                verifyResponse = verify.SendSms(phoneNumber, code, string.Empty, language);
                Console.WriteLine("Sent sms");
            }
            catch (Exception x)
            {
                Console.WriteLine("Error: " + x.ToString());
            }
        }
Ejemplo n.º 8
0
        /////// <summary>
        /////// The TeleSign Verify Soft Token web service is a server-side component of the TeleSign AuthID application, and it allows you to authenticate your end users when they use the TeleSign AuthID application on their mobile device to generate a Time-based One-time Password (TOTP) verification code
        /////// </summary>
        /////// <param name="phoneNumber">The phone number for the Verify Soft Token request, including country code</param>
        /////// <param name="softTokenId">
        /////// The alphanumeric string that uniquely identifies your TeleSign soft token subscription
        /////// </param>
        /////// <param name="verifyCode">
        /////// The verification code received from the end user
        /////// </param>
        /////// <returns>The raw JSON response from the REST API.</returns>
        ////public string SoftTokenRaw(
        ////            string phoneNumber,
        ////            string softTokenId = null,
        ////            string verifyCode = null)
        ////{
        ////    phoneNumber = this.CleanupPhoneNumber(phoneNumber);

        ////    if (softTokenId == null)
        ////    {
        ////        softTokenId = string.Empty;
        ////    }

        ////    if (verifyCode == null)
        ////    {
        ////        verifyCode = string.Empty;
        ////    }

        ////    Dictionary<string, string> args = ConstructVerifyArgs(
        ////                VerificationMethod.SoftToken,
        ////                phoneNumber,
        ////                softTokenId,
        ////                verifyCode);

        ////    string resourceName = string.Format(
        ////                RawVerifyService.VerifyResourceFormatString,
        ////                VerificationMethod.SoftToken.ToString().ToLowerInvariant());

        ////    WebRequest request = this.ConstructWebMobileRequest(
        ////                resourceName,
        ////                "POST",
        ////                args);

        ////    return this.WebRequester.ReadResponseAsString(request);
        ////}

        /// <summary>
        /// The TeleSign Verify 2-Way SMS web service allows you to authenticate your users and verify user transactions via two-way Short Message Service (SMS) wireless communication. Verification requests are sent to user’s in a text message, and users return their verification responses by replying to the text message.
        /// </summary>
        /// <param name="phoneNumber">The phone number for the Verify Soft Token request, including country code</param>
        /// <param name="message">
        /// The text to display in the body of the text message. You must include the $$CODE$$ placeholder for the verification code somewhere in your message text. TeleSign automatically replaces it with a randomly-generated verification code
        /// </param>
        /// <param name="validityPeriod">
        /// This parameter allows you to place a time-limit on the verification. This provides an extra level of security by restricting the amount of time your end user has to respond (after which, TeleSign automatically rejects their response). Values are expressed as a natural number followed by a lower-case letter that represents the unit of measure. You can use 's' for seconds, 'm' for minutes, 'h' for hours, and 'd' for days
        /// </param>
        /// <param name="useCaseId"></param>
        /// <returns>The raw JSON response from the REST API.</returns>
        public string TwoWaySmsRaw(
            string phoneNumber,
            string message,
            string validityPeriod = "5m",
            string useCaseId      = RawVerifyService.DefaultUseCaseId)
        {
            CheckArgument.NotEmpty(message, "message");
            CheckArgument.NotNullOrEmpty(validityPeriod, "validityPeriod");

            phoneNumber = this.CleanupPhoneNumber(phoneNumber);

            Dictionary <string, string> args = ConstructVerifyArgs(
                VerificationMethod.TwoWaySms,
                phoneNumber,
                null,
                message,
                null,
                validityPeriod,
                useCaseId);

            string resourceName = string.Format(
                RawVerifyService.VerifyResourceFormatString,
                "two_way_sms");

            WebRequest request = this.ConstructWebRequest(
                resourceName,
                "POST",
                args);

            return(this.WebRequester.ReadResponseAsString(request));
        }
Ejemplo n.º 9
0
 public void TestNotNullStillWorksWhenNameIsNull()
 {
     Assert.Throws <ArgumentNullException>(delegate
     {
         CheckArgument.NotNull(null, null);
     });
 }
Ejemplo n.º 10
0
        public void CreateOneWalletOperation(int personId, int walletId, int operationCategoryId, decimal balance, string description, DateTime?date)
        {
            CheckArgument.CheckForNull(description, nameof(description));

            Person person = this.UnitOfWork.PersonRepository.GetById(personId)
                            ?? throw new InvalidForeignKeyException(typeof(Person).Name);

            Wallet wallet = this.UnitOfWork.WalletRepository.GetById(walletId)
                            ?? throw new InvalidForeignKeyException(typeof(Wallet).Name);

            OperationCategory operationCategory = this.UnitOfWork.OperationCategoryRepository.GetById(operationCategoryId)
                                                  ?? throw new InvalidForeignKeyException(typeof(OperationCategory).Name);

            PersonWallet personWallet = this.UnitOfWork.PersonWalletRepository.GetPersonWalletByPersonAndWallet(personId, walletId)
                                        ?? throw new InvalidPropertyException(typeof(PersonWallet).Name);

            wallet.Balance = balanceCalculator.CountNewWalletBalance(wallet.Balance, balance, operationCategory.Type);
            this.UnitOfWork.WalletRepository.Update(wallet);

            OperationInfo operationInfo = new OperationInfo()
            {
                Balance = balance, Description = description, Date = date ?? DateTime.Now
            };

            this.UnitOfWork.OperationInfoRepository.Add(operationInfo);

            Operation operation = new Operation()
            {
                OperationCategoryID = operationCategory.ID, OperationInfoID = operationInfo.ID, PersonWalletID = personWallet.ID
            };

            this.GetRepository().Add(operation);
            this.UnitOfWork.SaveChanges();
        }
Ejemplo n.º 11
0
        public static void PhoneIdStandard(string[] args)
        {
            CheckArgument.ArrayLengthIs(args, 1, "args");
            string phoneNumber = args[0];

            PhoneIdService          service  = new PhoneIdService(GetConfiguration());
            PhoneIdStandardResponse response = service.StandardLookup(phoneNumber);
        }
Ejemplo n.º 12
0
        private void ThrowIfNeeded(string json)
        {
            CheckArgument.NotNull(json, "json");

            if (this.ExpectedException != null)
            {
                throw this.ExpectedException;
            }
        }
Ejemplo n.º 13
0
        public void GreaterThanZero_CalledWithZeroOrLess_ThrowsArgumentException(double arg)
        {
            // Act
            Action act = () => CheckArgument.GreaterThanZero(arg, nameof(arg));

            // Assert
            act.Should().Throw <ArgumentException>()
            .WithMessage("Argument 'arg' should be greater than '0'.");
        }
Ejemplo n.º 14
0
        public static void RawPhoneIdLive(string[] args)
        {
            CheckArgument.ArrayLengthIs(args, 1, "args");
            string phoneNumber = args[0];

            RawPhoneIdService service      = new RawPhoneIdService(GetConfiguration());
            string            jsonResponse = service.LiveLookupRaw(phoneNumber);

            Console.WriteLine(jsonResponse);
        }
Ejemplo n.º 15
0
        public PersonController(IPersonService personService, IPersonRepository personRepository, IMapper mapper)
        {
            CheckArgument.CheckForNull(personService, nameof(personService));
            CheckArgument.CheckForNull(personRepository, nameof(personRepository));
            CheckArgument.CheckForNull(mapper, nameof(mapper));

            this.personService    = personService;
            this.personRepository = personRepository;
            this.mapper           = mapper;
        }
        public FamilyController(IFamilyService familyService, IUnitOfWork unitOfWork, IMapper mapper)
        {
            CheckArgument.CheckForNull(familyService, nameof(familyService));
            CheckArgument.CheckForNull(unitOfWork, nameof(unitOfWork));
            CheckArgument.CheckForNull(mapper, nameof(mapper));

            this.familyService = familyService;
            this.unitOfWork    = unitOfWork;
            this.mapper        = mapper;
        }
Ejemplo n.º 17
0
        public void GreaterThanZero_CalledWithGreaterThanZero_DoesNotThrowArgumentException()
        {
            // Arrange
            double arg = .1;

            // Act
            Action act = () => CheckArgument.GreaterThanZero(arg, nameof(arg));

            // Assert
            act.Should().NotThrow <ArgumentException>();
        }
Ejemplo n.º 18
0
        public static void PhoneIdScore(string[] args)
        {
            CheckArgument.ArrayLengthIs(args, 1, "args");
            string phoneNumber = args[0];

            PhoneIdService       service  = new PhoneIdService(GetConfiguration());
            PhoneIdScoreResponse response = service.ScoreLookup(phoneNumber);

            Console.WriteLine("Phone Number: {0}", phoneNumber);
            Console.WriteLine("Risk        : {0} [{1}] - Recommend {2}", response.Risk.Level, response.Risk.Score, response.Risk.Recommendation);
        }
        public void Update(int id, string name)
        {
            CheckArgument.CheckForNull(name, nameof(name));

            Family family = this.GetRepository().GetById(id)
                            ?? throw new InvalidPrimaryKeyException(typeof(Family).Name);

            family.Name = name;
            this.GetRepository().Update(family);
            this.UnitOfWork.SaveChanges();
        }
Ejemplo n.º 20
0
        public void NotNull_CalledWithNotNull_DoesNotThrowArgumentNullException()
        {
            // Arrange
            object arg = new object();

            // Act
            Action act = () => CheckArgument.NotNull(arg, nameof(arg));

            // Assert
            act.Should().NotThrow <ArgumentNullException>();
        }
        public void Create(string name, OperationType operationType)
        {
            CheckArgument.CheckForNull(name, nameof(name));

            OperationCategory operationCategory = new OperationCategory()
            {
                Name = name, Type = operationType
            };

            this.GetRepository().Add(operationCategory);
            this.UnitOfWork.SaveChanges();
        }
Ejemplo n.º 22
0
        public static void PhoneIdContact(string[] args)
        {
            CheckArgument.ArrayLengthIs(args, 1, "args");
            string phoneNumber = args[0];

            PhoneIdService         service  = new PhoneIdService(GetConfiguration());
            PhoneIdContactResponse response = service.ContactLookup(phoneNumber);

            Console.WriteLine("Phone Number: {0}", phoneNumber);
            Console.WriteLine("Name        : {0}", response.Contact.FullName);
            Console.WriteLine("Address     :\r\n{0}", response.Contact.GetFullAddress());
        }
Ejemplo n.º 23
0
        public void NotNull_CalledWithNull_ThrowsArgumentNullException()
        {
            // Arrange
            object arg = null;

            // Act
            Action act = () => CheckArgument.NotNull(arg, nameof(arg));

            // Assert
            act.Should().Throw <ArgumentNullException>()
            .WithMessage("*Argument 'arg' can not be 'null'.");
        }
Ejemplo n.º 24
0
        public void Rename(int id, string name)
        {
            CheckArgument.CheckForNull(name, nameof(name));

            Wallet wallet = this.GetRepository().GetById(id)
                            ?? throw new InvalidPrimaryKeyException(typeof(Wallet).Name);

            wallet.Name = name;

            this.GetRepository().Update(wallet);
            this.UnitOfWork.SaveChanges();
        }
        public void Create(string name, string surname)
        {
            CheckArgument.CheckForNull(name, nameof(name));
            CheckArgument.CheckForNull(surname, nameof(surname));

            Person person = new Person()
            {
                Name = name, Surname = surname
            };

            this.GetRepository().Add(person);
            this.UnitOfWork.SaveChanges();
        }
        /// <summary>
        /// Parses a TeleSign PhoneID Standard JSON response into a rich object.
        /// </summary>
        /// <param name="json">The json string containing the response.</param>
        /// <returns>A StandardPhoneIdResponse object populated with the data from the response.</returns>
        public PhoneIdStandardResponse ParsePhoneIdStandardResponse(string json)
        {
            CheckArgument.NotNull(json, "json");

            JObject node = JObject.Parse(json);

            PhoneIdStandardResponse response = new PhoneIdStandardResponse(json);

            this.PopulateCommonPhoneIdResponseFields(response, node);
            this.PopulateStatusResponseFields(response, node);
            this.PopulatePhoneIdStandardResponseFields(response, node);

            return(response);
        }
        /// <summary>
        /// Parses a TeleSign Verify JSON response into a rich object.
        /// </summary>
        /// <param name="json">The json string containing the response.</param>
        /// <returns>A VerifyResponse object populated with the data from the response.</returns>
        public VerifyResponse ParseVerifyResponse(string json)
        {
            CheckArgument.NotNull(json, "json");

            JObject node = JObject.Parse(json);

            VerifyResponse response = new VerifyResponse(json)
            {
                VerifyInfo = this.ParseVerifyInfo((JObject)node["verify"]),
            };

            this.PopulateStatusResponseFields(response, node);

            return(response);
        }
Ejemplo n.º 28
0
        public static void MapRegistrationLocation(string[] args)
        {
            CheckArgument.ArrayLengthIs(args, 1, "args");
            string phoneNumber = args[0];

            PhoneIdService          service  = new PhoneIdService(GetConfiguration());
            PhoneIdStandardResponse response = service.StandardLookup(phoneNumber);

            string url = string.Format(
                "http://maps.google.com/maps?q={0},{1}",
                response.Location.Coordinates.Latitude,
                response.Location.Coordinates.Longitude);

            Process.Start(url);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the Configuration class with different settings.
        /// </summary>
        /// <param name="basePath">The base API path.</param>
        /// <param name="applicationUserID">The ID of application user.</param>
        /// <param name="authenticationKey">The secret authentication key.</param>
        /// <param name="tempFolderPath">Temp folder path</param>
        /// <param name="timeout">HTTP connection timeout (in milliseconds)</param>
        /// <param name="userAgent">HTTP user agent</param>
        /// <param name="exceptionFactory">The factory of exceptions which are caused by service methods.</param>
        public Configuration(string basePath,
                             string applicationUserID,
                             string authenticationKey,
                             string tempFolderPath,
                             int timeout,
                             string userAgent,
                             ExceptionFactory exceptionFactory
                             )
        {
            _basePath          = CheckArgument.NotEmpty("basePath", basePath);
            _authenticationKey = CheckArgument.NotNull("authenticationKey", authenticationKey);
            _applicationUserID = CheckArgument.NotNull("applicationUserID", applicationUserID);
            _timeout           = timeout;
            _userAgent         = userAgent;

            if (!String.IsNullOrEmpty(tempFolderPath))
            {
                // check if the path contains directory separator at the end
                if (tempFolderPath[tempFolderPath.Length - 1] == Path.DirectorySeparatorChar)
                {
                    _tempFolderPath = tempFolderPath;
                }
                else
                {
                    _tempFolderPath = tempFolderPath + Path.DirectorySeparatorChar;
                }
            }
            else
            {
                _tempFolderPath = Path.GetTempPath();
            }

            // create the directory if it does not exist
            if (!Directory.Exists(_tempFolderPath))
            {
                Directory.CreateDirectory(_tempFolderPath);
            }

            if (exceptionFactory != null)
            {
                _exceptionFactory = exceptionFactory;
            }
            else
            {
                _exceptionFactory = DefaultExceptionFactory;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Checks the status of TeleSign Verify transaction. At the underlying REST
        /// API layer this is the same call as ValidateCode (to the Status resource)
        /// but without supplying the code. This is useful to check the progress
        /// of the SMS or call prior to the user responding with the code.
        /// </summary>
        /// <param name="referenceId">
        /// The reference id return in the VerifyResponse from
        /// a call to Sms or Call.
        /// </param>
        /// <returns>
        /// A VerifyResponse object containing information about the status
        /// of the transactation
        /// </returns>
        public VerifyResponse CheckStatus(string referenceId)
        {
            CheckArgument.NotNullOrEmpty(referenceId, "referenceId");

            string rawResponse = this.StatusRaw(referenceId);

            try
            {
                return(this.parser.ParseVerifyResponse(rawResponse));
            }
            catch (Exception x)
            {
                throw new ResponseParseException(
                          "Error parsing Verify code check status response",
                          rawResponse,
                          x);
            }
        }