Пример #1
0
 public void True_Valid()
 {
     WrapErr.ToErrReport(out ErrReport err, 1111, "Validate arg", () => {
         WrapErr.ChkTrue(true, 8888, "zork error");
     });
     Assert.AreEqual(0, err.Code, "Should not have been an error");
 }
Пример #2
0
 public void True_Fail()
 {
     WrapErr.ToErrReport(out ErrReport err, 1111, "Validate arg", () => {
         WrapErr.ChkTrue(false, 8888, "zork error");
     });
     this.Validate(err, 8888, "True_Fail", "zork error");
 }
Пример #3
0
 /// <summary>
 /// The derived super state will override if it has some code to execute on the
 /// Defered transition type
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 protected virtual ISpEventMessage OnRuntimeTransitionRequest(ISpEventMessage msg)
 {
     WrapErr.ChkTrue(false, 9999, () => {
         return(String.Format("Not Overriden to Define Runtime Handling of Defered Transition for {0} State", this.FullName));
     });
     return(msg);
 }
Пример #4
0
        /// <summary>
        /// Add an event to the proper priority queue
        /// </summary>
        /// <param name="msg">The msg to add</param>
        protected override void AddEvent(ISpEventMessage msg)
        {
            switch (msg.Priority)
            {
            case SpEventPriority.Low:
                this.lowPriorityQueue.Enqueue(msg);
                break;

            case SpEventPriority.Normal:
                this.NormalPriorityQueue.Enqueue(msg);
                break;

            case SpEventPriority.High:
                this.HighPriorityQueue.Enqueue(msg);
                break;

            case SpEventPriority.Urgent:
                this.UrgentPriorityQueue.Enqueue(msg);
                break;

            default:
                WrapErr.ChkTrue(false, 50150, String.Format("The Priority Type '{0}' is not Handled", msg.Priority));
                break;
            }
        }
        //// TODO - remove this - do not want to copy the event id automatically ??
        //public SpBaseEventResponse(TMsgType _type, ISpEventMessage msg, TReturn _return, string returnStatus)
        //    : base(_type, new SpIntToInt(msg.EventId)) {
        //    // Transfer the message guid to the response for correlation
        //    this.Uid = msg.Uid;
        //    this.ReturnCode = this.GetReturnId(_return);
        //    this.ReturnStatus = ReturnStatus;
        //}


        //public SpBaseEventResponse(TMsgType _type, TMsgId id, SpEventPriority priority, ISpEventMessage msg, ISpToInt returnCode, string returnStatus)
        //    : base(_type, id, priority) {
        //    // Transfer the message guid to the response for correlation
        //    this.Uid = msg.Uid;
        //    this.ReturnCode = returnCode.ToInt();
        //    this.ReturnStatus = ReturnStatus;
        //}



        private int GetReturnId(TReturn _return)
        {
            WrapErr.ChkTrue(typeof(TReturn).IsEnum, 9999, () => string.Format("Return id {0} must be Enum", _return.GetType().Name));
            WrapErr.ChkTrue(typeof(TReturn).GetEnumUnderlyingType() == typeof(int), 9999,
                            () => string.Format("Event id enum {0} must be derived from int", _return.GetType().Name));
            return(Convert.ToInt32(_return));
        }
Пример #6
0
 /// <summary>
 /// Set the interval in  for wakeup for the next Start
 /// </summary>
 /// <param name="interval">The interval in </param>
 public void SetInterval(TimeSpan interval)
 {
     WrapErr.ChkDisposed(this.disposed, 50002);
     WrapErr.ChkTrue(interval.TotalMilliseconds > 0, 50000, "The interval cannot be 0 milliseconds total");
     WrapErr.ToErrorReportException(50001, () => {
         this.timespan = interval;
     });
 }
