public void LogExceptions(ExceptionEntry exception)
 {
     exception.MachineName = Dns.GetHostName();
     exception.IpAddress   = GetIpAddress();
     exception.DateTime    = DateTime.Now;
     WriteException(exception, "exception.txt");
 }
        public async Task <HttpResponseMessage> ProviderClientExceptionGeneral(ExceptionLogRequest clientException)
        {
            Services.Log.Warn("Mobile Provider Client General Exception [API]");
            Services.Log.Warn(clientException.Exception);

            ExceptionEntry newException = new ExceptionEntry()
            {
                Id            = Guid.NewGuid().ToString(),
                ExceptionText = clientException.Exception,
                Source        = "MOBILE PROVIDER CLIENT"
            };

            stranddContext context = new stranddContext();

            context.ExceptionLog.Add(newException);

            await context.SaveChangesAsync();

            string responseText;

            responseText = "Exception Logged in Service";

            //Return Successful Response
            return(this.Request.CreateResponse(HttpStatusCode.OK, responseText));
        }
示例#3
0
 public void AddExceptionEntry(ExceptionEntry exceptionEntry)
 {
     if (LogReceived != null && _clients.TryGetValue(OperationContext.Current.Channel, out var context))
     {
         ExceptionReceived(context, exceptionEntry);
     }
 }
        private ExceptionEntry CreateAndSaveExceptionEntryRecursive(AspNetDeployEntities entities, ExceptionEntry parentException, Exception exception)
        {
            ExceptionEntry exceptionEntry = new ExceptionEntry();

            exceptionEntry.Message    = exception.Message;
            exceptionEntry.Source     = exception.Source;
            exceptionEntry.StackTrace = exception.StackTrace;
            exceptionEntry.TypeName   = exception.GetType().FullName;
            entities.ExceptionEntry.Add(exceptionEntry);

            if (parentException != null)
            {
                parentException.InnerExceptionEntry = exceptionEntry;
            }

            foreach (ExceptionEntryData entryData in this.GetExceptionData(exception).Union(GetReflectionInfo(exception)).ToList())
            {
                entryData.ExceptionEntry = exceptionEntry;
                entities.ExceptionEntryData.Add(entryData);
            }

            if (exception.InnerException != null)
            {
                this.CreateAndSaveExceptionEntryRecursive(entities, exceptionEntry, exception.InnerException);
            }

            return(exceptionEntry);
        }
示例#5
0
        public async Task LogException(Exception exception, string data, guid serverId = 0)
        {
            if (exception is RateLimitedException)
            {
                return;
            }

            Console.WriteLine(exception.Message);
            Console.WriteLine(exception.StackTrace);
            Console.WriteLine($"{data} | ServerId:{serverId}");

            ExceptionEntry exceptionEntry = new ExceptionEntry()
            {
                Message  = exception.Message,
                Stack    = exception.StackTrace,
                Data     = data,
                DateTime = DateTime.UtcNow,
                ServerId = serverId,
                ShardId  = this.CurrentShard?.Id ?? 0
            };

            await this.Events.Exception(exceptionEntry);

            if (exception.InnerException != null && exception.Message != exception.InnerException.Message)
            {
                await LogException(exception.InnerException, "InnerException | " + data, serverId);
            }
        }
示例#6
0
        private void RecordException(AspNetDeployEntities entities, ExceptionEntry parentException, Exception exception)
        {
            ExceptionEntry exceptionEntry = new ExceptionEntry();

            exceptionEntry.Message    = exception.Message;
            exceptionEntry.Source     = exception.Source;
            exceptionEntry.StackTrace = exception.StackTrace;
            exceptionEntry.TypeName   = exception.GetType().FullName;
            entities.ExceptionEntry.Add(exceptionEntry);

            if (parentException != null)
            {
                parentException.InnerExceptionEntry = exceptionEntry;
            }
            else
            {
                AspNetDeployExceptionEntry aspNetDeployExceptionEntry = new AspNetDeployExceptionEntry();
                aspNetDeployExceptionEntry.TimeStamp      = DateTime.UtcNow;
                aspNetDeployExceptionEntry.ExceptionEntry = exceptionEntry;
                entities.AspNetDeployExceptionEntry.Add(aspNetDeployExceptionEntry);
            }

            if (exception.InnerException != null)
            {
                this.RecordException(entities, exceptionEntry, exception.InnerException);
            }

            entities.SaveChanges();
        }
示例#7
0
 public void AddError(ExceptionEntry entry)
 {
     Errors.Add(entry);
     OnErrorAdded(new ExceptionEntryEventArgs {
         ExceptionEntry = entry
     });
 }
示例#8
0
        private void AddEntry(ExceptionEntry entry)
        {
            var item = new ListViewItem(new[]
            {
                new ListViewItem.ListViewSubItem {
                    Text = listErrors.Items.Count.ToString() + 1
                },                                                                               // LFD
                new ListViewItem.ListViewSubItem {
                    Text = entry.Step.ToString()
                },                                                               // Step
                new ListViewItem.ListViewSubItem {
                    Text = entry.NameSafe
                },                                                        // Name
                new ListViewItem.ListViewSubItem {
                    Text = entry.DescriptionSafe
                },                                                               // Node
                new ListViewItem.ListViewSubItem {
                    Text = entry.Exception.GetType().Name
                },                                                                        // Exception
                new ListViewItem.ListViewSubItem {
                    Text = entry.Exception.ToString()
                },                                                                    // Exception
            }, 0);

            listErrors.Items.Add(item);
        }
