Ejemplo n.º 1
0
 public void ResetProcessor()
 {
     OperationReset();
     FunctionReset();
     Lop_Res.Reset();
     Rop.Reset();
 }
Ejemplo n.º 2
0
        /// <summary>
        /// StrToRomanNumberWithError
        /// </summary>
        public static RopResult <RomanNumber, string> StrToRomanNumberWithError(string input)
        {
            var digitsWithErrs =
                input
                .ToCharArray()
                .Select(CharToRomanDigitWithError);
            var errors =
                digitsWithErrs
                .Where(r => !r.IsSuccess)
                .Select(r => r.FailureValues.First());

            if (errors.Any())
            {
                return(Rop.Fail <RomanNumber, string>(errors));
            }
            else
            {
                var digits =
                    digitsWithErrs
                    .Where(r => r.IsSuccess)
                    .Select(r => r.SuccessValue)
                    .ToList();
                var romanNumber = new RomanNumber(digits);
                return(Rop.Succeed <RomanNumber, string>(romanNumber));
            }
        }
Ejemplo n.º 3
0
        public void FunctionRun()
        {
            switch (Function)
            {
            case EFunction.Rev:
            {
                if (Rop.GetType().GetMethod("Rev")?.Invoke(Rop, null) == null)
                {
                    Rop = 1 / (dynamic)Rop;
                }
                else
                {
                    Rop = (T)Rop.GetType().GetMethod("Rev")?.Invoke(Rop, null);
                }
                break;
            }

            case EFunction.Sqr:
            {
                if (Rop.GetType().GetMethod("Sqr")?.Invoke(Rop, null) == null)
                {
                    Rop = (dynamic)Rop * (dynamic)Rop;
                }
                else
                {
                    Rop = (T)Rop.GetType().GetMethod("Sqr")?.Invoke(Rop, null);
                }
                break;
            }
            }
        }
        public static RopResult <String10, DomainMessage> CreateFirstName(string firstName)
        {
            var opt = String10.Create(firstName);

            return(Option.Match(
                       opt,
                       Rop.Succeed <String10, DomainMessage>,
                       () => Rop.Fail <String10, DomainMessage>(DomainMessage.FirstNameIsRequired())
                       ));
        }
Ejemplo n.º 5
0
        private static RopResult <SimpleRequest, string> ValidateRequest(SimpleRequest input)
        {
            var name50R        = Rop.Bind <SimpleRequest, SimpleRequest, string>(Name50);
            var emailNotBlankR = Rop.Bind <SimpleRequest, SimpleRequest, string>(EmailNotBlank);

            return(input
                   .Pipe(NameNotBlank) // the first one does not need to be bound
                   .Pipe(name50R)
                   .Pipe(emailNotBlankR));
        }
        public static RopResult <CustomerId, DomainMessage> CreateCustomerId(int customerId)
        {
            var opt = CustomerId.Create(customerId);

            return(Option.Match(
                       opt,
                       Rop.Succeed <CustomerId, DomainMessage>,
                       () => Rop.Fail <CustomerId, DomainMessage>(DomainMessage.CustomerIdMustBePositive())
                       ));
        }
Ejemplo n.º 7
0
 // log errors on the failure path
 private Func <RopResult <T, DomainMessage>, RopResult <T, DomainMessage> > LogFailureR <T>()
 {
     return(Rop.FailureTee <T, DomainMessage>(errors =>
     {
         foreach (var err in errors)
         {
             Log("Error: {0}", err);
         }
     }));
 }
        public static RopResult <EmailAddress, DomainMessage> CreateEmail(string email)
        {
            var opt = EmailAddress.Create(email);

            return(Option.Match(
                       opt,
                       Rop.Succeed <EmailAddress, DomainMessage>,
                       () => Rop.Fail <EmailAddress, DomainMessage>(DomainMessage.EmailIsRequired())
                       ));
        }
Ejemplo n.º 9
0
 private static RopResult <SimpleRequest, string> Name50(SimpleRequest input)
 {
     if (input.Name.Length > 50)
     {
         return(Rop.Fail <SimpleRequest, string>("Name must not be longer than 50 chars"));
     }
     else
     {
         return(Rop.Succeed <SimpleRequest, string>(input));
     }
 }
Ejemplo n.º 10
0
 private static RopResult <SimpleRequest, string> EmailNotBlank(SimpleRequest input)
 {
     if (input.Email == "")
     {
         return(Rop.Fail <SimpleRequest, string>("Email must not be blank"));
     }
     else
     {
         return(Rop.Succeed <SimpleRequest, string>(input));
     }
 }
Ejemplo n.º 11
0
        public void TestCanonicaliseGood()
        {
            var canonicalizeEmailR = Rop.Lift <SimpleRequest, SimpleRequest, string>(CanonicalizeEmail);

            var goodRequest = GoodRequest;
            var result      = goodRequest
                              .Pipe(ValidateRequest)
                              .Pipe(canonicalizeEmailR);

            Assert.IsTrue(result.IsSuccess);
        }