Пример #7
0
        //private readonly static ClassLog log = new ("FileHelpers");

        #endregion


        /// <summary>Flip all slashes back or forth for cross-platform compatibility</summary>
        /// <param name="pathString">The path string to convert</param>
        /// <returns>The converted string</returns>
        public static string ConvertSlashes(string pathString)
        {
            WrapErr.ChkTrue(pathString.Length > 0, 9999, "Empty path string not allowed");
            return(WrapErr.ToErrorReportException(9999, "Failed to flip slashes", () => {
                // Cover all bases by converting forward or back slashes to OS specific
                string tmp = pathString.Replace('\\', Path.DirectorySeparatorChar);
                return tmp.Replace('/', Path.DirectorySeparatorChar);
            }));
        }
Пример #8
0
        /// <summary>Constructor for Normal Priority messages</summary>
        /// <param name="_type">The type id to cast to derived for payload retrieval</param>
        /// <param name="id">The event identifier</param>
        public SpBaseEventMsg(TMsgType _type, int id)
        {
            WrapErr.ChkTrue(typeof(TMsgType).IsEnum, 9999, () => string.Format("Event type {0} must be Enum", _type.GetType().Name));
            WrapErr.ChkTrue(typeof(TMsgType).GetEnumUnderlyingType() == typeof(int), 9999,
                            () => string.Format("Event type enum {0} must be derived from int", id.GetType().Name));

            this.typeId   = Convert.ToInt32(_type);
            this.eventId  = id;
            this.priority = SpEventPriority.Normal;
        }
Пример #9
0
 /// <summary>
 /// Called on every other period after the first
 /// </summary>
 /// <param name="msg">The incoming message</param>
 /// <returns>A state transition object</returns>
 public virtual ISpStateTransition OnTick(ISpEventMessage msg)
 {
     //Log.Info(this.className, "OnTick", String.Format("'{0}' State - {1}", this.FullName, this.ConvertEventIdToString(msg.EventId)));
     WrapErr.ChkTrue(this.IsEntryExcecuted, 50205, () => {
         return(String.Format("OnTick for '{0}' State Cannot be Executed Before OnEntry", this.FullName));
     });
     return(WrapErr.ToErrorReportException(9999, () => {
         return this.GetTransition(false, this.ExecOnTick, msg);
     }));
 }
 public IStorageManager <T> GetManager <T>() where T : class
 {
     // TODO
     if (typeof(T).Name == typeof(SettingsDataModel).Name)
     {
         return(this.set.Settings as IStorageManager <T>);
     }
     ////else if(typeof(T).Name == typeof(TerminatorData).Name) {
     ////}
     WrapErr.ChkTrue(false, 9999, () => string.Format("No storage manager for type {0}", typeof(T).Name));
     return(null);
 }
Пример #11
0
        //private readonly static ClassLog log = new ("DirectoryHelpers");

        #endregion


        public static bool CreateStorageDir(string dir)
        {
            WrapErr.ToErrReport(out ErrReport report, 9999,
                                () => string.Format("Failed to create directory '{0}'", dir),
                                () => {
                WrapErr.ChkTrue(dir.Length > 0, 9999, "0 length directory path");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            });
            return(report.Code == 0);
        }
Пример #12
0
        /// <summary>
        /// Override and seal the ExecOnExit to automate common super state
        /// entry functionality. After execution the SuperStateOnExit()
        /// is called.
        /// </summary>
        /// <param name="msg">The incoming message</param>
        /// <returns>The appropriate return message</returns>
        protected sealed override void ExecOnExit()
        {
            Log.Info(this.className, "ExecOnExit", this.FullName);
            WrapErr.ChkTrue(this.IsEntryExcecuted, 9999, () => {
                return(String.Format("ExecOnExit called Before OnEntry {0} State", this.FullName));
            });

            if (this.currentState != null)
            {
                this.currentState.OnExit();
            }
            this.currentState = this.entryState;
        }