示例#9
0
        public void Run(Engine renderingEngine, ProcessingTree <SwitchBase> processingTree)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();

            processingTree.CancellationTokenSource = tokenSource;

            Task.Run(() =>
            {
                Processor processor = null;
                try
                {
                    processor = new Processor(renderingEngine, tokenSource);


                    processingTree.IsActive = true;
                    processingTree.OnStarted();

                    do
                    {
                        processingTree.Process(processor, renderingEngine);
                    } while (processor.Restarting && !tokenSource.IsCancellationRequested);
                }
                catch (TaskCanceledException)
                {
                    processingTree.IsActive = false;
                    processingTree.OnFinished();
                }
                catch (Exception ex)
                {
                    if (processor != null)
                    {
                        ExceptionEntry entry = new ExceptionEntry {
                            Exception = ex, Step = processor.Step, Node = processor.CurrentNode, Tree = processingTree
                        };
                        processor.CurrentNode.Value.CleanUp(processor, processor.CurrentNode);
                        Errors.Add(entry);
                        OnErrorAdded(new ExceptionEntryEventArgs {
                            ExceptionEntry = entry
                        });
                    }
                }
                finally
                {
                    processingTree.IsActive = false;
                    processingTree.OnFinished();
                }
            }, tokenSource.Token);
        }
        public async Task LogException(Exception exception, string data, guid serverId = 0)
        {
            if ((exception is HttpException httpException && (int)httpException.HttpCode >= 500) || data.Contains("Error handling Dispatch"))
            {
                this.Monitoring.Error500s.Inc();
            }

            if ((exception is WebSocketClosedException websocketException))
            {
                data += $"\nCloseCode:{websocketException.CloseCode}\nReason:{websocketException.Reason}\nTarget:{websocketException.TargetSite}";
            }

            if (exception.Message == "Server requested a reconnect" ||
                exception.Message == "Server missed last heartbeat" ||
                exception.Message.Contains("Discord.PermissionTarget"))              //it's a spam
            {
                return;
            }

            Console.WriteLine(exception.Message);
            Console.WriteLine(exception.StackTrace);
            Console.WriteLine($"{data} | ServerId:{serverId}");

            if (exception is RateLimitedException || exception.Message.Contains("WebSocket connection was closed"))              //hack to not spam my logs
            {
                return;
            }

            ExceptionEntry exceptionEntry = new ExceptionEntry()
            {
                Type     = exception.GetType().ToString(),
                Message  = exception.Message,
                Stack    = exception.StackTrace,
                Data     = data,
                DateTime = DateTime.UtcNow,
                ServerId = serverId,
                ShardId  = this.CurrentShard?.Id ?? 0
            };

            await this.Events.Exception(exceptionEntry);

            if (exception.InnerException != null && exception.Message != exception.InnerException.Message)
            {
                await LogException(exception.InnerException, "InnerException | " + data, serverId);
            }
        }
示例#11
0
        public async Task LogException(Exception exception, string data, guid serverId = 0)
        {
            Console.WriteLine(exception.Message);
            Console.WriteLine(exception.StackTrace);
            Console.WriteLine(data);

            ExceptionEntry exceptionEntry = new ExceptionEntry()
            {
                Message  = exception.Message,
                Stack    = exception.StackTrace,
                Data     = data,
                ServerId = serverId,
                DateTime = DateTime.UtcNow
            };

            await this.Events.Exception(exceptionEntry);
        }
 private void WriteException(ExceptionEntry exceptionEntry, string fileType)
 {
     try
     {
         exceptionEntry.IsDebug = IsDebug();
         using (var txtWriter = File.AppendText(ExecutingAssemblyPath + "\\" + fileType))
         {
             txtWriter.WriteLine("==================== {0} ====================\n", DateTime.Now.ToString(CultureInfo.InvariantCulture));
             var result = JsonConvert.SerializeObject(exceptionEntry);
             result = result.Replace("{", "").Replace("}", "").Replace(",", " =|= \n");
             txtWriter.WriteLine("{0}", result);
             txtWriter.WriteLine("=============================================================\n\n");
         }
     }
     catch (Exception ex)
     {
         WriteException(new ExceptionEntry {
             Exception = ex.ToString()
         }, "exception.txt");
     }
 }
示例#13
0
        // TODO: Implement some kind of "copy to clipboard" functionality.

        #region Construction

        internal ExceptionBox(Window owner, Exception exception, String message, String caption)
        {
            this.InitializeComponent();

            base.Owner = owner;
            base.WindowStartupLocation = (base.Owner is null) ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner;
            base.ShowInTaskbar         = (base.Owner is null ? true : false);

            base.MinHeight = 450;
            base.MaxHeight = SystemParameters.WorkArea.Height;
            base.MinWidth  = 450;
            base.MaxWidth  = SystemParameters.WorkArea.Width;
            base.Height    = 450;
            base.Width     = 800;

            this.Message   = this.FixMessage(message);
            this.Exception = exception;
            base.Title     = this.FixCaption(caption);

            base.DataContext          = this;
            this.treeView.ItemsSource = new ObservableCollection <ExceptionEntry>(ExceptionEntry.FromException(this.Exception));
        }