Ejemplo n.º 12
0
        public IHttpActionResult GetAll()
        {
            var results = _dao.GetAll();

            return(Rop.Match(results,
                             customers =>
            {
                var dtos = customers.Select(DtoConverter.CustomerToDto);
                return Ok(dtos);
            },
                             failure => this.InternalServerErrorResponse("bad customers")));
        }
Ejemplo n.º 13
0
        public void TestUpdateDbGood()
        {
            var canonicalizeEmailR = Rop.Lift <SimpleRequest, SimpleRequest, string>(CanonicalizeEmail);
            var updateDbR          = Rop.SuccessTee <SimpleRequest, string>(input => UpdateDatabase(input));

            var goodRequest = GoodRequest;
            var result      = goodRequest
                              .Pipe(ValidateRequest)
                              .Pipe(canonicalizeEmailR)
                              .Pipe(updateDbR);

            Assert.IsTrue(result.IsSuccess);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Return all customers
        /// </summary>
        public RopResult <IEnumerable <Customer>, DomainMessage> GetAll()
        {
            var db         = new DbContext();
            var ropResults = db.Customers().Select(FromDbCustomer);

            if (ropResults.Any(r => !r.IsSuccess))
            {
                return(Rop.Fail <IEnumerable <Customer>, DomainMessage>(DomainMessage.SqlCustomerIsInvalid()));
            }
            else
            {
                var goodResults = ropResults.Select(r => r.SuccessValue);
                return(Rop.Succeed <IEnumerable <Customer>, DomainMessage>(goodResults));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// CharToRomanDigitWithError
        /// </summary>
        public static RopResult <RomanDigit, string> CharToRomanDigitWithError(char ch)
        {
            switch (ch)
            {
            case 'I': return(Rop.Succeed <RomanDigit, string>(RomanDigit.I));

            case 'V': return(Rop.Succeed <RomanDigit, string>(RomanDigit.V));

            case 'X': return(Rop.Succeed <RomanDigit, string>(RomanDigit.X));

            default:
                var msg = String.Format("{0} is not a valid char", ch);
                return(Rop.Fail <RomanDigit, string>(msg));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Return the customer with the given CustomerId, or null if not found
        /// </summary>
        public RopResult <Customer, DomainMessage> GetById(CustomerId id)
        {
            var db = new DbContext();

            // Note that this code does not trap exceptions coming from the database. What would it do with them?
            // Compare with the F# version, where errors are returned along with the Customer
            var result = db.Customers().Where(c => c.Id == id.Value).Select(FromDbCustomer).FirstOrDefault();

            if (result == null)
            {
                return(Rop.Fail <Customer, DomainMessage>(DomainMessage.CustomerNotFound()));
            }

            return(result);
        }
Ejemplo n.º 17
0
        public void ExecuteFunction()
        {
            switch (Function)
            {
            case TFunc.Rev:
                Rop = Rop.Invert(Rop);
                break;

            case TFunc.Sqr:
                Rop = Rop.Square(Rop);
                break;

            default:
                break;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Convert a DbCustomer into a domain Customer
        /// </summary>
        public static RopResult <Customer, DomainMessage> FromDbCustomer(DbCustomer sqlCustomer)
        {
            if (sqlCustomer == null)
            {
                return(Rop.Fail <Customer, DomainMessage>(DomainMessage.CustomerNotFound()));
            }

            var firstName  = DomainUtilities.CreateFirstName(sqlCustomer.FirstName);
            var lastName   = DomainUtilities.CreateLastName(sqlCustomer.LastName);
            var createName = Rop.Lift2 <String10, String10, PersonalName, DomainMessage>(PersonalName.Create);
            var name       = createName(firstName, lastName);

            var id         = DomainUtilities.CreateCustomerId(sqlCustomer.Id);
            var email      = DomainUtilities.CreateEmail(sqlCustomer.Email);
            var createCust = Rop.Lift3 <CustomerId, PersonalName, EmailAddress, Customer, DomainMessage>(Customer.Create);
            var cust       = createCust(id, name, email);

            return(cust);
        }
Ejemplo n.º 19
0
        public IHttpActionResult Post(int customerId, [FromBody] CustomerDto dto)
        {
            var logSuccessR     = LogSuccessR <CustomerDto>("Post {0}");
            var dtoToCustomerR  = Rop.Bind <CustomerDto, Customer, DomainMessage>(DtoConverter.DtoToCustomer);
            var upsertCustomerR = Rop.Bind <Customer, Unit, DomainMessage>(_dao.Upsert);
            var logFailureR     = LogFailureR <Unit>();
            var okR             = Rop.Lift <Unit, IHttpActionResult, DomainMessage>(this.Ok);

            dto.Id = customerId;                                      // set the DTO's CustomerId

            var dtoR = Rop.Succeed <CustomerDto, DomainMessage>(dto); // start with a success

            return(dtoR                                               // start with a success
                   .Pipe(logSuccessR)                                 // log the success branch
                   .Pipe(dtoToCustomerR)                              // convert the DTO to a Customer
                   .Pipe(upsertCustomerR)                             // upsert the Customer
                   .Pipe(logFailureR)                                 // log any errors
                   .Pipe(okR)                                         // return OK on the happy path
                   .Pipe(ToHttpResult));                              // other errors returned as BadRequest, etc
        }
        /// <summary>
        /// Create a domain customer from a DTO or null if not valid.
        /// </summary>
        public static RopResult <Customer, DomainMessage> DtoToCustomer(CustomerDto dto)
        {
            if (dto == null)
            {
                // dto can be null if deserialization fails
                return(Rop.Fail <Customer, DomainMessage>(DomainMessage.CustomerIsRequired()));
            }

            var firstName  = DomainUtilities.CreateFirstName(dto.FirstName);
            var lastName   = DomainUtilities.CreateLastName(dto.LastName);
            var createName = Rop.Lift2 <String10, String10, PersonalName, DomainMessage>(PersonalName.Create);
            var name       = createName(firstName, lastName);

            var id         = DomainUtilities.CreateCustomerId(dto.Id);
            var email      = DomainUtilities.CreateEmail(dto.Email);
            var createCust = Rop.Lift3 <CustomerId, PersonalName, EmailAddress, Customer, DomainMessage>(Customer.Create);
            var cust       = createCust(id, name, email);

            return(cust);
        }
Ejemplo n.º 21
0
        public IHttpActionResult Get(int customerId)
        {
            var logSuccessR       = LogSuccessR <int>("Get {0}");
            var createCustomerIdR = Rop.Bind <int, CustomerId, DomainMessage>(DomainUtilities.CreateCustomerId);
            var getByIdR          = Rop.Bind <CustomerId, Customer, DomainMessage>(_dao.GetById);
            var customerToDtoR    = Rop.Lift <Customer, CustomerDto, DomainMessage>(DtoConverter.CustomerToDto);
            var logFailureR       = LogFailureR <CustomerDto>();
            var okR = Rop.Lift <CustomerDto, IHttpActionResult, DomainMessage>(this.Ok);

            var idR = Rop.Succeed <int, DomainMessage>(customerId);    // start with a success

            return(idR
                   .Pipe(logSuccessR)       // log the success branch
                   .Pipe(createCustomerIdR) // convert the int into a CustomerId
                   .Pipe(getByIdR)          // get the Customer for that CustomerId
                   .Pipe(customerToDtoR)    // convert the Customer into a DTO
                   .Pipe(logFailureR)       // log any errors
                   .Pipe(okR)               // return OK on the happy path
                   .Pipe(ToHttpResult));    // other errors returned as BadRequest, etc
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Insert/update the customer
        /// If it already exists, update it, otherwise insert it.
        /// If the email address has changed, raise a EmailAddressChanged event on DomainEvents
        /// </summary>
        public RopResult <Unit, DomainMessage> Upsert(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            var db             = new DbContext();
            var existingDbCust = GetById(customer.Id);
            var newDbCust      = ToDbCustomer(customer);

            return(Rop.Match(existingDbCust,
                             success =>
            {
                // update
                db.Update(newDbCust);

                // check for changed email
                if (!customer.EmailAddress.Equals(success.EmailAddress))
                {
                    // return a Success with the extra event
                    var msg = DomainMessage.EmailAddressChanged(success.EmailAddress, customer.EmailAddress);
                    return Rop.SucceedWithMsg <Unit, DomainMessage>(Unit.Instance, msg);
                }
                else
                {
                    // return a Success with no extra event
                    return Rop.Succeed <Unit, DomainMessage>(Unit.Instance);
                }
            },
                             failure =>
            {
                // insert
                db.Insert(newDbCust);

                // return a Success
                return Rop.Succeed <Unit, DomainMessage>(Unit.Instance);
            }));
        }
Ejemplo n.º 23
0
 public TPNumber ReadRightOperand()
 {
     return(Rop.Copy());
 }
Ejemplo n.º 24
0
        //==============================================
        // helpers
        //==============================================

        // log values on the success path
        private Func <RopResult <T, DomainMessage>, RopResult <T, DomainMessage> > LogSuccessR <T>(string format)
        {
            return(Rop.SuccessTee <T, DomainMessage>(v => Log(format, v)));
        }
Ejemplo n.º 25
0
        public T RetTRop()
        {
            object str = Rop.GetType().GetMethod("Copy")?.Invoke(null, new object[] { Rop }) ?? Rop;

            return((T)str);
        }
Ejemplo n.º 26
0
        public string RetRop()
        {
            object str = Rop.GetType().GetMethod("Show")?.Invoke(Rop, null) ?? Rop;

            return(str.ToString());
        }