コード例 #1
0
        /// <summary>
        /// 删除
        /// </summary>
        public override void EntityDelete()
        {
            ExceptionalRule rule   = new ExceptionalRule();
            Exceptional     entity = EntityGet();

            rule.RDelete(entity);
        }
コード例 #2
0
        public async Task TestAsync()
        {
            var store = GetStore();

            Exceptional.Configure(new TestSettings(store));
            Assert.True(await store.TestAsync().ConfigureAwait(false));
        }
コード例 #3
0
        // applicative

        public static Exceptional <R> Apply <T, R>
            (this Exceptional <Func <T, R> > @this, Exceptional <T> arg)
        => @this.Match(
            Exception: ex => ex,
            Success: func => arg.Match(
                Exception: ex => ex,
                Success: t => new Exceptional <R>(func(t))));
コード例 #4
0
        public void IsSuccess_Should_return_true_when_not_an_Exception()
        {
            Exceptional <string> exceptional = Success("success");

            Assert.True(exceptional.IsSuccess);
            Assert.False(exceptional.IsException);
        }
コード例 #5
0
        public static IEnumerator GetWebText(Url url, IEnumerable <Tuple <string, string> > headers, bool treatEmptyStringAsError = false)
        {
            UnityWebRequest www = UnityWebRequest.Get(url.ToString());

            www.disposeDownloadHandlerOnDispose = true;
            www.chunkedTransfer = false;
            headers.ForEach(t => www.SetRequestHeader(t.Item1, t.Item2));
            yield return(www.SendWebRequest());

            while (!www.isDone)
            {
                yield return(null);
            }

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
                yield return(Exceptional.Of <string>(new WebRequestException(www.error)));
            }
            else if (treatEmptyStringAsError && String.IsNullOrEmpty(www.downloadHandler.text))
            {
                yield return(Exceptional.Of <string>(new WebRequestException("Result was empty")));
            }
            else
            {
                yield return(www.downloadHandler.text);
            }
            www.Dispose();
        }
コード例 #6
0
        public void Given_ExceptionError_REturns_Fail_Exceptional()
        {
            Exceptional <int> invalid = (ErrorException)"this is an error";

            invalid.Match(err => Assert.Equal("this is an error", err.Message),
                          i => Assert.False(true));
        }
コード例 #7
0
        /// <summary>
        /// 获得实体
        /// </summary>
        /// <returns></returns>
        private Exceptional EntityGet()
        {
            Exceptional entity = new Exceptional();

            entity.ID = HTDataID;
            return(entity);
        }
コード例 #8
0
ファイル: ExceptionalExtTests.cs プロジェクト: fambda/fambda
        public void BindShouldNotInvokeFuncWhenException()
        {
            // Arrange
            var exception = new SomeException("Some exception");
            Exceptional <int> exceptional = exception;

            Exceptional <bool> exceptionalWithSuccess = true;

            var anotherException = new SomeException("Some another exception");
            Exceptional <bool> exceptionalWithException = anotherException;


            Func <int, Exceptional <bool> > toAnotherExceptional = (i) =>
            {
                if (i.Equals(1))
                {
                    return(exceptionalWithSuccess);
                }
                else
                {
                    return(exceptionalWithException);
                }
            };

            // Act
            var result = exceptional.Bind(toAnotherExceptional);


            // Assert
            result.ToString().Should().Be(exceptional.ToString());
        }
コード例 #9
0
ファイル: ExceptionalExtTests.cs プロジェクト: fambda/fambda
        public void BindShouldSucceedWhenSuccess()
        {
            // Arrange
            var value = 1;
            Exceptional <int> exceptional = value;

            Exceptional <bool> exceptionalWithSuccess = true;

            var exception = new SomeException("Some exception");
            Exceptional <bool> exceptionalWithException = exception;


            Func <int, Exceptional <bool> > toAnotherExceptional = (i) =>
            {
                if (i.Equals(1))
                {
                    return(exceptionalWithSuccess);
                }
                else
                {
                    return(exceptionalWithException);
                }
            };

            // Act
            var result = exceptional.Bind(toAnotherExceptional);


            // Assert
            result.Should().Be(exceptionalWithSuccess);
        }