Пример #13
0
        /// <summary>
        /// Handle the NextState Transition type by setting the next state as
        /// </summary>
        /// <param name="tr"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private ISpStateTransition HandleNextStateTransitionType(ISpStateTransition tr, ISpEventMessage msg)
        {
            Log.Info(this.className, "HandleNextStateTransitionType", String.Format("'{0}' State", this.FullName));

            WrapErr.ChkTrue(tr.TransitionType == SpStateTransitionType.NextState, 9999,
                            () => { return(String.Format("{0} is not NextState", tr.TransitionType)); });

            WrapErr.ChkVar(tr.NextState, 9999, () => { return
                                                       (String.Format(
                                                            "State {0} Specified Next State on Event {1} but Next State Null",
                                                            this.currentState.FullName, this.GetCachedEventId(msg.EventId))); });

            this.currentState.OnExit();
            this.currentState = tr.NextState;
            return(this.currentState.OnEntry(this.MsgFactory.GetDefaultResponse(msg)));
        }
Пример #14
0
        /// <summary>
        /// Execute on each tick period
        /// </summary>
        /// <param name="msg">The incoming message with event</param>
        /// <returns>The return transition object with result information</returns>
        public sealed override ISpStateTransition OnTick(ISpEventMessage msg)
        {
            //Log.Info(this.className, "OnTick", String.Format("'{0}' State", this.FullName));
            WrapErr.ChkVar(this.entryState, 9999, "The 'SetEntryState() Must be Called in the Constructor");
            WrapErr.ChkVar(this.currentState, 9999, "Current state is not set");
            WrapErr.ChkTrue(this.IsEntryExcecuted, 9999, "Tick Being Called before OnEntry");

            // If there are OnEvent transitions registered at the superstate level return immediately
            ISpStateTransition tr = GetSuperStateOnEventTransition(msg);

            if (tr != null)
            {
                return(tr);
            }
            return(this.GetTransition(this.currentState.OnTick, msg));
        }
Пример #15
0
        /// <summary>Remove any leading or trailing '/' or '\' from path string</summary>
        /// <remarks>Path.Combine needs these off before combining</remarks>
        /// <param name="pathString">The path string to clean</param>
        /// <returns>The cleaned path string</returns>
        public static string CleanLeadAndTrailingSlashes(string pathString)
        {
            string tmp = pathString;

            if (tmp.StartsWith(Path.PathSeparator.ToString()))
            {
                tmp = tmp.Remove(0, 1);
                WrapErr.ChkTrue(tmp.Length > 0, 9999, () => string.Format("Empty path '{0}'", pathString));
            }
            if (tmp.EndsWith(Path.PathSeparator.ToString()))
            {
                tmp = tmp.Remove(tmp.Length - 1, 1);
                WrapErr.ChkTrue(tmp.Length > 0, 9999, () => string.Format("Empty path '{0}'", pathString));
            }
            return(tmp);
        }
Пример #16
0
        public void True_Fail_WithNullable()
        {
            //ErrReport err = new ErrReport();
            // To show that it will not flag a nullable error to compiler
            // because of attribute it knows ChkTrue will throw and so
            // the operation on null string never happens
            string?n = null;

            try {
                WrapErr.ChkTrue(false, 8889, "zork error");
                string x = n;
                Assert.True(false, "Should not get here");
            }
            catch {
                Assert.True(true, "Should get here");
            }
        }
Пример #17
0
        /// <summary>Register a transition for a state</summary>
        /// <param name="type">string of transition type</param>
        /// <typeparam name="TMsgId">Event id</typeparam>
        /// <param name="msgId">The event message id</param>
        /// <param name="transition">Transition object</param>
        /// <param name="store">Transition store</param>
        public static void RegisterTransition <TMsgId>(string type, TMsgId msgId, ISpStateTransition <TMsgId>?transition, Dictionary <int, ISpStateTransition <TMsgId> >?store) where TMsgId : struct
        {
            //WrapErr.ChkParam(eventId, "msgId", 51004);
            WrapErr.ChkParam(transition, "transition", 51005);
            WrapErr.ChkParam(store, "store", 51006);

            WrapErr.ChkTrue(typeof(TMsgId).IsEnum, 9999, () => string.Format("Transition type {0} must be Enum", msgId.GetType().Name));
            WrapErr.ChkTrue(typeof(TMsgId).GetEnumUnderlyingType() == typeof(Int32), 9999,
                            () => string.Format("Transition type enum {0} must be derived from int", msgId.GetType().Name));

            int tmp = Convert.ToInt32(msgId);

            // 51007 - failure of conversion number

            // Duplicate transitions on same Event is a no no.
            WrapErr.ChkFalse(store.Keys.Contains(tmp), 51008,
                             () => { return(String.Format("Already Contain a '{0}' Transition for Id:{1}", type, tmp)); });
            store.Add(tmp, transition);
        }
