public string GetAllMessages(Exception exception)
        {
            string result = ExceptionExtension.GetAllMessages(exception);

            return(result);
            // TODO: add assertions to method ExceptionExtensionTest.GetAllMessages(Exception)
        }
        // Add a SocketAsyncEventArg instance to the pool
        //
        //The "item" parameter is the SocketAsyncEventArgs instance
        // to add to the pool
        public void Push(SocketAsyncEventArgsProxy item)
        {
            ExceptionExtension.ArgumentNullExceptionIfNull(item, "item");

            item.Reset();
            _pools.Push(item);
        }
Beispiel #3
0
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="ent"></param>
        /// <param name="isSave">是否保存到数据库,如果为false,则没有保存数据库,必须执行SaveChanges()
        /// 来实现事务</param>
        /// <returns></returns>
        public int Delete(TEntity ent, bool isSave = true)
        {
            ExceptionExtension.IsNull(ent, "ent");

            _entites.Remove(ent);
            return(isSave?_db.SaveChanges():0);
        }
Beispiel #4
0
        public async Task <string> NRequest(HttpMethod method
                                            , Uri uri
                                            , Option <string> data
                                            , Option <HttpRequestOption> config)
        {
            var req = new HttpRequestMessage(method, uri);

            data.Then(s =>
            {
                req.Content = new StringContent(s);
                req.Content.Headers.ContentType = JsonMimeType;
            });
            config.Then(ApplyConfig(req));

            HttpResponseMessage res;
            string text;

            try {
                res = await http.SendAsync(req);

                text = await res.Content.ReadAsStringAsync();
            }
            catch (Exception ex) {
                throw ExceptionExtension.ChainError("HTTP invocation failed.", NetworkErrorCode, $"{nameof(TextHttp)}:{nameof(Request)}", uri.ToString())(ex);
            }

            return(res.IsSuccessStatusCode
                       ? text
                       : throw ExceptionExtension.CreateError(res.ReasonPhrase !, $"{HttpErrorCodePrefix}{(int) res.StatusCode}", uri.ToString(), text));
        }
Beispiel #5
0
        /// <summary>
        /// 批量删除(条件)
        /// </summary>
        /// <param name="where"></param>
        /// <param name="isSave">是否保存到数据库,如果为false,则没有保存数据库,必须执行SaveChanges()
        /// 来实现事务</param>
        /// <returns></returns>
        public int Delete(System.Linq.Expressions.Expression <Func <TEntity, bool> > where, bool isSave = true)
        {
            ExceptionExtension.IsNull(where, "where");

            var ents = _entites.Where(where).ToList();

            return(isSave?_db.SaveChanges():0);
        }
Beispiel #6
0
        /// <summary>
        /// 批量更新条件相同的实体
        /// </summary>
        /// <param name="where">需要更新的实体条件</param>
        /// <param name="isSave">是否保存到数据库,如果为false,则没有保存数据库,必须执行SaveChanges()
        /// 来实现事务</param>
        /// <returns></returns>
        public int Update(System.Linq.Expressions.Expression <Func <TEntity, bool> > where,
                          bool isSave = true)
        {
            ExceptionExtension.IsNull(where, "where");

            var ents = _entites.Where(where).ToList();

            return(Update(ents, isSave));
        }
Beispiel #7
0
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ents"></param>
        /// <param name="isSave">是否保存到数据库,如果为false,则没有保存数据库,必须执行SaveChanges()
        /// 来实现事务</param>
        /// <returns></returns>
        public int Delete(IEnumerable <TEntity> ents, bool isSave = true)
        {
            ExceptionExtension.IsNull(ents, "ents");

            foreach (var ent in ents)
            {
                _entites.Remove(ent);
            }
            return(isSave?_db.SaveChanges():0);
        }