示例#14
0
        private void RecordException(AspNetDeployEntities entities, ExceptionEntry parentException, IExceptionInfo lastException, MachinePublicationLog machinePublicationLog)
        {
            ExceptionEntry exceptionEntry = new ExceptionEntry();

            machinePublicationLog.Exception = exceptionEntry;
            exceptionEntry.Message          = lastException.Message;
            exceptionEntry.Source           = lastException.Source;
            exceptionEntry.StackTrace       = lastException.StackTrace;
            exceptionEntry.TypeName         = lastException.TypeName;
            entities.ExceptionEntry.Add(exceptionEntry);

            if (parentException != null)
            {
                parentException.InnerExceptionEntry = exceptionEntry;
            }
            else
            {
                AspNetDeployExceptionEntry aspNetDeployExceptionEntry = new AspNetDeployExceptionEntry();
                aspNetDeployExceptionEntry.TimeStamp      = DateTime.UtcNow;
                aspNetDeployExceptionEntry.ExceptionEntry = exceptionEntry;
                entities.AspNetDeployExceptionEntry.Add(aspNetDeployExceptionEntry);
            }

            foreach (IExceptionDataInfo exceptionDataInfo in lastException.ExceptionData)
            {
                ExceptionEntryData data = new ExceptionEntryData();
                data.ExceptionEntry = exceptionEntry;
                data.IsProperty     = exceptionDataInfo.IsProperty;
                data.Name           = exceptionDataInfo.Name;
                data.Value          = exceptionDataInfo.Value;
                entities.ExceptionEntryData.Add(data);
            }

            if (lastException.InnerException != null)
            {
                this.RecordException(entities, exceptionEntry, lastException.InnerException, machinePublicationLog);
            }
        }
示例#15
0
        public ExceptionEntry CreateExceptionEntry(Exception exception)
        {
            if (exception == null)
            {
                return(null);
            }
            var exceptionEntry = new ExceptionEntry();

            exceptionEntry.HResult = exception.HResult;
            if (exception.InnerException != null)
            {
                exceptionEntry.InnerException = CreateExceptionEntry(exception.InnerException);
            }
            exceptionEntry.Message    = exception.Message;
            exceptionEntry.Source     = exception.Source;
            exceptionEntry.StackTrace = exception.StackTrace;
            if (exception.TargetSite != null)
            {
                exceptionEntry.Method = exception.TargetSite.Name; // Method name
            }

            return(exceptionEntry);
        }
示例#16
0
        private Task InitCommands()
        {
            Command <TUser> newCommand = null;

// !global
            newCommand                     = new Command <TUser>("global");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display all teh numbers.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                StringBuilder shards      = new StringBuilder();
                GlobalContext dbContext   = GlobalContext.Create(this.DbConfig.GetDbConnectionString());
                Shard         globalCount = new Shard();
                foreach (Shard shard in dbContext.Shards)
                {
                    globalCount.ServerCount       += shard.ServerCount;
                    globalCount.UserCount         += shard.UserCount;
                    globalCount.MemoryUsed        += shard.MemoryUsed;
                    globalCount.ThreadsActive     += shard.ThreadsActive;
                    globalCount.MessagesTotal     += shard.MessagesTotal;
                    globalCount.MessagesPerMinute += shard.MessagesPerMinute;
                    globalCount.OperationsRan     += shard.OperationsRan;
                    globalCount.OperationsActive  += shard.OperationsActive;
                    globalCount.Disconnects       += shard.Disconnects;

                    shards.AppendLine(shard.GetStatsString());
                }

                string message = "Server Status: <http://status.botwinder.info>\n\n" +
                                 $"Global Servers: `{globalCount.ServerCount}`\n" +
                                 $"Global Members `{globalCount.UserCount}`\n" +
                                 $"Global Allocated data Memory: `{globalCount.MemoryUsed} MB`\n" +
                                 $"Global Threads: `{globalCount.ThreadsActive}`\n" +
                                 $"Global Messages received: `{globalCount.MessagesTotal}`\n" +
                                 $"Global Messages per minute: `{globalCount.MessagesPerMinute}`\n" +
                                 $"Global Operations ran: `{globalCount.OperationsRan}`\n" +
                                 $"Global Operations active: `{globalCount.OperationsActive}`\n" +
                                 $"Global Disconnects: `{globalCount.Disconnects}`\n" +
                                 $"\n**Shards: `{dbContext.Shards.Count()}`**\n\n" +
                                 $"{shards.ToString()}";

                await SendMessageToChannel(e.Channel, message);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !getServer
            newCommand                     = new Command <TUser>("getServer");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display some info about specific server with id/name, or owners id/username.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await SendMessageToChannel(e.Channel, "Requires parameters.");

                    return;
                }

                guid id;
                guid.TryParse(e.TrimmedMessage, out id);
                StringBuilder             response     = new StringBuilder();
                IEnumerable <ServerStats> foundServers = null;
                if (!(foundServers = ServerContext.Create(this.DbConfig.GetDbConnectionString()).ServerStats.Where(s =>
                                                                                                                   s.ServerId == id || s.OwnerId == id ||
                                                                                                                   s.ServerName.ToLower().Contains($"{e.TrimmedMessage.ToLower()}") ||
                                                                                                                   s.OwnerName.ToLower().Contains($"{e.TrimmedMessage.ToLower()}")
                                                                                                                   )).Any())
                {
                    await SendMessageToChannel(e.Channel, "Server not found.");

                    return;
                }

                if (foundServers.Count() > 5)
                {
                    response.AppendLine("__**Found more than 5 servers!**__\n");
                }

                foreach (ServerStats server in foundServers.Take(5))
                {
                    response.AppendLine(server.ToString());
                    response.AppendLine();
                }

                await SendMessageToChannel(e.Channel, response.ToString());
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !getInvite
            newCommand                     = new Command <TUser>("getInvite");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get an invite url with serverid.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                guid         id;
                ServerConfig foundServer = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    !guid.TryParse(e.TrimmedMessage, out id) ||
                    (foundServer = ServerContext.Create(this.DbConfig.GetDbConnectionString()).ServerConfigurations.FirstOrDefault(s => s.ServerId == id)) == null)
                {
                    await SendMessageToChannel(e.Channel, "Server not found.");

                    return;
                }

                if (string.IsNullOrEmpty(foundServer.InviteUrl))
                {
                    await SendMessageToChannel(e.Channel, "I don't have permissions to create this InviteUrl.");

                    return;
                }

                await SendMessageToChannel(e.Channel, foundServer.InviteUrl);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !maintenance
            newCommand                     = new Command <TUser>("maintenance");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Performe maintenance";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                await SendMessageToChannel(e.Channel, "Okay, this may take a while...");
                await LogMaintenanceAndExit();
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !restart
            newCommand                     = new Command <TUser>("restart");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Shut down the bot.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                await SendMessageToChannel(e.Channel, "bai");

                await Task.Delay(1000);

                Environment.Exit(0);
            };
            this.Commands.Add(newCommand.Id, newCommand);
            this.Commands.Add("shutdown", newCommand.CreateAlias("shutdown"));

