TraceLog() приватный Метод

private TraceLog ( Exception ex, string message, bool reportIt = true, [ filePath = "", [ lineNumber, [ method = "" ) : void
ex System.Exception
message string
reportIt bool
filePath [
lineNumber [
method [
Результат void
Пример #1
0
        private static YConfig <T> Retrieve(string filename, Func <string, string> PreProccessContent = null)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                return(null);
            }

            try
            {
                //Read in configuration array from file pointed to by input param (or falling back to default file)
#if NETFX
                var content = File.ReadAllText(filename);
#elif UNIVERSAL
                var ss      = new Tools.StorageService(false);
                var content = ss.LoadFile(filename).GetResults();
#endif
                if (PreProccessContent != null)
                {
                    content = PreProccessContent(content);
                }
                //deserialize into List of Configurations and pick the active one
                return(content.FromJSON <YConfig <T> >());
            }
            catch (Exception ex)
            {
                DebugEx.TraceLog("Failed to read config file : " + ex.Message);
                return(null);
            }
        }
Пример #2
0
        //------------------------------------------------------------------------------------------------------------------------
        public bool OnMessageReceived(T wrapper_msg, object payload)
        {
            //check if this is a response, in which case unblock pending request
            if (wrapper_msg.IsResponse)
            {
                int syncId = wrapper_msg.SyncId;

                DebugEx.Assert(syncId != 0, "IsResponse flag without valid syncId not allowed");
                if (syncId == 0)
                {
                    return(false);
                }

                DebugEx.TraceLog("MsgSync: got " + payload.GetType() + ", syncid: " + wrapper_msg.SyncId);

                //find waiter
                RpcWaiter w = null;
                lock (RpcPending)
                    if (RpcPending.TryGetValue(syncId, out w))
                    {
                        RpcPending.Remove(syncId);
                    }                              //remove if found

                //set result and wake
                if (w != null)
                {
                    lock (w)
                    {
                        w.Response = payload;
                        Monitor.Pulse(w);
                        return(true);
                    }
                }
                else
                {
                    DebugEx.TraceError("Could not find MsgSync waiter from " + payload.GetType() + " with syncId=" + syncId);
                }
            }
            return(false);
        }
Пример #3
0
        public override bool Save()
        {
            if (string.IsNullOrWhiteSpace(this.Filename))
            {
                return(false);
            }

            try
            {
                String cfg = JsonConvert.SerializeObject(this, Formatting.Indented);
#if NETFX
                File.WriteAllText(Filename, cfg);
                return(true);
#elif UNIVERSAL
                var ss = new Tools.StorageService(false);
                return(ss.SaveFile(Filename, cfg).GetResults());
#endif
            }
            catch (Exception ex)
            {
                DebugEx.TraceLog("Error: Failed to write configFile {0}", ex.Message);
                return(false);
            }
        }
Пример #4
0
        //------------------------------------------------------------------------------------------------------------------------
        public static bool SingleValueConvert(object value, Type toType, out object result)
        {
            result = null;
            //try convert
            try
            {
                //if nullable extract wrapped type
#if NETFX
                var isNullable = toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable <>);
#elif UNIVERSAL
                var isNullable = toType.GetTypeInfo().IsGenericType&& toType.GetGenericTypeDefinition() == typeof(Nullable <>);
#endif
                if (isNullable)
                {
                    toType = toType.GenericTypeArguments[0];
                }

                try
                {
                    //get value type
                    var fromType        = value == null ? typeof(object) : value.GetType();
                    var ToTypeIsInteger = toType.IsInteger();
                    var ToTypeIsDecimal = toType.IsDecimal();
                    var ToTypeIsNumber  = ToTypeIsInteger || ToTypeIsDecimal;

                    //universal helpers
#if NETFX
                    var ToTypeInfo   = toType;
                    var FromTypeInfo = fromType;
#elif UNIVERSAL
                    var ToTypeInfo   = toType.GetTypeInfo();
                    var FromTypeInfo = fromType.GetTypeInfo();
#endif

                    //nothing to do?
                    if (fromType == toType)
                    {
                        result = value;
                        return(true);
                    }

                    //check for enums
                    if (ToTypeInfo.IsEnum && fromType != typeof(string) && toType.GetEnumUnderlyingType() != fromType)
                    {
                        //try to convert to target type
                        object convValue = null;
                        if (Convert(value, toType.GetEnumUnderlyingType(), out convValue))
                        {
                            value    = convValue?.ToStringInvariant();
                            fromType = typeof(string);
#if UNIVERSAL
                            FromTypeInfo = fromType.GetTypeInfo();
#endif
                        }
                    }

                    //check easy stuff
                    if (value != null && ToTypeInfo.IsAssignableFrom(FromTypeInfo))
                    {
                        result = value;
                        return(true);
                    }
#if NETFX
                    else if (value is string && typeof(IFillFromString).IsAssignableFrom(toType))
#elif UNIVERSAL
                    else if (value is string && typeof(IFillFromString).GetTypeInfo().IsAssignableFrom(ToTypeInfo))
#endif
                    {
                        var box = Activator.CreateInstance(toType) as IFillFromString;
                        box.FillFromString((string)value);
                        result = box;
                        return(true);
                    }

                    //special string cases
                    if (value is string)
                    {
                        var str = value as string;
                        if (str != null)
                        {
                            str = str.ToLowerInvariant().Trim();
                        }

                        //string->boolean cases
                        if (toType == typeof(Boolean))
                        {
                            bool   bv;
                            double fv;
                            Int64  iv;
                            if (str.TryParse(out bv))
                            {
                                result = bv;
                                return(true);
                            }
                            else if (str.TryParse(out fv))
                            {
                                result = fv != 0;
                                return(true);
                            }
                            else if (str.TryParse(out iv))
                            {
                                result = iv != 0;
                                return(true);
                            }
                            else
                            {
                                //could not parse to a bool, fallback to false
                                result = false;
                                //but allow callers to handle the failure on their own if they want to
                                return(false);
                            }
                        }

                        //special cases for string
                        if (!ToTypeInfo.IsEnum)
                        {
                            if (string.IsNullOrEmpty(str) && ToTypeInfo.IsPrimitive && toType != typeof(string))
                            {
                                fromType = typeof(bool);
                                value    = false;
                            }
                            else if (str == "true" || str == "false")
                            {
                                fromType = typeof(bool);
                                value    = str == "true" ? true : false;
                            }
                            else if (str == "yes" || str == "no")
                            {
                                fromType = typeof(bool);
                                value    = str == "yes" ? true : false;
                            }
                            else if (str == "on" || str == "off")
                            {
                                fromType = typeof(bool);
                                value    = str == "on" ? true : false;
                            }
                            else if (str == "enabled" || str == "disabled")
                            {
                                fromType = typeof(bool);
                                value    = str == "enabled" ? true : false;
                            }
                            else if (str == "enable" || str == "disable")
                            {
                                fromType = typeof(bool);
                                value    = str == "enable" ? true : false;
                            }
                            else if (str == "active" || str == "inactive")
                            {
                                fromType = typeof(bool);
                                value    = str == "active" ? true : false;
                            }
                            else if (str == "activate" || str == "deactivate")
                            {
                                fromType = typeof(bool);
                                value    = str == "activate" ? true : false;
                            }
                            else if (str == "activated" || str == "deactivated")
                            {
                                fromType = typeof(bool);
                                value    = str == "activated" ? true : false;
                            }
                        }

                        //nothing to do?
                        if (fromType == toType)
                        {
                            result = value;
                            return(true);
                        }

                        //number converter
                        if (ToTypeIsNumber)
                        {
                            double dv;
                            if (str.TryParse(out dv))
                            {
                                value    = dv;
                                fromType = typeof(double);
                            }
                        }
                    }

                    //custom converters
                    if (fromType == typeof(Boolean))
                    {
                        if (toType == typeof(float))
                        {
                            result = (bool)value ? 1f : 0f;
                            return(true);
                        }
                        else if (toType == typeof(byte))
                        {
                            result = (bool)value ? (byte)1 : (byte)0;
                            return(true);
                        }
                        else if (toType == typeof(sbyte))
                        {
                            result = (bool)value ? (sbyte)1 : (sbyte)0;
                            return(true);
                        }
                        else if (toType == typeof(double))
                        {
                            result = (bool)value ? 1d : 0d;
                            return(true);
                        }
                        else if (toType == typeof(decimal))
                        {
                            result = (bool)value ? (decimal)1 : (decimal)0;
                            return(true);
                        }
                        else if (toType == typeof(Int16))
                        {
                            result = (bool)value ? (Int16)1 : (Int16)0;
                            return(true);
                        }
                        else if (toType == typeof(Int32))
                        {
                            result = (bool)value ? (Int32)1 : (Int32)0;
                            return(true);
                        }
                        else if (toType == typeof(Int64))
                        {
                            result = (bool)value ? (Int64)1 : (Int64)0;
                            return(true);
                        }
                        else if (toType == typeof(UInt16))
                        {
                            result = (bool)value ? (UInt16)1 : (UInt16)0;
                            return(true);
                        }
                        else if (toType == typeof(UInt32))
                        {
                            result = (bool)value ? (UInt32)1 : (UInt32)0;
                            return(true);
                        }
                        else if (toType == typeof(UInt64))
                        {
                            result = (bool)value ? (UInt64)1 : (UInt64)0;
                            return(true);
                        }
                        else if (toType == typeof(string))
                        {
                            result = (bool)value ? "True" : "False";
                            return(true);
                        }
                        else
                        {
                            result = null;
                            return(false);
                        }
                    }

                    //if input is null then give null back
                    if (value == null)
                    {
#if NETFX
                        result = ToTypeInfo.IsClass || toType.IsInterface ? null : Activator.CreateInstance(toType);
#elif UNIVERSAL
                        result = ToTypeInfo.IsClass || ToTypeInfo.IsInterface ? null : Activator.CreateInstance(toType);
#else
#error unkown platform
#endif
                        return(true);
                    }

#if NETFX
                    //try forward convert
                    {
                        var convValue = TypeDescriptor.GetConverter(fromType);
                        if (convValue.CanConvertTo(toType))
                        {
                            result = convValue.ConvertTo(null, System.Globalization.CultureInfo.InvariantCulture, value, toType);

                            //special object->string case (use json if objects ToString is the default typename)
                            if (fromType.IsClass && toType == typeof(string) && (result as string) == fromType.FullName)
                            {
#if NEWTONSOFT
                                result = value.ToJSON();
#endif
                            }

                            return(true);
                        }
                    }

                    //try the other way around
                    {
                        var convType = TypeDescriptor.GetConverter(toType);
                        if (convType.CanConvertFrom(fromType))
                        {
                            //try the other way around
                            result = convType.ConvertFrom(null, System.Globalization.CultureInfo.InvariantCulture, value);
                            return(true);
                        }
                    }
#endif

                    //last attempt
                    try
                    {
                        result = System.Convert.ChangeType(value, toType);
                        //special object->string case (use json if objects ToString is the default typename)
                        if (FromTypeInfo.IsClass && toType == typeof(string) && (result as string) == fromType.FullName)
                        {
#if NEWTONSOFT
                            result = value.ToJSON();
#endif
                        }

                        return(true);
                    }
                    catch { }

                    //string<->object special case using json
                    if (fromType == typeof(string) && ToTypeInfo.IsClass)
                    {
#if NEWTONSOFT
                        try
                        {
                            var trimmedStr = (value as string).Trim();
                            if (trimmedStr.Length > 1 &&
                                (trimmedStr.StartsWithInvariant("{", true) || trimmedStr.StartsWithInvariant("[", true)) &&
                                (trimmedStr.EndsWithInvariant("}", true) || trimmedStr.EndsWithInvariant("]", true)))
                            {
                                result = trimmedStr.FromJSON(toType);
                                if (result != null && result.GetType() == toType)
                                {
                                    return(true);
                                }
                                else
                                {
                                    result = null;
                                }
                            }
                        }
                        catch { }
#endif
                    }


                    //failed
                    result = null;
                    return(false);
                }
                finally
                {
                    //re-wrap with nullable (not sure if this is needed, because from debugger it will not do it anyway and c# will handle it internally.. but what-the-heck)
                    if (isNullable)
                    {
                        var nullableType = typeof(Nullable <>).MakeGenericType(toType);
                        try { result = Activator.CreateInstance(nullableType, new object[] { result }); } catch { }
                    }
                }
            }
            catch (Exception ex) { DebugEx.TraceLog(ex, "Convert Error"); result = null; return(false); } //pokemon exception handler
        }
Пример #5
0
        //------------------------------------------------------------------------------------------------------------------------
        public virtual Trsp SendRequest <Trsp>(T wrapper_msg, object request, TimeSpan?timeout = null, bool auto_json = false)
        {
            //null check
            if (wrapper_msg == null)
            {
                DebugEx.Assert("Null wrapper detected");
                return(default(Trsp));
            }

            try
            {
                //create synchronization id
                var syncId = GetNewSyncId();

                //create waiter
                var w = new RpcWaiter();
                lock (RpcPending)
                    RpcPending.Add(syncId, w);

                //create wrapper message
                try
                {
                    wrapper_msg.IsRequest = true;
                    wrapper_msg.SyncId    = syncId;
                    wrapper_msg.Payload   = request?.ToJSON();
                }
                catch (Exception ex)
                {
                    DebugEx.Assert(ex, "msg wrapper create failed");
                    return(default(Trsp));
                }


                //Send request and wait for response
                bool failed = false;
                lock (w)
                {
                    DebugEx.TraceLog("MsgSync: sending " + request?.GetType() + ", syncid: " + wrapper_msg.SyncId);
                    PublishFunc?.Invoke(wrapper_msg, request);
                    //wait for response
#if DEBUG
                    Monitor.Wait(w);
#else
                    if (timeout.HasValue)
                    {
                        if (timeout.Value == TimeSpan.Zero)
                        {
                            Monitor.Wait(w); //if explicitly zero timespan, wait forever
                        }
                        else
                        {
                            Monitor.Wait(w, timeout.Value);
                        }
                    }
                    else
                    {
                        //if no value given, wait for default msec
                        Monitor.Wait(w, DefaultRPCTimeout);
                    }
#endif
                    if (w.Response == null)
                    {
                        failed = true;
                    }
                }
                if (failed)
                {
                    lock (RpcPending)
                        RpcPending.Remove(syncId); //remove if failed to receive within time limit
                }
                //give response back
                if (w.Response != null)
                {
                    if (w.Response is string && auto_json)
                    {
                        var rsp_str = w.Response as string;
                        if ((rsp_str.StartsWith("{") && rsp_str.EndsWith("}")) ||
                            (rsp_str.StartsWith("[") && rsp_str.EndsWith("]")))
                        {
                            return((Trsp)rsp_str.FromJSON(type: typeof(Trsp)));
                        }
                    }
                    else
                    {
                        return((Trsp)w.Response);
                    }
                }
                return(default(Trsp));
            }
            catch (Exception ex)
            {
                DebugEx.TraceErrorException(ex);
                return(default(Trsp));
            }
        }
Пример #6
0
        public static void StartTest()
        {
            var       evr        = new YEventRouter();
            const int iterations = 1000000;
            //TimeSpan total_derived = TimeSpan.Zero;
            //TimeSpan total_direct = TimeSpan.Zero;

            Stopwatch watch = new Stopwatch();
            int       g     = 0;

            //add 2 event handlers
            DebugEx.TraceLog("Adding handler1a/b and handler2");
            evr.AddEventHandler <Payload1>((s, i, e) =>
            {
                g++;
            }, 5);
            //evr.AddEventHandler<Payload1>(Handler1b);
            evr.AddEventHandler <Payload2>((s, i, e) =>
            {
                g++;
            }, 6);

            //evr.AddEventHandler<Payload2>((s, i, e) =>
            //    {
            //        DebugEx.TraceLog("HANDLER2 " + e + " called");

            //        //create new handler for this Type route (altering the internal hashset)
            //        evr.AddEventHandler<Payload2>((x, y, z) => DebugEx.TraceLog("HANDLER2 created from within handler"));

            //        //create new handler for a new Type route
            //        evr.AddEventHandler<Payload2_3>((x, y, z) => DebugEx.TraceLog("HANDLER2_3 created from within handler"));
            //    });
            //evr.AddEventHandler<Payload2_2>((s, i, e) => DebugEx.TraceLog("DERIVED HANDLER2_2 " + e + " called"));

            //scale cpu clock up
            for (int i = 0; i < iterations; i++)
            {
                evr.TriggerEvent <Payload2_2>(null, new Payload2_2()
                {
                    b = "Payload2_2"
                });
            }

            //trigger events
            DebugEx.TraceLog("Trigger events");
            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                evr.TriggerEvent <Payload2_2>(null, new Payload2_2()
                {
                    b = "Payload2_2"
                });
            }
            watch.Stop();
            var total_derived = watch.ElapsedMilliseconds;

            DebugEx.TraceLog("Total time for " + g + " derived iterations = " + total_derived);

            g = 0;
            watch.Restart();
            for (int i = 0; i < iterations; i++)
            {
                evr.TriggerEvent <Payload2>(null, new Payload2()
                {
                    b = "Payload1"
                });
            }

            watch.Stop();
            var total_direct = watch.ElapsedMilliseconds;

            DebugEx.TraceLog("Total time for " + g + " direct iterations = " + total_direct);


            evr.TriggerEvent <Payload2>(null, new Payload2()
            {
                b = "Payload2"
            });
            evr.TriggerEvent <Payload1>(null, new Payload1()
            {
                a = "Payload1", c = "newtest"
            });
            Task.Delay(3000).Wait();
            evr.TriggerEvent <Payload1>(null, new Payload1()
            {
                a = "Payload1", c = "newtest"
            });
            evr.TriggerEvent <Payload2>(null, new Payload2()
            {
                b = "Payload2"
            });

            //remove handler1b
            DebugEx.TraceLog("removing handler1b");
            evr.RemoveEventHandler <Payload1>(Handler1b);

            //trigger same events
            DebugEx.TraceLog("Trigger events");
            evr.TriggerEvent <Payload1>(null, new Payload1()
            {
                a = "Payload1", c = "newtest"
            });
            evr.TriggerEvent <Payload2>(null, new Payload2()
            {
                b = "Payload2"
            });
            Task.Delay(3000).Wait();
            evr.TriggerEvent <Payload1>(null, new Payload1()
            {
                a = "Payload1", c = "newtest"
            });
            Task.Delay(3000).Wait();
            evr.TriggerEvent <Payload1>(null, new Payload1()
            {
                a = "Payload1", c = "newtest"
            });
            evr.TriggerEvent <Payload2>(null, new Payload2()
            {
                b = "Payload2"
            });

            DebugEx.TraceLog("END");
        }
Пример #7
0
 public static void Handler1b(object sender, YEventRouter.EvInfo info, object ev)
 {
     DebugEx.TraceLog("HANDLER1b " + ev + " called");
 }