コード例 #10
0
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="p_Entity">实体类</param>
        /// <returns>操作影响的记录行数</returns>
        public override int Delete(BaseEntity p_Entity)
        {
            try
            {
                Exceptional MasterEntity = (Exceptional)p_Entity;
                if (MasterEntity.ID == 0)
                {
                    return(0);
                }

                //删除主表数据
                string Sql = "";
                Sql = "DELETE FROM Enum_Exceptional WHERE " + "ID=" + SysString.ToDBString(MasterEntity.ID);
                //执行
                int AffectedRows = 0;
                if (!this.sqlTransFlag)
                {
                    AffectedRows = this.ExecuteNonQuery(Sql);
                }
                else
                {
                    AffectedRows = sqlTrans.ExecuteNonQuery(Sql);
                }

                return(AffectedRows);
            }
            catch (BaseException E)
            {
                throw new BaseException(E.Message, E);
            }
            catch (Exception E)
            {
                throw new BaseException(FrameWorkMessage.GetAlertMessage((int)Message.CommonDBDelete), E);
            }
        }
コード例 #11
0
        public void SuccessTest()
        {
            var testObject = Exceptional <int> .Success(5, new PagingInfo(10, 5));

            Assert.True(testObject.IsSuccess);
            Assert.Equal(5, testObject.Value);
        }
コード例 #12
0
        public void Given_Value_Return_Success_Exceptional()
        {
            Exceptional <int> validInt = 5;

            validInt.Match(err => Assert.False(true),
                           i => Assert.Equal(5, i));
        }
コード例 #13
0
 /// <summary>
 /// 修改
 /// </summary>
 /// <param name="p_BE">要修改的实体</param>
 /// <param name="sqlTrans">事务类</param>
 public void RUpdate(BaseEntity p_BE, IDBTransAccess sqlTrans)
 {
     try
     {
         this.CheckCorrect(p_BE);
         Exceptional entity = (Exceptional)p_BE;
         string      sql    = "";
         sql  = " SELECT Name FROM Enum_Exceptional WHERE Name = " + SysString.ToDBString(entity.Name);
         sql += " AND ID <>" + entity.ID;
         DataTable dt = new DataTable();
         dt = sqlTrans.Fill(sql);
         if (dt.Rows.Count != 0)
         {
             throw new Exception("此原因已存在,请重新输入");
         }
         ExceptionalCtl control = new ExceptionalCtl(sqlTrans);
         control.Update(entity);
     }
     catch (BaseException)
     {
         throw;
     }
     catch (Exception E)
     {
         throw new BaseException(E.Message);
     }
 }
コード例 #14
0
 /// <summary>
 /// 新增(传入事务处理)
 /// </summary>
 /// <param name="p_BE">要新增的实体</param>
 /// <param name="sqlTrans">事务类</param>
 public void RAdd(BaseEntity p_BE, IDBTransAccess sqlTrans)
 {
     try
     {
         this.CheckCorrect(p_BE);
         Exceptional entity = (Exceptional)p_BE;
         string      sql    = "";
         sql = " SELECT Name FROM Enum_Exceptional WHERE Name = " + SysString.ToDBString(entity.Name);
         DataTable dt = new DataTable();
         dt = sqlTrans.Fill(sql);
         if (dt.Rows.Count != 0)
         {
             throw new Exception("此原因已存在,请重新输入");
         }
         ExceptionalCtl control = new ExceptionalCtl(sqlTrans);
         //entity.ID=(int)EntityIDTable.GetID((long)SysEntity.Enum_Exceptional,sqlTrans);
         control.AddNew(entity);
     }
     catch (BaseException)
     {
         throw;
     }
     catch (Exception E)
     {
         throw new BaseException(E.Message);
     }
 }