// !getExceptions
            newCommand                     = new Command <TUser>("getExceptions");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a list of exceptions.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                StringBuilder response = new StringBuilder();
                if (string.IsNullOrEmpty(e.TrimmedMessage) || !int.TryParse(e.TrimmedMessage, out int n) || n <= 0)
                {
                    n = 5;
                }

                GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString());
                foreach (ExceptionEntry exception in dbContext.Exceptions.Skip(Math.Max(0, dbContext.Exceptions.Count() - n)))
                {
                    response.AppendLine(exception.GetMessage());
                }

                string responseString = response.ToString();
                if (string.IsNullOrWhiteSpace(responseString))
                {
                    responseString = "I did not record any errors :stuck_out_tongue:";
                }
                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !getException
            newCommand                     = new Command <TUser>("getException");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get an exception stack for specific ID.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                string         responseString = "I couldn't find that exception.";
                ExceptionEntry exception      = null;
                GlobalContext  dbContext      = GlobalContext.Create(this.DbConfig.GetDbConnectionString());
                if (!string.IsNullOrEmpty(e.TrimmedMessage) && int.TryParse(e.TrimmedMessage, out int id) && (exception = dbContext.Exceptions.FirstOrDefault(ex => ex.Id == id)) != null)
                {
                    responseString = exception.GetStack();
                }

                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !blacklist
            newCommand                     = new Command <TUser>("blacklist");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add or remove an ID to or from the blacklist.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                guid   id             = 0;
                string responseString = "Invalid parameters.";
                if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[1], out id))
                {
                    if (!e.Message.MentionedUsers.Any())
                    {
                        await SendMessageToChannel(e.Channel, responseString);

                        return;
                    }

                    id = e.Message.MentionedUsers.First().Id;
                }

                GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString());
                ServerStats   server    = ServerContext.Create(this.DbConfig.GetDbConnectionString()).ServerStats
                                          .FirstOrDefault(s => s.ServerId == id || s.OwnerId == id);
                switch (e.MessageArgs[0])
                {
                case "add":
                    if (dbContext.Blacklist.Any(b => b.Id == id))
                    {
                        responseString = "That ID is already blacklisted.";
                        break;
                    }

                    dbContext.Blacklist.Add(new BlacklistEntry()
                    {
                        Id = id
                    });
                    dbContext.SaveChanges();
                    responseString = server == null ? "Done." : server.ServerId == id ?
                                     $"I'll be leaving `{server.OwnerName}`'s server `{server.ServerName}` shortly." :
                                     $"All of `{server.OwnerName}`'s servers are now blacklisted.";
                    break;

                case "remove":
                    BlacklistEntry entry = dbContext.Blacklist.FirstOrDefault(b => b.Id == id);
                    if (entry == null)
                    {
                        responseString = "That ID was not blacklisted.";
                        break;
                    }

                    dbContext.Blacklist.Remove(entry);
                    dbContext.SaveChanges();
                    responseString = server == null ? "Done." : server.ServerId == id ?
                                     $"Entry for `{server.OwnerName}`'s server `{server.ServerName}` was removed from the balcklist." :
                                     $"Entries for all `{server.OwnerName}`'s servers were removed from the blacklist.";
                    break;

                default:
                    responseString = "Invalid keyword.";
                    break;
                }

                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !subscriber
            newCommand                     = new Command <TUser>("subscriber");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add or remove an ID to or from the subscribers, use with optional bonus or premium parameter.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                guid   id             = 0;
                string responseString = "Invalid parameters.";
                if (e.MessageArgs == null || e.MessageArgs.Length < 2 ||
                    !guid.TryParse(e.MessageArgs[1], out id))
                {
                    if (!e.Message.MentionedUsers.Any())
                    {
                        await SendMessageToChannel(e.Channel, responseString);

                        return;
                    }

                    id = e.Message.MentionedUsers.First().Id;
                }

                GlobalContext dbContext  = GlobalContext.Create(this.DbConfig.GetDbConnectionString());
                Subscriber    subscriber = dbContext.Subscribers.FirstOrDefault(s => s.UserId == id);
                switch (e.MessageArgs[0])                //Nope - mentioned users above mean that there is a parameter.
                {
                case "add":
                    if (subscriber == null)
                    {
                        dbContext.Subscribers.Add(subscriber = new Subscriber()
                        {
                            UserId = id
                        });
                    }

                    for (int i = 2; i < e.MessageArgs.Length; i++)
                    {
                        subscriber.HasBonus  = subscriber.HasBonus || e.MessageArgs[i] == "bonus";
                        subscriber.IsPremium = subscriber.IsPremium || e.MessageArgs[i] == "premium";
                    }

                    dbContext.SaveChanges();
                    responseString = "Done.";
                    break;

                case "remove":
                    if (subscriber == null)
                    {
                        responseString = "That ID was not a subscriber.";
                        break;
                    }

                    responseString = "Done.";
                    if (e.MessageArgs.Length < 3)
                    {
                        dbContext.Subscribers.Remove(subscriber);
                        break;
                    }

                    for (int i = 2; i < e.MessageArgs.Length; i++)
                    {
                        subscriber.HasBonus  = subscriber.HasBonus && e.MessageArgs[i] != "bonus";
                        subscriber.IsPremium = subscriber.IsPremium && e.MessageArgs[i] != "premium";
                    }

                    dbContext.SaveChanges();
                    break;

                default:
                    responseString = "Invalid keyword.";
                    break;
                }

                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !partner
            newCommand                     = new Command <TUser>("partner");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add or remove an ID to or from the partners, use with optional premium parameter.";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.OnExecute          += async e => {
                guid   id             = 0;
                string responseString = "Invalid parameters.";
                if (e.MessageArgs == null || e.MessageArgs.Length < 2 ||
                    !guid.TryParse(e.MessageArgs[1], out id))
                {
                    if (!e.Message.MentionedUsers.Any())
                    {
                        await SendMessageToChannel(e.Channel, responseString);

                        return;
                    }

                    id = e.Message.MentionedUsers.First().Id;
                }

                GlobalContext   dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString());
                PartneredServer partner   = dbContext.PartneredServers.FirstOrDefault(s => s.ServerId == id);
                switch (e.MessageArgs[0])                //Nope - mentioned users above mean that there is a parameter.
                {
                case "add":
                    if (partner == null)
                    {
                        dbContext.PartneredServers.Add(partner = new PartneredServer()
                        {
                            ServerId = id
                        });
                    }

                    if (e.MessageArgs.Length > 2)
                    {
                        partner.IsPremium = partner.IsPremium || e.MessageArgs[2] == "premium";
                    }

                    dbContext.SaveChanges();
                    responseString = "Done.";
                    break;

                case "remove":
                    if (partner == null)
                    {
                        responseString = "That ID was not a partner.";
                        break;
                    }

                    responseString = "Done.";
                    if (e.MessageArgs.Length < 3)
                    {
                        dbContext.PartneredServers.Remove(partner);
                        break;
                    }

                    if (e.MessageArgs.Length > 2)
                    {
                        partner.IsPremium = partner.IsPremium && e.MessageArgs[2] != "premium";
                    }

                    dbContext.SaveChanges();
                    break;

                default:
                    responseString = "Invalid keyword.";
                    break;
                }

                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !operations
            newCommand                     = new Command <TUser>("operations");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display info about all queued or running operations on your server.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                StringBuilder response      = new StringBuilder();
                bool          allOperations = IsGlobalAdmin(e.Message.Author.Id);

                response.AppendLine($"Total operations in the queue: `{this.CurrentOperations.Count}`");
                if (allOperations)
                {
                    response.AppendLine($"Currently allocated data Memory: `{(GC.GetTotalMemory(false) / 1000000f):#0.00} MB`");
                }

                response.AppendLine();
                lock (this.OperationsLock)
                {
                    foreach (Operation <TUser> op in this.CurrentOperations)
                    {
                        if (!allOperations && op.CommandArgs.Server.Id != e.Server.Id)
                        {
                            continue;
                        }

                        response.AppendLine(op.ToString());
                        if (allOperations)
                        {
                            response.AppendLine($"Server: `{op.CommandArgs.Server.Guild.Name}`\n" +
                                                $"ServerID: `{op.CommandArgs.Server.Id}`\n" +
                                                $"Allocated DataMemory: `{op.AllocatedMemoryStarted:#0.00} MB`\n");
                        }
                    }
                }

                string responseString = response.ToString();
                if (string.IsNullOrEmpty(responseString))
                {
                    responseString = "There are no operations running.";
                }

                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !cancel
            newCommand                     = new Command <TUser>("cancel");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Cancel queued or running operation - use in the same channel, and with the name of the command as parameter. (nuke, archive, etc...)";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                string            responseString = "Operation not found.";
                Operation <TUser> operation      = null;

                if (!string.IsNullOrEmpty(e.TrimmedMessage) &&
                    (operation = this.CurrentOperations.FirstOrDefault(
                         op => op.CommandArgs.Channel.Id == e.Channel.Id &&
                         op.CommandArgs.Command.Id == e.TrimmedMessage)) != null)
                {
                    responseString = "Operation canceled:\n\n" + operation.ToString();
                }

                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !say
            newCommand                     = new Command <TUser>("say");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Make the bot say something!";
            newCommand.RequiredPermissions = PermissionType.SubModerator;
            newCommand.DeleteRequest       = true;
            newCommand.IsBonusCommand      = true;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    return;
                }
                await SendMessageToChannel(e.Channel, e.TrimmedMessage);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !ping
            newCommand                     = new Command <TUser>("ping");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Measure how long does it take to receive a message and handle it as a command.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                TimeSpan time           = DateTime.UtcNow - Utils.GetTimeFromId(e.Message.Id);
                string   responseString = "`" + time.TotalMilliseconds.ToString("#00") + "`ms";
                await SendMessageToChannel(e.Channel, responseString);
            };
            this.Commands.Add(newCommand.Id, newCommand);