Пример #18
0
        public string IconSource(UIIcon code)
        {
            ErrReport report;
            string    source = WrapErr.ToErrReport(out report, 9999,
                                                   () => string.Format(""),
                                                   () => {
                string tmp = "";
                this.IconInfo(code, (info) => {
                    tmp = info.IconSource as string;
                    WrapErr.ChkVar(tmp, 9999, () => string.Format("No source string for {0}", code));
                    WrapErr.ChkTrue(tmp.Length > 0, 9999, () => string.Format("0 length source string for {0}", code));
                }, (msg) => {
                    tmp = "";
                });
                return(tmp);
            });

            return(report.Code == 0 ? source : "");
        }
Пример #19
0
        /// <summary>
        /// Convert an integer to a generic enum
        /// </summary>
        /// <typeparam name="T">The enum type</typeparam>
        /// <param name="value">The integer value to convert from</param>
        /// <returns>The Enum or an exception on failure to convert</returns>
        public static T ToEnum <T>(this int value) where T : struct
        {
            T enumType = default(T);
            T ret      =
                WrapErr.ToErrorReportException(9999,
                                               () => { return(String.Format(
                                                                  "Enum Conversion Failed Attempting to Convert to Type '{0}' with Value '{1}'",
                                                                  enumType.GetType().Name, value)); },
                                               () => {
                // This will throw on non enum but not out of range
                return((T)Enum.Parse(typeof(T), value.ToString()));
            });

            // Do the enum range check
            WrapErr.ChkTrue(Enum.IsDefined(typeof(T), ret), 9999, () => {
                return(String.Format(
                           "Enum Conversion Out of Range Attempting to Convert to Type '{0}' with Value '{1}'",
                           enumType.GetType().Name, value));
            });
            return(ret);
        }
Пример #20
0
        /// <summary>
        /// Read the transition object to determine behavior
        /// </summary>
        /// <param name="tr">The transition object</param>
        /// <param name="msg">the current event message</param>
        /// <param name="superStateLevelEvent">
        ///  true if the transition object is from the current substate, false if the transition was generated
        ///  by the superstate based on a previous Defered Transition type generated from the substate. This
        ///  prevents infinite recursion.
        /// </param>
        /// <returns>A Transtion object with the results of the state processing</returns>
        ISpStateTransition ReadTransitionType(ISpStateTransition tr, ISpEventMessage msg, bool superStateLevelEvent)
        {
            WrapErr.ChkVar(tr, 9999, "The transition is null");
            switch (tr.TransitionType)
            {
            case SpStateTransitionType.SameState:
                return(tr);

            case SpStateTransitionType.NextState:
                return(this.HandleNextStateTransitionType(tr, msg));

            case SpStateTransitionType.ExitState:
                return(this.HandleExitStateTransitionType(msg));

            case SpStateTransitionType.Defered:
                return(this.HandleDeferedStateTransitionType(tr, msg, superStateLevelEvent));

            default:
                WrapErr.ChkTrue(false, 9999, String.Format("Transition Type {0} not Handled", tr.TransitionType));
                return(tr);
            }
        }
Пример #21
0
 public void ExceptionType_Regular_False()
 {
     CheckExceptionType(() => { WrapErr.ChkTrue(true, 8888, "true"); });
 }
Пример #22
0
 public void ExceptionType_Regular_True()
 {
     CheckExceptionType(() => { WrapErr.ChkTrue(false, 8888, "false"); });
 }