コード例 #15
0
        public void IfSuccessTest()
        {
            var testObject = 0;

            try
            {
                // Test exception is thrown.
                Exceptional <int> .Success(0, new PagingInfo(10, 5)).IfSuccess(null);

                Assert.Fail();
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual("action", ex.ParamName);
            }
            catch
            {
                Assert.Fail();
            }

            Exceptional <int> .Success(0, new PagingInfo(10, 5)).IfSuccess(x => testObject = 5);

            Assert.AreEqual(5, testObject);

            Exceptional <int> .Failure(new ArgumentNullException("test")).IfSuccess(x => testObject = 10);

            Assert.AreNotEqual(10, testObject);
        }
コード例 #16
0
        public void SuccessTest()
        {
            var testObject = Exceptional <int> .Success(5, new PagingInfo(10, 5));

            Assert.AreEqual(true, testObject.IsSuccess, "The Result was expected to be a success, but it was a failure.");
            Assert.AreEqual(5, testObject.Value, "The Result value did not match the expected result.");
        }
コード例 #17
0
        /// <summary>
        /// 新增
        /// </summary>
        public override int EntityAdd()
        {
            ExceptionalRule rule   = new ExceptionalRule();
            Exceptional     entity = EntityGet();

            rule.RAdd(entity);
            return(entity.ID);
        }
コード例 #18
0
 public static Exceptional <R> Apply <T, R>(this Exceptional <Func <T, R> > fExt, Exceptional <T> tExt)
 => fExt.Match(
     Exception: (e) => e,
     Success: (f) => tExt.Match(
         Exception: (e) => e,
         Success: (t) => Exceptional(f(t))
         )
     );
コード例 #19
0
 public static Exceptional <RR> SelectMany <T, R, RR>(this Exceptional <T> exceptional, Func <T, Exceptional <R> > bind, Func <T, R, RR> project)
 => exceptional.Match(
     Exception: (e) => e,
     Success: (t) => bind(t).Match(
         Exception: (e) => e,
         Success: (r) => Exceptional(project(t, r))
         )
     );
コード例 #20
0
        public void FailureTest()
        {
            var testObject = Exceptional <int?> .Failure(new ArgumentNullException("test"));

            Assert.AreEqual(false, testObject.IsSuccess);
            Assert.IsInstanceOfType(testObject.Exception, typeof(ArgumentNullException));
            Assert.AreEqual("test", ((ArgumentNullException)testObject.Exception).ParamName);
        }
コード例 #21
0
ファイル: ExceptionalTest.cs プロジェクト: eberzosa/pundit
        public void NotVsDocFileTest()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");

            path = Path.Combine(path, "nodoc.xml");

            Assert.IsFalse(Exceptional.IsVsDocFile(path));
        }
コード例 #22
0
        public void FailureTest()
        {
            var testObject = Exceptional <int?> .Failure(new ArgumentNullException("test"));

            Assert.False(testObject.IsSuccess);
            Assert.IsType <ArgumentNullException>(testObject.Exception);
            Assert.Equal("test", ((ArgumentNullException)testObject.Exception).ParamName);
        }
コード例 #23
0
        public void Data_of_T_should_cast_to_Exceptional()
        {
            const string         value       = "sample";
            Exceptional <string> exceptional = value;

            Assert.True(exceptional.IsSuccess);

            exceptional.OnSuccess(data => Assert.Equal(value, data));
        }
コード例 #24
0
        public void Map_TransFrom_ET_To_Er(double?num)
        {
            Exceptional <double> valid = num.HasValue ? (Exceptional <double>)num : (ErrorException)("num is null");
            bool isValid = num.HasValue;
            var  res     = valid.Map(d => $"num is {d}");

            res.Match(err => Assert.True(!isValid && err.Message == "num is null"),
                      s => Assert.Equal($"num is {num}", s));
        }
コード例 #25
0
        public void Exceptions_should_be_cast_to_Exceptional()
        {
            var exception = new InvalidCastException();
            Exceptional <int> exceptional = exception;

            Assert.True(exceptional.IsException);

            exceptional.OnException(ex => Assert.Equal(exception, ex));
        }
コード例 #26
0
        public void Assert_Select_ET_Transfrom_ER(int?num)
        {
            Exceptional <int> E1 = num.HasValue ? (Exceptional <int>)num : (ErrorException)("num is null");
            var res = E1.Select <int, double>(i => (double)i / 2.0);

            res.Match(
                err => Assert.Equal("num is null", err.Message),
                d => Assert.Equal((double)num / 2.0, d));
        }