// !help
            newCommand                     = new Command <TUser>("help");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "PMs a list of Custom Commands for the server if used without a parameter. Use with a parameter to search for specific commands.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                StringBuilder response       = new StringBuilder("Please refer to the website documentation for the full list of features and commands: <http://botwinder.info/docs>\n\n");
                StringBuilder commandStrings = new StringBuilder();

                bool          isSpecific         = !string.IsNullOrWhiteSpace(e.TrimmedMessage);
                string        prefix             = e.Server.Config.CommandPrefix;
                List <string> includedCommandIds = new List <string>();
                int           count = 0;

                void AddCustomAlias(string commandId)
                {
                    List <CustomAlias> aliases = e.Server.CustomAliases.Values.Where(a => a.CommandId == commandId).ToList();
                    int aliasCount             = aliases.Count;

                    if (aliasCount > 0)
                    {
                        commandStrings.Append(aliasCount == 1 ? " **-** Custom Alias: " : " **-** Custom Aliases: ");
                        for (int i = 0; i < aliasCount; i++)
                        {
                            commandStrings.Append((i == 0 ? "`" : i == aliasCount - 1 ? " and `" : ", `") +
                                                  prefix + aliases[i].Alias + "`");
                        }
                    }
                    commandStrings.AppendLine();
                }

                void AddCommand(Command <TUser> cmd)
                {
                    commandStrings.AppendLine($"\n```diff\n{(cmd.CanExecute(this, e.Server, e.Channel, e.Message.Author as SocketGuildUser) ? "+" : "-")}" +
                                              $"  {prefix}{cmd.Id}```" +
                                              $" **-** {cmd.Description}");
                    if (cmd.Aliases != null && cmd.Aliases.Any())
                    {
                        int aliasCount = cmd.Aliases.Count;
                        commandStrings.Append(aliasCount == 1 ? " **-** Alias: " : " **-** Aliases: ");
                        for (int i = 0; i < aliasCount; i++)
                        {
                            commandStrings.Append((i == 0 ? "`" : i == aliasCount - 1 ? " and `" : ", `") +
                                                  prefix + cmd.Aliases[i] + "`");
                        }
                        commandStrings.AppendLine();
                    }

                    AddCustomAlias(cmd.Id);
                }

                void AddCustomCommand(CustomCommand cmd)
                {
                    commandStrings.AppendLine($"\n```diff\n{(cmd.CanExecute(this, e.Server, e.Channel, e.Message.Author as SocketGuildUser) ? "+" : "-")}" +
                                              $"  {prefix}{cmd.CommandId}```" +
                                              $" **-** {cmd.Description}");

                    AddCustomAlias(cmd.CommandId);
                }

                if (isSpecific)
                {
                    string expression = e.TrimmedMessage.Replace(" ", "|") + ")\\w*";
                    if (e.MessageArgs.Length > 1)
                    {
                        expression += "(" + expression;
                    }
                    Regex regex = new Regex($"\\w*({expression}", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(10f));

                    foreach (Command <TUser> cmd in e.Server.Commands.Values)
                    {
                        if (!cmd.IsHidden &&
                            cmd.RequiredPermissions != PermissionType.OwnerOnly &&
                            regex.Match(cmd.Id).Success)
                        {
                            Command <TUser> command = cmd;
                            if (cmd.IsAlias && e.Server.Commands.ContainsKey(cmd.ParentId))
                            {
                                command = e.Server.Commands[cmd.ParentId];
                            }

                            if (includedCommandIds.Contains(command.Id))
                            {
                                continue;
                            }

                            if (++count > 5)
                            {
                                break;
                            }

                            AddCommand(cmd);
                        }
                    }

                    foreach (CustomCommand cmd in e.Server.CustomCommands.Values)
                    {
                        if (regex.Match(cmd.CommandId).Success)                          //Chances are that it's gonna fail more often.
                        {
                            if (includedCommandIds.Contains(cmd.CommandId))
                            {
                                continue;
                            }

                            if (++count > 5)
                            {
                                break;
                            }

                            AddCustomCommand(cmd);
                        }
                    }

                    foreach (CustomAlias alias in e.Server.CustomAliases.Values)
                    {
                        if (regex.Match(alias.Alias).Success)                          //Chances are that it's gonna fail more often.
                        {
                            if (includedCommandIds.Contains(alias.CommandId))
                            {
                                continue;
                            }

                            if (++count > 5)
                            {
                                break;
                            }

                            if (e.Server.Commands.ContainsKey(alias.CommandId))
                            {
                                AddCommand(e.Server.Commands[alias.CommandId]);
                            }
                            else if (e.Server.CustomCommands.ContainsKey(alias.CommandId))
                            {
                                AddCustomCommand(e.Server.CustomCommands[alias.CommandId]);
                            }
                        }
                    }

                    if (count == 0)
                    {
                        response.AppendLine("I did not find any commands matching your search expression.");
                    }
                    else
                    {
                        if (count > 5)
                        {
                            response.AppendLine("I found too many commands matching your search expression. **Here are the first five:**");
                        }

                        response.Append(commandStrings.ToString());
                    }
                }
                else                 //Not specific - PM CustomCommands.
                {
                    foreach (CustomCommand cmd in e.Server.CustomCommands.Values)
                    {
                        if (includedCommandIds.Contains(cmd.CommandId))
                        {
                            continue;
                        }

                        if (++count > 5)
                        {
                            break;
                        }

                        AddCustomCommand(cmd);
                    }

                    response.AppendLine("I've PMed you the Custom Commands for this server.");
                    await e.Message.Author.SendMessageSafe(commandStrings.ToString());
                }

                await SendMessageToChannel(e.Channel, response.ToString());
            };
            this.Commands.Add(newCommand.Id, newCommand);