Beispiel #8
0
        public static async Task HandleFailedSynced(SyncFailedEventArgs e, IMessageBoxService messageBoxService, INavigationService navigationService)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }
            if (messageBoxService == null)
            {
                throw new ArgumentNullException(nameof(messageBoxService));
            }
            if (navigationService == null)
            {
                throw new ArgumentNullException(nameof(navigationService));
            }

            string message = e.Message ?? string.Empty;
            string details = null;

            if (e.Exception != null)
            {
                details = ExceptionExtension.BeautifyAsyncStacktrace(e.Exception.ToString());
            }

            if (!string.IsNullOrEmpty(message))
            {
                if (!string.IsNullOrEmpty(details))
                {
                    var result = await messageBoxService.ShowAsync(
                        StringResources.Sync_FailedMessage,
                        message,
                        new[] { StringResources.General_LabelOk, StringResources.General_LabelDetails });

                    if (result.ButtonIndex == 1)
                    {
                        details = string.Format("{0}\r\n{1}", message, details);
                        await messageBoxService.ShowAsync(StringResources.Message_Information, details);
                    }
                }
                else
                {
                    await messageBoxService.ShowAsync(StringResources.Message_Warning, message);
                }

                if (message.Equals(StringResources.Exchange_InvalidSyncKeyWorkaround))
                {
                    navigationService.FlyoutTo(ViewLocator.SyncAdvancedSyncSettingsPage);
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="ent"></param>
        /// <param name="isSave">是否保存到数据库,如果为false,则没有保存数据库,必须执行SaveChanges()
        /// 来实现事务</param>
        /// <returns></returns>
        public int Update(TEntity ent, bool isSave = true)
        {
            ExceptionExtension.IsNull(ent, "ent");

            var state = _db.Entry <TEntity>(ent).State;

            if (state == EntityState.Detached)
            {
                _entites.Attach(ent);
            }

            _db.Entry <TEntity>(ent).State = EntityState.Modified;

            return(isSave == true?_db.SaveChanges() : 0);
        }
Beispiel #10
0
        /// <summary>
        /// 批量更新多个实体
        /// </summary>
        /// <param name="ents"></param>
        /// <param name="isSave">是否保存到数据库,如果为false,则没有保存数据库,必须执行SaveChanges()
        /// 来实现事务</param>
        /// <returns></returns>
        public int Update(IEnumerable <TEntity> ents, bool isSave = true)
        {
            ExceptionExtension.IsNull(ents, "ents");

            foreach (var ent in ents)
            {
                var state = _db.Entry <TEntity>(ent).State;
                if (state == EntityState.Detached)
                {
                    _entites.Attach(ent);
                }

                _db.Entry <TEntity>(ent).State = EntityState.Modified;
            }

            return(isSave == true?_db.SaveChanges() : 0);
        }
Beispiel #11
0
        private async void SuggestExceptionEmail(Exception e, string page)
        {
            var service         = Ioc.Resolve <IMessageBoxService>();
            var platformService = Ioc.Resolve <IPlatformService>();

            TrackingManagerHelper.Exception(e, "Crash handler");

            var result = await service.ShowAsync(StringResources.General_LabelError, StringResources.Crash_MessageContent, DialogButton.YesNo);

            if (result == DialogResult.Yes)
            {
                var builder = new StringBuilder();

                builder.AppendLine("IMPORTANT: Please give details about the context of this error");
                builder.AppendLine();
                builder.AppendLine();

                builder.Append(GetDiagnosticsInformation(page));

                builder.AppendLine();
                builder.AppendLine();

                builder.AppendLine($"Exception: {e.Message}");
                builder.AppendLine($"Stacktrace: {ExceptionExtension.BeautifyAsyncStacktrace(e.StackTrace)}");

                if (e is AggregateException)
                {
                    var aggregateException = (AggregateException)e;
                    foreach (var innerException in aggregateException.InnerExceptions)
                    {
                        builder.AppendLine($"   Exception: {innerException.Message}");
                        builder.AppendLine($"   Stacktrace: {ExceptionExtension.BeautifyAsyncStacktrace(innerException.StackTrace)}");
                    }
                }

                await platformService.SendDiagnosticEmailAsync("2Day for Windows Error Report", builder.ToString());
            }
        }
Beispiel #12
0
        /// <summary>
        /// Remove the device by deleting it from the Registry.
        /// </summary>
        /// <param name="device">The device address.</param>
        /// <returns>Whether the device is deleted -- it is no longer a remembered device.
        /// </returns>
        internal static bool DeleteKnownDevice(BluetoothAddress device)
        {
            string itemName = GetWidcommDeviceKeyName(device);

            using (RegistryKey rkDevices = Registry.LocalMachine.OpenSubKey(DevicesRegPath, true)) {
                using (RegistryKey theOne = rkDevices.OpenSubKey(itemName, false)) {
                    if (theOne == null) // Isn't present.
                    {
                        return(true);
                    }
                }
                try {
                    rkDevices.DeleteSubKeyTree(itemName);
                    return(true);
                } catch (System.Security.SecurityException ex) {
                    Utils.MiscUtils.Trace_WriteLine("DeleteKnownDevice DeleteSubKeyTree(" + itemName + "): "
                                                    + ExceptionExtension.ToStringNoStackTrace(ex));
                } catch (UnauthorizedAccessException ex) {
                    Utils.MiscUtils.Trace_WriteLine("DeleteKnownDevice DeleteSubKeyTree(" + itemName + "): "
                                                    + ExceptionExtension.ToStringNoStackTrace(ex));
                }
                return(false);
            }
        }
Beispiel #13
0
        private static void GetStacks_inLock()
        {
            List_BluetoothFactory list   = new List_BluetoothFactory();
            List_Exception        errors = new List_Exception();
            var stacks = new System.Collections.Generic.List <string>(
                BluetoothFactoryConfig.KnownStacks);

            TraceWriteLibraryVersion();
            foreach (string factoryName in stacks)
            {
                try {
                    Type t = Type.GetType(factoryName, true);
                    Debug.Assert(t != null, string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                          "Expected GetType to throw when type not found: '{0}'", factoryName));
                    object tmp = Activator.CreateInstance(t);
                    Debug.Assert(tmp != null, "Expect all failures to throw rather than return null.");
                    IBluetoothFactoryFactory ff = tmp as IBluetoothFactoryFactory;
                    if (ff == null)
                    {
                        list.Add((BluetoothFactory)tmp);
                    }
                    else     // BluetoothFactoryFactory!
                    {
                        IList_BluetoothFactory multiple = ff.GetFactories(errors);
                        if (multiple != null)
                        {
                            Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                          "BluetoothFactoryFactory '{0}' supplied {1} items.",
                                                          ff.GetType().AssemblyQualifiedName, multiple.Count));
                            list.AddRange(multiple);
                        }
                        else
                        {
                            Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                          "BluetoothFactoryFactory '{0}' returned null.", ff.GetType().AssemblyQualifiedName));
                        }
                    }
                    if (BluetoothFactoryConfig.OneStackOnly)
                    {
                        break;
                    }
                } catch (Exception ex) {
                    if (ex is System.Reflection.TargetInvocationException)
                    {
                        Debug.Assert(ex.InnerException != null, "We know from the old }catch(TIEX){throw ex.InnerEx;} that this is non-null");
                        ex = ex.InnerException;
                    }
                    errors.Add(ex);
                    string msg = string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                               "Exception creating factory '{0}, ex: {1}", factoryName, ex);
                    if (BluetoothFactoryConfig.ReportAllErrors)
                    {
                        Utils.MiscUtils.Trace_Fail(msg);  // (No Trace.Fail on NETCF).
                    }
                    Debug.WriteLine(msg);
                }
            }//for
            if (list.Count == 0)
            {
                if (!BluetoothFactoryConfig.ReportAllErrors)   // Have been reported above.
                {
                    foreach (Exception ex in errors)
                    {
                        string info = ExceptionExtension.ToStringNoStackTrace(ex);
                        Utils.MiscUtils.Trace_WriteLine(info);
                    }
                }
#if !NO_WIDCOMM
                // Special case Widcomm -- report if stacks seems there, but not our DLL.
                Exception wcNoInterfaceDll = null;
                try {
                    wcNoInterfaceDll = Widcomm.WidcommBtIf.IsWidcommStackPresentButNotInterfaceDll();
                } catch (Exception ex) {
                    // Maybe a P/Invoke exception calling GetModuleHandle
                    if (Environment.OSVersion.Platform.ToString().StartsWith("Win", StringComparison.Ordinal))
                    {
                        // Don't complain in Linux etc.
                        Utils.MiscUtils.Trace_WriteLine("Exception in IsWidcommStackPresentButNotInterfaceDll: " + ex);
                    }
                }
                if (wcNoInterfaceDll != null)
                {
                    throw wcNoInterfaceDll;
                }
#endif
                throw new PlatformNotSupportedException("No supported Bluetooth protocol stack found.");
            }
            else
            {
                SetFactories_inLock(list);
            }
            // result