コード例 #27
0
        public void Exceptional_should_be_converted_to_failed_result_when_it_is_success()
        {
            Exceptional <int> exceptional = 11;

            Validation <int> result = exceptional;

            result.IsValid.Should().BeTrue();
            result.Data.Should().Be(11);
        }
コード例 #28
0
        private IEnumerable InternalRoutine(IEnumerator coroutine)
        {
            while (true)
            {
                if (isCancelled)
                {
                    e = new CoroutineCancelledException();
                    yield break;
                }
                try
                {
                    if (!coroutine.MoveNext())
                    {
                        yield break;
                    }
                }
                catch (Exception e)
                {
                    this.e = e;
                    yield break;
                }
                object yielded = coroutine.Current;

                // Support nested Nestable Coroutines by returning the underlying
                // system coroutine so that Unity will recognise it and process it.
                // Otherwise we will continue executing on the next frame.
                if (yielded is NestableCoroutine <T> )
                {
                    yield return((yielded as NestableCoroutine <T>).coroutine);
                }
                else
                {
                    if (yielded != null && yielded is T)
                    {
                        returnVal = F.Exceptional((T)yielded);
                        yield break;
                    }
                    else if (yielded != null && yielded is Option <T> )
                    {
                        returnVal = ((Option <T>)yielded).Match(
                            () => Exceptional.Of <T>(new NoneException()),
                            (f) => F.Exceptional(f));
                        yield break;
                    }
                    else if (yielded != null && yielded is Exceptional <T> )
                    {
                        returnVal = (Exceptional <T>)yielded;
                        yield break;
                    }
                    else
                    {
                        yield return(coroutine.Current);
                    }
                }
            }
        }
コード例 #29
0
        private static void Main()
        {
            // Example of code-only setup, alternatively this can be in the App.config
            // RollupPeriod is null so a new file is always generated, for demonstration purposes
            Exceptional.Configure(settings =>
            {
                settings.DefaultStore = new JSONErrorStore(new ErrorStoreSettings
                {
                    ApplicationName = "Samples.Console",
                    Path            = "Errors",
                    RollupPeriod    = null
                });

                // Example of a code-only email setup, alternatively this can be in the App.config
                settings.Register(new EmailNotifier(new EmailSettings
                {
                    SMTPHost        = "localhost", // Use Papercut here for testing: https://github.com/ChangemakerStudios/Papercut
                    FromAddress     = "*****@*****.**",
                    FromDisplayName = "Bob the Builder",
                    ToAddress       = "*****@*****.**"
                }));
            });

            // How to do it with normal roll-up
            //Exceptional.Configure(new ExceptionalSettings() { DefaultStore = new JSONErrorStore("Errors") });

            // Optional: for logging all unhandled exceptions
            Exceptional.ObserveAppDomainUnhandledExceptions();

            // Normally we wouldn't want to .GetAwaiter().GetResult(), but async Main is only on a the latest platforms at the moment
            DisplayExceptionStats().GetAwaiter().GetResult();
            PauseForInput();

            try
            {
                throw new Exception("Just a try/catch test");
            }
            catch (Exception ex)
            {
                ex.AddLogData("Example string", DateTime.UtcNow.ToString())
                .AddLogData("User Id", "You could fetch a user/account Id here, etc.")
                .AddLogData("Links get linkified", "https://www.google.com");

                // logged, but caught so we don't crash
                ex.LogNoContext();
            }

            DisplayExceptionStats().GetAwaiter().GetResult();
            PauseForInput();

            WriteLine("This next one will crash the program, but will be logged on the way out...");
            PauseForInput();

            // one not explicitly caught, will be logged by ExceptionHandler
            throw new Exception("I am an exception thrown on exit");
        }
コード例 #30
0
 public static Exceptional <RR> Bind <R, RR>
 (
     this Exceptional <R> @this,
     Func <R, Exceptional <RR> > f
 )
 => @this.Match
 (
     Exception: ex => new Exceptional <RR>(ex),
     Success: r => f(r)
 );