/*
 * // !command
 *                      newCommand = new Command<TUser>("command");
 *                      newCommand.Type = CommandType.Standard;
 *                      newCommand.Description = "";
 *                      newCommand.RequiredPermissions = PermissionType.OwnerOnly;
 *                      newCommand.OnExecute += async e => {
 *                              string responseString = "";
 *                              await SendMessageToChannel(e.Channel, responseString);
 *                      };
 *                      this.Commands.Add(newCommand.Id, newCommand);
 *
 */
            return(Task.CompletedTask);
        }
示例#17
0
        private void button1_Click(object sender, EventArgs e)
        {
            string[] directories = Directory.GetDirectories(".");

            foreach (string dir in directories)
            {
                if (!dir.Contains("svn") && !dir.Contains("Logs"))
                {
                    string[] zipFiles = Directory.GetFiles(dir);
                    foreach (string fileName in zipFiles)
                    {
                        var zf = new ZipFile(fileName);

                        if (zf.ContainsEntry("Logs/ApplicationLog.txt"))
                        {
                            if (Directory.Exists("Logs"))
                            {
                                Directory.Delete("Logs", true);
                            }

                            zf["Logs/ApplicationLog.txt"].Extract(".");
                            StreamReader reader;
                            if (zf.ContainsEntry("Logs/SoundException.txt"))
                            {
                                zf["Logs/SoundException.txt"].Extract(".");
                                reader = new StreamReader("Logs/SoundException.txt");
                            }
                            else
                            {
                                reader = new StreamReader("Logs/ApplicationLog.txt");
                            }

                            string line = "";

                            ExceptionEntry entry = new ExceptionEntry();

                            entry.Date = dir.ToString();
                            entry.Date = entry.Date.Remove(0, 2);
                            string year  = entry.Date.Substring(0, 4);
                            string month = entry.Date.Substring(4, 2);
                            string day   = entry.Date.Substring(6, 2);
                            entry.Date = year + "-" + month + "-" + day;

                            if (zf.ContainsEntry("Logs/SoundException.txt"))
                            {
                                bool   first     = true;
                                string firstLine = "";
                                while ((line = reader.ReadLine()) != null)
                                {
                                    if (first)
                                    {
                                        firstLine = line;
                                        first     = false;
                                    }
                                    if (line.Contains("Exception") || line.Contains("INVALID") || line.Contains("reference"))
                                    {
                                        while (line.StartsWith(" "))
                                        {
                                            line = line.Remove(0, 1);
                                        }

                                        entry.Exception = GetException(line);
                                        entry.Cause     = GetCause(line);

                                        bool foundStartTrace = false;
                                        int  index           = 4;

                                        while ((line = reader.ReadLine()) != null)
                                        {
                                            if ((line.Contains("   ") && !foundStartTrace))
                                            {
                                                foundStartTrace      = true;
                                                line                 = line.Remove(0, 5);
                                                entry.DirectLocation = line;
                                            }
                                            else if (foundStartTrace && (line.Contains(knownProjects[0]) || line.Contains(knownProjects[1]) || line.Contains(knownProjects[2]) || line.Contains(knownProjects[3])))
                                            {
                                                line = line.Remove(0, 5);
                                                entry.KnownLocation = line;
                                                break;
                                            }
                                        }
                                    }
                                    if (entry.Exception == null)
                                    {
                                        entry.Exception      = firstLine;
                                        entry.Cause          = "All info in exception field";
                                        entry.DirectLocation = "All info in exception field";
                                        entry.KnownLocation  = "All info in exception field";
                                    }
                                }
                            }
                            else
                            {
                                while ((line = reader.ReadLine()) != null)
                                {
                                    if (line.Contains("Exception"))
                                    {
                                        while (line.StartsWith(" "))
                                        {
                                            line = line.Remove(0, 1);
                                        }

                                        entry.Exception = GetException(line);
                                        entry.Cause     = GetCause(line);

                                        bool foundStartTrace = false;

                                        int index = 4;

                                        while ((line = reader.ReadLine()) != null)
                                        {
                                            //if (((line.Contains(" at ") || line.Contains(" en ") || line.Contains(" bei ") || line.Contains(" bij ") || line.Contains(" в ") || line.Contains(" w ") || line.Contains(" konum:") || line.Contains(" vid ") || line.Contains(" 在 ") || line.Contains(" v ") || line.Contains(" a ")) && !foundStartTrace))
                                            if (line.Contains("   ") && !foundStartTrace)
                                            {
                                                foundStartTrace      = true;
                                                line                 = line.Remove(0, 5);
                                                entry.DirectLocation = line;
                                            }
                                            else if (foundStartTrace && (line.Contains(knownProjects[0]) || line.Contains(knownProjects[1]) || line.Contains(knownProjects[2]) || line.Contains(knownProjects[3])))
                                            {
                                                line = line.Remove(0, 5);
                                                entry.KnownLocation = line;
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }

                            reader.Close();

                            dataGridView1.Rows.Add(new string[] { entry.Date, entry.Exception, entry.Cause, entry.KnownLocation, entry.DirectLocation });
                            entries.Add(entry);

                            //dataGridView1.Columns.Add(new DataGridViewColumn { a });
                            //propertyGrid1.SelectedObject = new List<ExceptionEntry>();
                            Directory.Delete("./Logs", true);
                        }
                    }
                }
            }
        }
示例#18
0
        private void button1_Click(object sender, EventArgs e)
        {
            string[] directories = Directory.GetDirectories(".");

            foreach (string dir in directories)
            {
                if (!dir.Contains("svn")&& !dir.Contains("Logs"))
                {
                    string[] zipFiles = Directory.GetFiles(dir);
                    foreach (string fileName in zipFiles)
                    {
                        var zf = new ZipFile(fileName);

                        if (zf.ContainsEntry("Logs/ApplicationLog.txt"))
                        {
                            if (Directory.Exists("Logs"))
                                Directory.Delete("Logs", true);

                            zf["Logs/ApplicationLog.txt"].Extract(".");
                            StreamReader reader;
                            if (zf.ContainsEntry("Logs/SoundException.txt"))
                            {
                                zf["Logs/SoundException.txt"].Extract(".");
                                reader = new StreamReader("Logs/SoundException.txt");
                            }
                            else
                                reader = new StreamReader("Logs/ApplicationLog.txt");

                            string line = "";

                            ExceptionEntry entry = new ExceptionEntry();

                            entry.Date = dir.ToString();
                            entry.Date = entry.Date.Remove(0, 2);
                            string year = entry.Date.Substring(0, 4);
                            string month = entry.Date.Substring(4, 2);
                            string day = entry.Date.Substring(6, 2);
                            entry.Date = year + "-" + month + "-" + day;

                            if (zf.ContainsEntry("Logs/SoundException.txt"))
                            {
                                bool first = true;
                                string firstLine = "";
                                while ((line = reader.ReadLine()) != null)
                                {
                                    if (first)
                                    {
                                        firstLine = line;
                                        first = false;
                                    }
                                    if (line.Contains("Exception") || line.Contains("INVALID") || line.Contains("reference"))
                                    {
                                        while (line.StartsWith(" "))
                                            line = line.Remove(0, 1);

                                        entry.Exception = GetException(line);
                                        entry.Cause = GetCause(line);

                                        bool foundStartTrace = false;
                                        int index = 4;

                                        while((line = reader.ReadLine()) != null)
                                        {
                                            if ((line.Contains("   ") && !foundStartTrace))
                                            {
                                                foundStartTrace = true;
                                                line = line.Remove(0, 5);
                                                entry.DirectLocation = line;
                                            }
                                            else if (foundStartTrace && (line.Contains(knownProjects[0]) || line.Contains(knownProjects[1]) || line.Contains(knownProjects[2]) || line.Contains(knownProjects[3])))
                                            {
                                                line = line.Remove(0, 5);
                                                entry.KnownLocation = line;
                                                break;
                                            }
                                        }
                                    }
                                    if (entry.Exception == null)
                                    {
                                        entry.Exception = firstLine;
                                        entry.Cause = "All info in exception field";
                                        entry.DirectLocation = "All info in exception field";
                                        entry.KnownLocation = "All info in exception field";
                                    }
                                }
                            }
                            else
                            {
                                while ((line = reader.ReadLine()) != null)
                                {
                                    if (line.Contains("Exception"))
                                    {
                                        while (line.StartsWith(" "))
                                            line = line.Remove(0, 1);

                                        entry.Exception = GetException(line);
                                        entry.Cause = GetCause(line);

                                        bool foundStartTrace = false;

                                        int index = 4;

                                        while ((line = reader.ReadLine()) != null)
                                        {
                                            //if (((line.Contains(" at ") || line.Contains(" en ") || line.Contains(" bei ") || line.Contains(" bij ") || line.Contains(" в ") || line.Contains(" w ") || line.Contains(" konum:") || line.Contains(" vid ") || line.Contains(" 在 ") || line.Contains(" v ") || line.Contains(" a ")) && !foundStartTrace))
                                            if(line.Contains("   ") && !foundStartTrace)
                                            {
                                                foundStartTrace = true;
                                                line = line.Remove(0, 5);
                                                entry.DirectLocation = line;
                                            }
                                            else if (foundStartTrace && (line.Contains(knownProjects[0]) || line.Contains(knownProjects[1]) || line.Contains(knownProjects[2]) || line.Contains(knownProjects[3])))
                                            {
                                                line = line.Remove(0, 5);
                                                entry.KnownLocation = line;
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }

                            reader.Close();

                            dataGridView1.Rows.Add(new string[] { entry.Date, entry.Exception, entry.Cause, entry.KnownLocation, entry.DirectLocation });
                            entries.Add(entry);

                            //dataGridView1.Columns.Add(new DataGridViewColumn { a });
                            //propertyGrid1.SelectedObject = new List<ExceptionEntry>();
                            Directory.Delete("./Logs", true);

                        }
                    }
                }
            }
        }