#if !ANDROID
            Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                          "Num factories: {1}, Primary Factory: {0}",
                                          (s_factories == null ? "(null)" : s_factories[0].GetType().Name),
                                          (s_factories == null ? "(null)" : s_factories.Count.ToString())));
#endif
        }
Beispiel #14
0
        public SocketAsyncEventArgsPool(IEnumerable <SocketAsyncEventArgs> enumerator)
        {
            ExceptionExtension.ArgumentNullExceptionIfNull(enumerator, "enumerator");

            _pools = new ConcurrentStack <SocketAsyncEventArgs>(enumerator);
        }
Beispiel #15
0
        protected override async Task OnUpdate()
        {
            _dbContext.DetachEverything();

            // get events
            var log = await _ethereumReader.GatherPoolFreezerEvents(_lastBlock - 1, _lastBlock + _blocksPerRound, _confirmationsRequired);

            _lastBlock = log.ToBlock;

            Logger.Debug(
                (log.Events.Length > 0
                                        ? $"{log.Events.Length} request(s) found"
                                        : "Nothing found"
                ) + $" in blocks [{log.FromBlock} - {log.ToBlock}]"
                );

            if (IsCancelled())
            {
                return;
            }

            foreach (var v in log.Events)
            {
                if (IsCancelled())
                {
                    return;
                }
                Logger.Debug($"Trying to enqueue pool-freezer event with tx {v.TransactionId}");

                try {
                    var model = new DAL.Models.PoolFreezeRequest()
                    {
                        Status         = EmissionRequestStatus.Initial,
                        EthAddress     = v.Address,
                        EthTransaction = v.TransactionId,
                        Amount         = v.Amount.FromSumus(),
                        SumAddress     = v.SumusAddress,
                        SumTransaction = null,
                        TimeCreated    = DateTime.UtcNow,
                        TimeCompleted  = null,
                    };
                    _dbContext.PoolFreezeRequest.Add(model);
                    await _dbContext.SaveChangesAsync();

                    Logger.Information(
                        $"Pool-freezer event enqueued for tx {v.TransactionId}"
                        );
                } catch (Exception e) {
                    if (!ExceptionExtension.IsMySqlDuplicateException(e))
                    {
                        Logger.Error(e, $"Pool-freezer event failed with tx {v.TransactionId}");
                    }
                }

                ++_statProcessed;
            }

            // save last index to settings
            if (_lastSavedBlock != _lastBlock)
            {
                if (await _dbContext.SaveDbSetting(DbSetting.PoolFreezerHarvLastBlock, _lastBlock.ToString()))
                {
                    _lastSavedBlock = _lastBlock;
                    Logger.Debug($"Last block #{_lastBlock} saved to DB");
                }
            }
        }