public static void Initialize() { ModuleMgr = ModuleManager.GetInstance(); PatchMgr = PatchManager.GetInstance(); RealmMgr = RealmManager.GetInstance(); SessionMgr = SessionManager.GetInstance(); }
static void Main(string[] args) { //LogManager.Assign(new SimpleLogManager<ConsoleLogger>()); // Module manager handles all modules in the server var moduleManager = new ModuleManager(); // Let's serve our downloaded files (Windows 7 users) var fileService = new DiskFileService("/", string.Format(@"C:\Users\{0}\Downloads", Environment.UserName)); // Create the file module and allow files to be listed. var module = new FileModule(fileService) {AllowFileListing = true}; // Add the module moduleManager.Add(module); moduleManager.Add(new MyModule()); moduleManager.Add(new MyModule2()); // And start the server. var server = new HttpServer(moduleManager); server.Start(IPAddress.Any, 0); Console.WriteLine("PORT " + server.LocalPort); //TrySendARequest(server); Console.ReadLine(); }
public void Start(int port) { try { // Module manager handles all modules in the server var moduleManager = new ModuleManager(); // Let's serve our downloaded files (Windows 7 users) var fileService = new DiskFileService("/", Settings.WebServerFolder); // Create the file module and allow files to be listed. var module = new FileModule(fileService) { ListFiles = false }; var routerModule = new RouterModule(); // Add the module //moduleManager.Add(module); moduleManager.Add(new WebServerModule()); //moduleManager.Add(new BodyDecodingModule(new UrlFormattedDecoder())); // And start the server. var server = new HttpServer(moduleManager); server.Start(IPAddress.Any, port); } catch (Exception ex) { Log.Error("Unable to start web server ", ex); } }
public Issue14_should_work_with_concurrent_requests() { var moduleManager = new ModuleManager(); moduleManager.Add(this); _server = new HttpServer(moduleManager); _server.Start(IPAddress.Any, 0); }
public Issue8CrashDuringDecodingOfHttpMessage() { _messageReceivedEvent = new ManualResetEvent(false); var moduleManager = new ModuleManager(); var myM = new MyModule(_messageReceivedEvent); moduleManager.Add(myM); _server = new HttpServer(moduleManager); _server.Start(IPAddress.Any, 8088); }
public void Run(IBackgroundTaskInstance taskInstance) { // Get the deferral and save it to local variable so that the app stays alive this.backgroundTaskDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += TaskCanceled; // Setup system logging logProvider.Add(systemDebugLogger, new NamespaceFilter("MicroServer")); LogManager.Provider = logProvider; ILogger Logger = LogManager.GetLogger<StartupTask>(); try { // Create Http server pipeline ModuleManager ModuleManager = new ModuleManager(); // Add the router module as the fist module to pipeline ModuleManager.Add(new RouterModule()); // Add the storage service module to pipeline //ModuleManager.Add(new FileModule(new StorageService("/", @"WebRoot"))); // Add the controller module to pipeline ModuleManager.Add(new ControllerModule()); // Add the error module as the last module to pipeline ModuleManager.Add(new ErrorModule()); // Create the http server HttpServer webServer = new HttpServer(ModuleManager); IAsyncAction asyncAction = ThreadPool.RunAsync( async (workItem) => { await webServer.StartAsync("80"); }); Logger.Info("Background task is running..."); } catch (Exception ex) { Debug.WriteLine("Exception in Run: {0}", ex.Message); } }
static void Main(string[] args) { //LogManager.Assign(new SimpleLogManager<ConsoleLogger>()); // Module manager handles all modules in the server var moduleManager = new ModuleManager(); // Let's serve our downloaded files (Windows 7 users) var fileService = new DiskFileService("/", string.Format(@"C:\Users\{0}\Downloads", Environment.UserName)); // Create the file module and allow files to be listed. var module = new FileModule(fileService) {ListFiles = true}; // Add the module moduleManager.Add(module); moduleManager.Add(new MyModule()); moduleManager.Add(new MyModule2()); // And start the server. var server = new HttpServer(moduleManager); server.Start(IPAddress.Any, 0); Console.WriteLine("PORT " + server.LocalPort); var request = @"GET /?signature=1dfea26808d632903549c69d78558fce1c418405&echostr=5867553698596935317×tamp=1365661332&nonce=1366146317 HTTP/1.0 User-Agent:Mozilla/4.0 Host:58.215.164.183 Pragma:no-cache Connection/Value:Keep-Alive "; var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Loopback, server.LocalPort); socket.Send(Encoding.UTF8.GetBytes(request)); var buffer = new byte[65535]; var len = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); var answer = Encoding.UTF8.GetString(buffer, 0, len); Console.WriteLine(answer); len = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); answer = Encoding.UTF8.GetString(buffer, 0, len); Console.WriteLine(answer); Console.ReadLine(); }
private void StartWebServer(int httpPort) { if (!isWebServerStarted) { //if (Log != null) // Log(this, "Starting web server... ", false, LogLevel.Normal); try { var moduleManager = new ModuleManager(); //string root = Path.GetPathRoot(Assembly.GetExecutingAssembly().Location); string root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\WebSite\"; var fileService = new DiskFileService("/", root); var module = new FileModule(fileService) { ListFiles = false }; // Add the module moduleManager.Add(new RootModule()); moduleManager.Add(module); //moduleManager.Add(new BodyDecodingModule(new UrlFormattedDecoder())); // And start the server. webServer = new HttpServer(moduleManager); webServer.Start(IPAddress.Any, httpPort); isWebServerStarted = true; } catch (Exception) { isWebServerStarted = false; } //if (Log != null) // Log(this, isWebServerStarted ? "Success." : "Failed.", true, isWebServerStarted ? LogLevel.Success : LogLevel.Error); } }
static void Main(string[] args) { LogManager.Assign(new SimpleLogManager<ConsoleLogger>()); // Module manager handles all modules in the server var moduleManager = new ModuleManager(); // Let's serve our downloaded files (Windows 7 users) var fileService = new DiskFileService("/", string.Format(@"C:\Users\{0}\Downloads", Environment.UserName)); // Create the file module and allow files to be listed. var module = new FileModule(fileService) {ListFiles = true}; // Add the module moduleManager.Add(module); moduleManager.Add(new BodyDecodingModule(new UrlFormattedDecoder())); moduleManager.Add(new MyModule()); // And start the server. var server = new HttpServer(moduleManager); server.Start(IPAddress.Any, 8080); Console.ReadLine(); }
public static void Initialize() { Module = ModuleManager.GetInstance(); Realm = RealmManager.GetInstance(); }
//Control public static void Init() { //See if there is a new version of the web files waiting before we start the server if (File.Exists(Core.RootFolder + @"\web.zip")) { if (Directory.Exists(Core.RootFolder + @"\web\")) Directory.Delete(Core.RootFolder + @"\web\", true); Directory.CreateDirectory(YAMS.Core.RootFolder + @"\web\"); AutoUpdate.ExtractZip(YAMS.Core.RootFolder + @"\web.zip", YAMS.Core.RootFolder + @"\web\"); File.Delete(Core.RootFolder + @"\web.zip"); } //create module manager to add all modules to admin webserver adminModuleManager = new ModuleManager(); //Handle the requests for static files var fileService = new DiskFileService("/assets/", YAMS.Core.RootFolder + "\\web\\assets\\"); var assets = new FileModule(fileService) { AllowFileListing = false }; adminModuleManager.Add(assets); //Handle requests to API adminModuleManager.Add(new Web.AdminAPI()); adminServerThread = new Thread(new ThreadStart(StartAdmin)); adminServerThread.Start(); //Open firewall ports if (Database.GetSetting("EnableOpenFirewall", "YAMS") == "true") { Networking.OpenFirewallPort(Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")), "Admin website"); } if (Database.GetSetting("EnablePortForwarding", "YAMS") == "true") { Networking.OpenUPnP(Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")), "Admin website", YAMS.Database.GetSetting("YAMSListenIP", "YAMS")); } if (Database.GetSetting("EnablePublicSite", "YAMS") == "true") { //Add any server specific folders publicModuleManager = new ModuleManager(); publicModuleManager.Add(assets); SqlCeDataReader readerServers = YAMS.Database.GetServers(); while (readerServers.Read()) { var intServerID = readerServers["ServerID"].ToString(); if (!Directory.Exists(Core.StoragePath + intServerID + "\\renders\\")) Directory.CreateDirectory(Core.StoragePath + intServerID + "\\renders\\"); publicModuleManager.Add(new FileModule(new DiskFileService("/servers/" + intServerID + "/renders/", Core.StoragePath + intServerID + "\\renders\\"))); if (!Directory.Exists(Core.StoragePath + intServerID + "\\backups\\")) Directory.CreateDirectory(Core.StoragePath + intServerID + "\\backups\\"); publicModuleManager.Add(new FileModule(new DiskFileService("/servers/" + intServerID + "/backups/", Core.StoragePath + intServerID + "\\backups\\"))); } //Handle requests to API publicModuleManager.Add(new Web.PublicAPI()); //publicServer.Add(HttpListener.Create(IPAddress.Any, Convert.ToInt32(YAMS.Database.GetSetting("PublicListenPort", "YAMS")))); publicServerThread = new Thread(new ThreadStart(StartPublic)); publicServerThread.Start(); //Open firewall ports if (Database.GetSetting("EnableOpenFirewall", "YAMS") == "true") { Networking.OpenFirewallPort(Convert.ToInt32(YAMS.Database.GetSetting("PublicListenPort", "YAMS")), "Public website"); } if (Database.GetSetting("EnablePortForwarding", "YAMS") == "true") { Networking.OpenUPnP(Convert.ToInt32(YAMS.Database.GetSetting("PublicListenPort", "YAMS")), "Public website", YAMS.Database.GetSetting("YAMSListenIP", "YAMS")); } } }
protected override void RegisterModule() { ModuleManager.Add <ModuleA>(); }
/// <summary> /// Bind the data. /// </summary> public void Bind() { if (!string.IsNullOrEmpty(ObjectType)) { pnlGrid.Visible = true; // Initialize strings btnAllTasks.Text = GetString("ImportExport.All"); btnNoneTasks.Text = GetString("export.none"); lblTasks.Text = GetString("Export.Tasks"); // Get object info GeneralizedInfo info = ModuleManager.GetReadOnlyObject(ObjectType); if (info != null) { gvTasks.RowDataBound += gvTasks_RowDataBound; plcGrid.Visible = true; codeNameColumnName = info.CodeNameColumn; displayNameColumnName = info.DisplayNameColumn; // Task fields TemplateField taskCheckBoxField = (TemplateField)gvTasks.Columns[0]; taskCheckBoxField.HeaderText = GetString("General.Export"); TemplateField titleField = (TemplateField)gvTasks.Columns[1]; titleField.HeaderText = GetString("Export.TaskTitle"); BoundField typeField = (BoundField)gvTasks.Columns[2]; typeField.HeaderText = GetString("general.type"); BoundField timeField = (BoundField)gvTasks.Columns[3]; timeField.HeaderText = GetString("Export.TaskTime"); // Load tasks int siteId = (SiteObject ? Settings.SiteId : 0); DataSet ds = ExportTaskInfoProvider.SelectTaskList(siteId, ObjectType, null, "TaskTime DESC", 0, null, CurrentOffset, CurrentPageSize, ref pagerForceNumberOfResults); // Set correct ID for direct page contol pagerElem.DirectPageControlID = ((float)pagerForceNumberOfResults / pagerElem.CurrentPageSize > 20.0f) ? "txtPage" : "drpPage"; // Call page binding event if (OnPageBinding != null) { OnPageBinding(this, null); } if (!DataHelper.DataSourceIsEmpty(ds) && (ValidationHelper.GetBoolean(Settings.GetSettings(ImportExportHelper.SETTINGS_TASKS), true))) { plcTasks.Visible = true; gvTasks.DataSource = ds; gvTasks.DataBind(); } else { plcTasks.Visible = false; } } else { plcGrid.Visible = false; } } else { pnlGrid.Visible = false; } }
void IModule.Install(ModuleManager manager) { _client = manager.Client; manager.CreateDynCommands("announce", PermissionLevel.ServerModerator, group => { group.CreateCommand("disable") .AddCheck((cmd, usr, chnl) => { if (_defaultAnnounceChannels.ContainsKey(chnl.Server.Id)) { return(_defaultAnnounceChannels[chnl.Server.Id].IsEnabled); } return(true); }) .Description("Disables bot owner announcements on this server.") .Do(async e => { if (_defaultAnnounceChannels.ContainsKey(e.Server.Id)) { _defaultAnnounceChannels[e.Server.Id].IsEnabled = false; } else { _defaultAnnounceChannels.TryAdd(e.Server.Id, new AnnounceChannelData(e.Server.DefaultChannel) { IsEnabled = false }); } await e.Channel.SendMessage("Disabled owner announcements for this server."); }); group.CreateCommand("enable") .AddCheck((cmd, usr, chnl) => { if (_defaultAnnounceChannels.ContainsKey(chnl.Server.Id)) { return(!_defaultAnnounceChannels[chnl.Server.Id].IsEnabled); } return(false); }) .Description("Enabled but owner announcements on this server.") .Do(async e => { _defaultAnnounceChannels[e.Server.Id].IsEnabled = true; await e.Channel.SendMessage("Enabled owner announcements for this server."); }); group.CreateCommand("channel") .Description("Sets the default channel of any announcements from the bot's owner.") .Parameter("channelname", ParameterType.Unparsed) .Do(async e => { string channelQuery = e.GetArg("channelname").ToLowerInvariant(); Channel channel = e.Server.TextChannels.FirstOrDefault(c => c.Name.ToLowerInvariant() == channelQuery); if (channel == null) { await e.Channel.SafeSendMessage($"Channel with the name of `{channelQuery}` wasn't found."); return; } AnnounceChannelData newVal = new AnnounceChannelData(channel); _defaultAnnounceChannels.AddOrUpdate(e.Server.Id, newVal, (k, v) => newVal); await e.Channel.SendMessage($"Set annoucement channel to `{channel.Name}`"); }); group.CreateCommand("current") .Description("Returns the current announcement channel.") .Do(async e => { StringBuilder builder = new StringBuilder("**Announcement channel**: "); if (!_defaultAnnounceChannels.ContainsKey(e.Server.Id)) { builder.Append(e.Server.DefaultChannel); } else { builder.Append(_defaultAnnounceChannels[e.Server.Id].Channel.Channel.Name); } await e.Channel.SafeSendMessage(builder.ToString()); }); group.CreateCommand("message") .MinPermissions((int)PermissionLevel.BotOwner) .Parameter("msg", ParameterType.Unparsed) .Do(async e => { string message = e.GetArg("msg"); foreach (Server server in _client.Servers) { AnnounceChannelData announceData; _defaultAnnounceChannels.TryGetValue(server.Id, out announceData); if (announceData == null) { await server.DefaultChannel.SafeSendMessage(message); } else { if (announceData.IsEnabled) { await _defaultAnnounceChannels[server.Id].Channel.Channel.SafeSendMessage(message); } } } }); }); manager.CreateDynCommands("autorole", PermissionLevel.ServerAdmin, group => { // commands that are available when the server doesnt have an auto role set on join. group.CreateGroup("", noSubGroup => { noSubGroup.AddCheck((cmd, usr, chnl) => !_joinedRoleSubs.ContainsKey(chnl.Server.Id)); noSubGroup.CreateCommand("create") .Description("Enables the bot to add a given role to newly joined users.") .Parameter("rolename", ParameterType.Unparsed) .Do(async e => { string roleQuery = e.GetArg("rolename"); Role role = e.Server.FindRoles(roleQuery).FirstOrDefault(); if (role == null) { await e.Channel.SafeSendMessage($"A role with the name of `{roleQuery}` was not found."); return; } _joinedRoleSubs.TryAdd(e.Server.Id, role.Id); await e.Channel.SafeSendMessage( $"Created an auto role asigned for new users. Role: {role.Name}"); }); }); // commands that are available when the server does have an auto role set on join. group.CreateGroup("", subGroup => { subGroup.AddCheck((cmd, usr, chnl) => (_joinedRoleSubs.ContainsKey(chnl.Server.Id))); subGroup.CreateCommand("destroy") .Description("Destoys the auto role assigner for this server.") .Do(e => RemoveAutoRoleAssigner(e.Server.Id, e.Channel)); subGroup.CreateCommand("role") .Parameter("rolename", ParameterType.Unparsed) .Description("Changes the role of the auto role assigner for this server.") .Do(async e => { string roleQuery = e.GetArg("rolename"); Role role = e.Server.FindRoles(roleQuery, false).FirstOrDefault(); if (role == null) { await e.Channel.SafeSendMessage($"A role with the name of `{roleQuery}` was not found."); return; } _joinedRoleSubs[e.Server.Id] = role.Id; await e.Channel.SafeSendMessage($"Set the auto role assigner role to `{role.Name}`."); }); }); }); manager.CreateDynCommands("newuser", PermissionLevel.ServerModerator, group => { group.CreateCommand("syntax") .Description("Syntax rules for newuser commands.") .Do( async e => await e.Channel.SafeSendMessage( $"Syntax: `{UserNameKeyword}` - replaced with the name of the user who triggered the event, `{LocationKeyword}` - replaced with the location (server or channel) where the event occured.```")); group.CreateGroup("join", joinGroup => { // joinGroup callback exists commands joinGroup.CreateGroup("", existsJoin => { existsJoin.AddCheck((cmd, usr, chnl) => { if (_userJoinedSubs.ContainsKey(chnl.Server.Id)) { return(_userJoinedSubs[chnl.Server.Id].IsEnabled); } return(false); }); existsJoin.CreateCommand("message") .Description($"Sets the join message for this current server.") .Parameter("message", ParameterType.Unparsed) .Do(async e => { string msg = e.GetArg("message"); _userJoinedSubs[e.Server.Id].Message = msg; await e.Channel.SafeSendMessage($"Set join message to {msg}"); }); existsJoin.CreateCommand("channel") .Description("Sets the callback channel for this servers join announcements.") .Parameter("channelName", ParameterType.Unparsed) .Do(async e => { string channelName = e.GetArg("channelName").ToLowerInvariant(); Channel channel = e.Server.TextChannels.FirstOrDefault(c => c.Name.ToLowerInvariant() == channelName); if (channel == null) { await e.Channel.SafeSendMessage($"Channel with the name {channelName} was not found."); return; } _userJoinedSubs[e.Server.Id].Channel = channel; await e.Channel.SafeSendMessage($"Set join callback to channel {channel.Name}"); }); existsJoin.CreateCommand("destroy") .Description("Stops announcing when new users have joined this server.") .Do(async e => { _userJoinedSubs[e.Server.Id].IsEnabled = false; await e.Channel.SafeSendMessage( "Disabled user join messages. You can re-enable them at any time."); }); }); // no join callback exists commands joinGroup.CreateGroup("", doesntExistJoin => { doesntExistJoin.AddCheck((cmd, usr, chnl) => { if (!_userJoinedSubs.ContainsKey(chnl.Server.Id)) { return(true); } return(!_userJoinedSubs[chnl.Server.Id].IsEnabled); }); doesntExistJoin.CreateCommand("enable") .Description("Enables announcing for when a new user joins this server.") .Do(async e => { if (_userJoinedSubs.ContainsKey(e.Server.Id)) { _userJoinedSubs[e.Server.Id].IsEnabled = true; } else { _userJoinedSubs.TryAdd(e.Server.Id, new UserEventCallback(e.Channel, DefaultMessage)); } await e.Channel.SafeSendMessage( "Enabled user join messages.\r\nYou can now change the channel and the message by typing !help announce join."); }); }); }); group.CreateGroup("leave", leaveGroup => { // joinGroup callback exists commands leaveGroup.CreateGroup("", existsLeave => { existsLeave.AddCheck((cmd, usr, chnl) => { if (_userLeftSubs.ContainsKey(chnl.Server.Id)) { return(_userLeftSubs[chnl.Server.Id].IsEnabled); } return(false); }); existsLeave.CreateCommand("message") .Description($"Sets the leave message for this current server.") .Parameter("message", ParameterType.Unparsed) .Do(async e => { string msg = e.GetArg("message"); _userLeftSubs[e.Server.Id].Message = msg; await e.Channel.SafeSendMessage($"Set leave message to {msg}"); }); existsLeave.CreateCommand("channel") .Description("Sets the callback channel for this servers leave announcements.") .Parameter("channelName", ParameterType.Unparsed) .Do(async e => { string channelName = e.GetArg("channelName").ToLowerInvariant(); Channel channel = e.Server.TextChannels.FirstOrDefault(c => c.Name.ToLowerInvariant() == channelName); if (channel == null) { await e.Channel.SafeSendMessage($"Channel with the name {channelName} was not found."); return; } _userLeftSubs[e.Server.Id].Channel = channel; await e.Channel.SafeSendMessage($"Set leave callback to channel {channel.Name}"); }); existsLeave.CreateCommand("destroy") .Description("Stops announcing when users have left joined this server.") .Do(async e => { _userLeftSubs[e.Server.Id].IsEnabled = false; await e.Channel.SafeSendMessage( "Disabled user join messages. You can re-enable them at any time."); }); }); // no leavea callback exists commands leaveGroup.CreateGroup("", doesntExistLeave => { doesntExistLeave.AddCheck((cmd, usr, chnl) => { if (!_userLeftSubs.ContainsKey(chnl.Server.Id)) { return(true); } return(!_userLeftSubs[chnl.Server.Id].IsEnabled); }); doesntExistLeave.CreateCommand("enable") .Description("Enables announcing for when a user leaves this server.") .Do(async e => { if (_userLeftSubs.ContainsKey(e.Server.Id)) { _userLeftSubs[e.Server.Id].IsEnabled = true; } else { _userLeftSubs.TryAdd(e.Server.Id, new UserEventCallback(e.Channel, DefaultMessage)); } await e.Channel.SafeSendMessage( "Enabled user leave messages.\r\nYou can now change the channel and the message by typing !help announce leave."); }); }); }); }); manager.UserJoined += async(s, e) => { if (!manager.EnabledServers.Contains(e.Server)) { return; } if (_userJoinedSubs.ContainsKey(e.Server.Id)) { UserEventCallback callback = _userJoinedSubs[e.Server.Id]; if (callback.IsEnabled) { await callback.Channel.SafeSendMessage(ParseString(callback.Message, e.User, e.Server)); } } if (_joinedRoleSubs.ContainsKey(e.Server.Id)) { // verify that the role still exists. Role role = e.Server.GetRole(_joinedRoleSubs[e.Server.Id]); if (role == null) { await RemoveAutoRoleAssigner(e.Server.Id, null, false); Channel callback = e.Server.TextChannels.FirstOrDefault(); if (callback != null) { await callback.SafeSendMessage("Auto role assigner was given a non existant role. Removing."); } return; } await e.User.SafeAddRoles(e.Server.CurrentUser, role); } }; manager.UserLeft += async(s, e) => { if (!manager.EnabledServers.Contains(e.Server)) { return; } if (!_userLeftSubs.ContainsKey(e.Server.Id)) { return; } UserEventCallback callback = _userLeftSubs[e.Server.Id]; if (callback.IsEnabled) { await callback.Channel.SafeSendMessage(ParseString(callback.Message, e.User, e.Server)); } }; }
/// <summary> /// Bind the data. /// </summary> public void Bind() { if (!string.IsNullOrEmpty(ObjectType)) { pnlGrid.Visible = true; selectionEnabled = ((ObjectType != LicenseKeyInfo.OBJECT_TYPE) || !Settings.IsOlderVersion); if (selectionEnabled) { // Initilaize strings btnAll.Text = GetString("ImportExport.All"); btnNone.Text = GetString("export.none"); btnDefault.Text = GetString("General.Default"); } pnlLinks.Visible = selectionEnabled; // Get object info GeneralizedInfo info = ModuleManager.GetReadOnlyObject(ObjectType); if (info != null) { gvObjects.RowDataBound += gvObjects_RowDataBound; plcGrid.Visible = true; codeNameColumnName = info.CodeNameColumn; displayNameColumnName = info.DisplayNameColumn; // Get data source DataSet ds = DataSource; DataTable table = null; if (!DataHelper.DataSourceIsEmpty(ds)) { // Get the table string tableName = DataClassInfoProvider.GetTableName(info); table = ds.Tables[tableName]; // Set correct ID for direct page contol pagerElem.DirectPageControlID = ((float)table.Rows.Count / pagerElem.CurrentPageSize > 20.0f) ? "txtPage" : "drpPage"; // Sort data if (!DataHelper.DataSourceIsEmpty(table)) { string orderBy = GetOrderByExpression(info); table.DefaultView.Sort = orderBy; if (ValidationHelper.GetString(table.Rows[0][codeNameColumnName], null) == null) { codeNameColumnName = info.GUIDColumn; } } } // Prepare checkBox column TemplateField checkBoxField = (TemplateField)gvObjects.Columns[0]; checkBoxField.HeaderText = GetString("General.Import"); // Prepare name field TemplateField nameField = (TemplateField)gvObjects.Columns[1]; nameField.HeaderText = GetString("general.displayname"); if (!DataHelper.DataSourceIsEmpty(table)) { plcObjects.Visible = true; lblNoData.Visible = false; gvObjects.DataSource = table; // Call page binding event if (OnPageBinding != null) { OnPageBinding(this, null); } PagedDataSource pagedDS = gvObjects.DataSource as PagedDataSource; if (pagedDS != null) { if (pagedDS.PageSize <= 0) { gvObjects.DataSource = table; } } gvObjects.DataBind(); } else { plcObjects.Visible = false; lblNoData.Visible = true; lblNoData.Text = String.Format(GetString("ImportGridView.NoData"), GetString("objecttype." + ObjectType.Replace(".", "_").Replace("#", "_"))); } } else { plcGrid.Visible = false; } // Disable license selection bool enable = !((ObjectType == LicenseKeyInfo.OBJECT_TYPE) && Settings.IsOlderVersion); gvObjects.Enabled = enable; pnlLinks.Enabled = enable; lblInfo.Text = enable ? GetString("ImportGridView.Info") : GetString("ImportGridView.Disabled"); } else { pnlGrid.Visible = false; gvObjects.DataSource = null; gvObjects.DataBind(); } }
public override void Install(ModuleManager manager) { Random rng = new Random(); manager.CreateCommands("", cgb => { cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); var client = manager.Client; cgb.CreateCommand("\\o\\") .Description("Nadeko replies with /o/") .Do(async e => { await e.Send(e.User.Mention + "/o/"); }); cgb.CreateCommand("/o/") .Description("Nadeko replies with \\o\\") .Do(async e => { await e.Send(e.User.Mention + "\\o\\"); }); }); manager.CreateCommands(NadekoBot.botMention, cgb => { var client = manager.Client; cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); commands.ForEach(cmd => cmd.Init(cgb)); cgb.CreateCommand("uptime") .Description("Shows how long is Nadeko running for.") .Do(async e => { var time = (DateTime.Now - Process.GetCurrentProcess().StartTime); string str = "I am online for " + time.Days + " days, " + time.Hours + " hours, and " + time.Minutes + " minutes."; await e.Send(str); }); cgb.CreateCommand("die") .Description("Works only for the owner. Shuts the bot down.") .Do(async e => { if (e.User.Id == NadekoBot.OwnerID) { Timer t = new Timer(); t.Interval = 2000; t.Elapsed += (s, ev) => { Environment.Exit(0); }; t.Start(); await e.Send(e.User.Mention + ", Yes, my love."); } else { await e.Send(e.User.Mention + ", No."); } }); Stopwatch randServerSW = new Stopwatch(); randServerSW.Start(); cgb.CreateCommand("randserver") .Description("Generates an invite to a random server and prints some stats.") .Do(async e => { if (client.Servers.Count() < 10) { await e.Send("I need to be connected to at least 10 servers for this command to work."); return; } if (randServerSW.Elapsed.Seconds < 1800) { await e.Send("You have to wait " + (1800 - randServerSW.Elapsed.Seconds) + " more seconds to use this function."); return; } randServerSW.Restart(); while (true) { var server = client.Servers.OrderBy(x => rng.Next()).FirstOrDefault(); if (server == null) { continue; } try { var inv = await server.CreateInvite(100, 5); await e.Send("**Server:** " + server.Name + "\n**Owner:** " + server.Owner.Name + "\n**Channels:** " + server.AllChannels.Count() + "\n**Total Members:** " + server.Users.Count() + "\n**Online Members:** " + server.Users.Where(u => u.Status == UserStatus.Online).Count() + "\n**Invite:** " + inv.Url); break; } catch { continue; } } }); /* * cgb.CreateCommand("avalanche!") * .Description("Mentions a person in every channel of the server, then deletes it") * .Parameter("name", ParameterType.Required) * .Do(e => { * var usr = e.Server.FindUsers(e.GetArg("name")).FirstOrDefault(); * if (usr == null) return; * e.Server.AllChannels.ForEach(async c => { * try { * var m = await c.SendMessage(usr.Mention); * await m.Delete(); * } catch (Exception ex) { * Console.WriteLine(ex); * } * }); * }); */ cgb.CreateCommand("do you love me") .Description("Replies with positive answer only to the bot owner.") .Do(async e => { if (e.User.Id == NadekoBot.OwnerID) { await e.Send(e.User.Mention + ", Of course I do, my Master."); } else { await e.Send(e.User.Mention + ", Don't be silly."); } }); cgb.CreateCommand("how are you") .Description("Replies positive only if bot owner is online.") .Do(async e => { if (e.User.Id == NadekoBot.OwnerID) { await e.Send(e.User.Mention + " I am great as long as you are here."); } else { var kw = e.Server.GetUser(NadekoBot.OwnerID); if (kw != null && kw.Status == UserStatus.Online) { await e.Send(e.User.Mention + " I am great as long as " + kw.Mention + " is with me."); } else { await e.Send(e.User.Mention + " I am sad. My Master is not with me."); } } }); cgb.CreateCommand("insult") .Parameter("mention", ParameterType.Required) .Description("Only works for owner. Insults @X person.\n**Usage**: @NadekoBot insult @X.") .Do(async e => { List <string> insults = new List <string> { " you are a poop.", " you jerk.", " i will eat you when i get my powers back." }; Random r = new Random(); var u = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault(); if (u == null) { await e.Send("Invalid user specified."); return; } if (u.Id == NadekoBot.OwnerID) { await e.Send("I would never insult my master <3"); return; } await e.Send(u.Mention + insults[r.Next(0, insults.Count)]); }); cgb.CreateCommand("praise") .Description("Only works for owner. Praises @X person.\n**Usage**: @NadekoBot praise @X.") .Parameter("mention", ParameterType.Required) .Do(async e => { List <string> praises = new List <string> { " You are cool.", " You are nice!", " You did a good job.", " You did something nice.", " is awesome!", " Wow." }; Random r = new Random(); var u = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault(); if (u == null) { await e.Send("Invalid user specified."); return; } if (u.Id == NadekoBot.OwnerID) { await e.Send(e.User.Mention + " I don't need your permission to praise my beloved Master <3"); return; } await e.Send(u.Mention + praises[r.Next(0, praises.Count)]); }); cgb.CreateCommand("pat") .Description("Pat someone ^_^") .Parameter("user", ParameterType.Unparsed) .Do(async e => { var user = e.GetArg("user"); if (user == null || e.Message.MentionedUsers.Count() == 0) { return; } string[] pats = new string[] { "http://i.imgur.com/IiQwK12.gif", "http://i.imgur.com/JCXj8yD.gif", "http://i.imgur.com/qqBl2bm.gif", "http://i.imgur.com/eOJlnwP.gif", "https://45.media.tumblr.com/229ec0458891c4dcd847545c81e760a5/tumblr_mpfy232F4j1rxrpjzo1_r2_500.gif", "https://media.giphy.com/media/KZQlfylo73AMU/giphy.gif", "https://media.giphy.com/media/12hvLuZ7uzvCvK/giphy.gif", "http://gallery1.anivide.com/_full/65030_1382582341.gif", "https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif ", }; await e.Send($"{e.Message.MentionedUsers.First().Mention} {pats[new Random().Next(0, pats.Length)]}"); }); cgb.CreateCommand("cry") .Description("Tell Nadeko to cry. You are a heartless monster if you use this command.") .Do(async e => { string[] pats = new string[] { "http://i.imgur.com/Xg3i1Qy.gif", "http://i.imgur.com/3K8DRrU.gif", "http://i.imgur.com/k58BcAv.gif", "http://i.imgur.com/I2fLXwo.gif" }; await e.Send($"(•̥́ _•ૅ。)\n{pats[new Random().Next(0, pats.Length)]}"); }); cgb.CreateCommand("are you real") .Description("Useless.") .Do(async e => { await e.Send(e.User.Mention + " I will be soon."); }); cgb.CreateCommand("are you there") .Description("Checks if nadeko is operational.") .Alias(new string[] { "!", "?" }) .Do(SayYes()); cgb.CreateCommand("draw") .Description("Nadeko instructs you to type $draw. Gambling functions start with $") .Do(async e => { await e.Send("Sorry, I don't gamble, type $draw for that function."); }); cgb.CreateCommand("fire") .Description("Shows a unicode fire message. Optional parameter [x] tells her how many times to repeat the fire.\n**Usage**: @NadekoBot fire [x]") .Parameter("times", ParameterType.Optional) .Do(async e => { int count = 0; if (e.Args?.Length > 0) { int.TryParse(e.Args[0], out count); } if (count < 1) { count = 1; } else if (count > 12) { count = 12; } string str = ""; for (int i = 0; i < count; i++) { str += firestr; } await e.Send(str); }); cgb.CreateCommand("rip") .Description("Shows a grave image of someone with a start year\n**Usage**: @NadekoBot rip @Someone 2000") .Parameter("user", ParameterType.Optional) .Parameter("year", ParameterType.Optional) .Do(async e => { var usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault(); string text = ""; text = usr?.Name; await e.Channel.SendFile("ripzor_m8.png", RipName(text, e.GetArg("year") == "" ? null : e.GetArg("year"))); }); cgb.CreateCommand("j") .Description("Joins a server using a code.") .Parameter("id", ParameterType.Required) .Do(async e => { try { await(await client.GetInvite(e.Args[0])).Accept(); await e.Send("I got in!"); } catch { await e.Send("Invalid code."); } }); cgb.CreateCommand("slm") .Description("Shows the message where you were last mentioned in this channel (checks last 10k messages)") .Do(async e => { Message msg = null; var msgs = (await e.Channel.DownloadMessages(100)) .Where(m => m.MentionedUsers.Contains(e.User)) .OrderByDescending(m => m.Timestamp); if (msgs.Count() > 0) { msg = msgs.First(); } else { int attempt = 0; Message lastMessage = null; while (msg == null && attempt++ < 5) { var msgsarr = await e.Channel.DownloadMessages(100, lastMessage?.Id); msg = msgsarr .Where(m => m.MentionedUsers.Contains(e.User)) .OrderByDescending(m => m.Timestamp) .FirstOrDefault(); lastMessage = msgsarr.OrderBy(m => m.Timestamp).First(); } } if (msg != null) { await e.Send($"Last message mentioning you was at {msg.Timestamp}\n**Message from {msg.User.Name}:** {msg.RawText.Replace("@everyone", "@everryone")}"); } else { await e.Send("I can't find a message mentioning you."); } }); cgb.CreateCommand("bb") .Description("Says bye to someone. **Usage**: @NadekoBot bb @X") .Parameter("ppl", ParameterType.Unparsed) .Do(async e => { string str = "Bye"; foreach (var u in e.Message.MentionedUsers) { if (u.Id != NadekoBot.client.CurrentUser.Id) { str += " " + u.Mention; } } await e.Send(str); }); cgb.CreateCommand("call") .Description("Useless. Writes calling @X to chat.\n**Usage**: @NadekoBot call @X ") .Parameter("who", ParameterType.Required) .Do(async e => { await e.Send("Calling " + e.Args[0].Replace("@everyone", "[everyone]") + "..."); }); cgb.CreateCommand("hide") .Description("Hides nadeko in plain sight!11!!") .Do(async e => { using (Stream ms = Resources.hidden.ToStream(ImageFormat.Png)) { await client.CurrentUser.Edit(NadekoBot.password, avatar: ms); } await e.Send("*hides*"); }); cgb.CreateCommand("unhide") .Description("Unhides nadeko in plain sight!1!!1") .Do(async e => { using (FileStream fs = new FileStream("data/avatar.png", FileMode.Open)) { await client.CurrentUser.Edit(NadekoBot.password, avatar: fs); } await e.Send("*unhides*"); }); cgb.CreateCommand("dump") .Description("Dumps all of the invites it can to dump.txt.** Owner Only.**") .Do(async e => { if (NadekoBot.OwnerID != e.User.Id) { return; } int i = 0; int j = 0; string invites = ""; foreach (var s in client.Servers) { try { var invite = await s.CreateInvite(0); invites += invite.Url + "\n"; i++; } catch { j++; continue; } } File.WriteAllText("dump.txt", invites); await e.Send($"Got invites for {i} servers and failed to get invites for {j} servers"); }); cgb.CreateCommand("ab") .Description("Try to get 'abalabahaha'") .Do(async e => { string[] strings = { "ba", "la", "ha" }; string construct = "@a"; int cnt = rng.Next(4, 7); while (cnt-- > 0) { construct += strings[rng.Next(0, strings.Length)]; } await e.Send(construct); }); cgb.CreateCommand("av").Alias("avatar") .Parameter("mention", ParameterType.Required) .Description("Shows a mentioned person's avatar. **Usage**: ~av @X") .Do(async e => { var usr = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault(); if (usr == null) { await e.Send("Invalid user specified."); return; } await e.Send(await usr.AvatarUrl.ShortenUrl()); }); /* * string saved = ""; * cgb.CreateCommand("save") * .Description("Saves up to 5 last messages as a quote") * .Parameter("number", ParameterType.Required) * .Do(e => { * var arg = e.GetArg("number"); * int num; * if (!int.TryParse(arg, out num) || num < 1 || num > 5) * num = 1; * saved = string.Join("\n", e.Channel.Messages.Skip(1).Take(num)); * }); * * cgb.CreateCommand("quote") * .Description("Shows the previously saved quote") * .Parameter("arg", ParameterType.Required) * .Do(async e => { * var arg = e.GetArg("arg"); * await e.Send("```"+saved+"```"); * }); */ //TODO add eval /* * cgb.CreateCommand(">") * .Parameter("code", ParameterType.Unparsed) * .Do(async e => * { * if (e.Message.User.Id == NadekoBot.OwnerId) * { * var result = await CSharpScript.EvaluateAsync(e.Args[0]); * await e.Send( result?.ToString() ?? "null"); * return; * } * });*/ }); }
private void OnGUI() { if (position.size * EditorGUIUtility.pixelsPerPoint != m_LastWindowPixelSize) // pixelsPerPoint only reliable in OnGUI() { UpdateZoomAreaAndParent(); } DoToolbarGUI(); // This isn't ideal. Custom Cursors set by editor extensions for other windows can leak into the game view. // To fix this we should probably stop using the global custom cursor (intended for runtime) for custom editor cursors. // This has been noted for Cursors tech debt. EditorGUIUtility.AddCursorRect(viewInWindow, MouseCursor.CustomCursor); EventType type = Event.current.type; // Gain mouse lock when clicking on game view content if (type == EventType.MouseDown && viewInWindow.Contains(Event.current.mousePosition)) { AllowCursorLockAndHide(true); } // Lose mouse lock when pressing escape else if (type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) { AllowCursorLockAndHide(false); } // We hide sliders when playing, and also when we are zoomed out beyond canvas edges var playing = EditorApplication.isPlaying && !EditorApplication.isPaused; var targetInContentCached = targetInContent; m_ZoomArea.hSlider = !playing && m_ZoomArea.shownArea.width < targetInContentCached.width; m_ZoomArea.vSlider = !playing && m_ZoomArea.shownArea.height < targetInContentCached.height; m_ZoomArea.enableMouseInput = !playing; ConfigureZoomArea(); // We don't want controls inside the GameView (e.g. the toolbar) to have keyboard focus while playing. // The game should get the keyboard events. if (playing) { EditorGUIUtility.keyboardControl = 0; } GUI.color = Color.white; // Get rid of play mode tint var originalEventType = Event.current.type; m_ZoomArea.BeginViewGUI(); // Setup game view dimensions, so that player loop can use it for input var gameViewTarget = GUIClip.UnclipToWindow(m_ZoomArea.drawRect); if (m_Parent) { var zoomedTarget = new Rect(targetInView.position + gameViewTarget.position, targetInView.size); SetParentGameViewDimensions(zoomedTarget, gameViewTarget, targetRenderSize); } var editorMousePosition = Event.current.mousePosition; var gameMousePosition = (editorMousePosition + gameMouseOffset) * gameMouseScale; if (type == EventType.Repaint) { GUI.Box(m_ZoomArea.drawRect, GUIContent.none, Styles.gameViewBackgroundStyle); Vector2 oldOffset = GUIUtility.s_EditorScreenPointOffset; GUIUtility.s_EditorScreenPointOffset = Vector2.zero; SavedGUIState oldState = SavedGUIState.Create(); var clearTexture = m_ClearInEditMode && !EditorApplication.isPlaying; var currentTargetDisplay = 0; if (ModuleManager.ShouldShowMultiDisplayOption()) { // Display Targets can have valid targets from 0 to 7. System.Diagnostics.Debug.Assert(targetDisplay < 8, "Display Target is Out of Range"); currentTargetDisplay = targetDisplay; } targetDisplay = currentTargetDisplay; targetSize = targetRenderSize; showGizmos = m_Gizmos; clearColor = kClearBlack; renderIMGUI = true; if (!EditorApplication.isPlaying || (EditorApplication.isPlaying && Time.frameCount % OnDemandRendering.GetRenderFrameInterval() == 0)) { m_RenderTexture = RenderPreview(gameMousePosition, clearTexture); } if (m_TargetClamped) { Debug.LogWarningFormat("GameView reduced to a reasonable size for this system ({0}x{1})", targetSize.x, targetSize.y); } EditorGUIUtility.SetupWindowSpaceAndVSyncInternal(GUIClip.Unclip(viewInWindow)); if (m_RenderTexture.IsCreated()) { oldState.ApplyAndForget(); GUIUtility.s_EditorScreenPointOffset = oldOffset; GUI.BeginGroup(m_ZoomArea.drawRect); // Actually draw the game view to the screen, without alpha blending Rect drawRect = deviceFlippedTargetInView; drawRect.x = Mathf.Round(drawRect.x); drawRect.y = Mathf.Round(drawRect.y); Graphics.DrawTexture(drawRect, m_RenderTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, GUI.blitMaterial); GUI.EndGroup(); } } else if (type != EventType.Layout && type != EventType.Used) { if (Event.current.isKey && (!EditorApplication.isPlaying || EditorApplication.isPaused)) { return; } bool mousePosInGameViewRect = viewInWindow.Contains(Event.current.mousePosition); // MouseDown events outside game view rect are not send to scripts but MouseUp events are (see below) if (Event.current.rawType == EventType.MouseDown && !mousePosInGameViewRect) { return; } var originalDisplayIndex = Event.current.displayIndex; // Transform events into local space, so the mouse position is correct // Then queue it up for playback during playerloop Event.current.mousePosition = gameMousePosition; Event.current.displayIndex = targetDisplay; EditorGUIUtility.QueueGameViewInputEvent(Event.current); bool useEvent = true; // Do not use mouse UP event if mousepos is outside game view rect (fix for case 380995: Gameview tab's context menu is not appearing on right click) // Placed after event queueing above to ensure scripts can react on mouse up events. if (Event.current.rawType == EventType.MouseUp && !mousePosInGameViewRect) { useEvent = false; } // Don't use command events, or they won't be sent to other views. if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) { useEvent = false; } if (useEvent) { Event.current.Use(); } else { Event.current.mousePosition = editorMousePosition; } // Reset display index Event.current.displayIndex = originalDisplayIndex; } m_ZoomArea.EndViewGUI(); if (originalEventType == EventType.ScrollWheel && Event.current.type == EventType.Used) { EditorApplication.update -= SnapZoomDelayed; EditorApplication.update += SnapZoomDelayed; s_LastScrollTime = EditorApplication.timeSinceStartup; } EnforceZoomAreaConstraints(); if (m_RenderTexture) { if (m_ZoomArea.scale.y < 1f) { m_RenderTexture.filterMode = FilterMode.Bilinear; } else { m_RenderTexture.filterMode = FilterMode.Point; } } if (m_NoCameraWarning && !EditorGUIUtility.IsDisplayReferencedByCameras(targetDisplay)) { GUI.Label(warningPosition, GUIContent.none, EditorStyles.notificationBackground); var displayName = ModuleManager.ShouldShowMultiDisplayOption() ? DisplayUtility.GetDisplayNames()[targetDisplay].text : string.Empty; var cameraWarning = string.Format("{0}\nNo cameras rendering", displayName); EditorGUI.DoDropShadowLabel(warningPosition, EditorGUIUtility.TempContent(cameraWarning), EditorStyles.notificationText, .3f); } if (m_Stats) { GameViewGUI.GameViewStatsGUI(); } }
private void DoToolbarGUI() { GameViewSizes.instance.RefreshStandaloneAndRemoteDefaultSizes(); GUILayout.BeginHorizontal(EditorStyles.toolbar); { var types = GetAvailableWindowTypes().OrderBy(type => type.Name).ToList(); if (types.Count > 1) { int viewIndex = EditorGUILayout.Popup(types.IndexOf(typeof(GameView)), types.Select(viewTypes => viewTypes.Name).ToArray(), EditorStyles.toolbarPopup, GUILayout.Width(90)); EditorGUILayout.Space(); if (types[viewIndex].Name != typeof(GameView).Name) { SwapMainWindow(types[viewIndex]); } } if (ModuleManager.ShouldShowMultiDisplayOption()) { int display = EditorGUILayout.Popup(targetDisplay, DisplayUtility.GetDisplayNames(), EditorStyles.toolbarPopup, GUILayout.Width(80)); if (display != targetDisplay) { targetDisplay = display; UpdateZoomAreaAndParent(); } } EditorGUILayout.GameViewSizePopup(currentSizeGroupType, selectedSizeIndex, this, EditorStyles.toolbarPopup, GUILayout.Width(160f)); DoZoomSlider(); // If the previous platform and current does not match, update the scale if ((int)currentSizeGroupType != prevSizeGroupType) { UpdateZoomAreaAndParent(); // Update the platform to the recent one prevSizeGroupType = (int)currentSizeGroupType; } if (FrameDebuggerUtility.IsLocalEnabled()) { GUILayout.FlexibleSpace(); Color oldCol = GUI.color; // This has nothing to do with animation recording. Can we replace this color with something else? GUI.color *= AnimationMode.recordedPropertyColor; GUILayout.Label(Styles.frameDebuggerOnContent, EditorStyles.miniLabel); GUI.color = oldCol; // Make frame debugger windows repaint after each time game view repaints. // We want them to always display the latest & greatest game view // rendering state. if (Event.current.type == EventType.Repaint) { FrameDebuggerWindow.RepaintAll(); } } GUILayout.FlexibleSpace(); if (RenderDoc.IsLoaded()) { using (new EditorGUI.DisabledScope(!RenderDoc.IsSupported())) { if (GUILayout.Button(Styles.renderdocContent, EditorStyles.toolbarButton)) { m_Parent.CaptureRenderDocScene(); GUIUtility.ExitGUI(); } } } // Allow the user to select how the XR device will be rendered during "Play In Editor" if (PlayerSettings.virtualRealitySupported) { int selectedRenderMode = EditorGUILayout.Popup(m_XRRenderMode, Styles.xrRenderingModes, EditorStyles.toolbarPopup, GUILayout.Width(80)); SetXRRenderMode(selectedRenderMode); } maximizeOnPlay = GUILayout.Toggle(maximizeOnPlay, Styles.maximizeOnPlayContent, EditorStyles.toolbarButton); EditorUtility.audioMasterMute = GUILayout.Toggle(EditorUtility.audioMasterMute, Styles.muteContent, EditorStyles.toolbarButton); DoVSyncButton(); m_Stats = GUILayout.Toggle(m_Stats, Styles.statsContent, EditorStyles.toolbarButton); if (EditorGUILayout.DropDownToggle(ref m_Gizmos, Styles.gizmosContent, EditorStyles.toolbarDropDownToggleRight)) { Rect rect = GUILayoutUtility.topLevel.GetLast(); if (AnnotationWindow.ShowAtPosition(rect, true)) { GUIUtility.ExitGUI(); } } } GUILayout.EndHorizontal(); }
/// <summary> /// Compare DataSets. /// </summary> /// <param name="ds">Original DataSet</param> /// <param name="compareDs">DataSet to compare</param> private void CompareDataSets(DataSet ds, DataSet compareDs) { Table = new Table(); SetTable(Table); Table.CssClass += " NoSideBorders"; // Ensure same tables in DataSets EnsureSameTables(ds, compareDs); EnsureSameTables(compareDs, ds); // Prepare list of tables SortedDictionary <string, string> tables = new SortedDictionary <string, string>(); foreach (DataTable dt in ds.Tables) { string excludedTableNames = (ExcludedTableNames != null) ? ";" + ExcludedTableNames.Trim(';').ToLowerCSafe() + ";" : ""; string tableName = dt.TableName; if (!DataHelper.DataSourceIsEmpty(ds.Tables[tableName]) || !DataHelper.DataSourceIsEmpty(CompareDataSet.Tables[tableName])) { if (!excludedTableNames.Contains(";" + tableName.ToLowerCSafe() + ";")) { tables.Add(GetString("ObjectType." + tableName), tableName); } } } // Generate the tables foreach (string tableName in tables.Values) { DataTable dt = ds.Tables[tableName].Copy(); DataTable dtCompare = CompareDataSet.Tables[tableName].Copy(); if (dt.PrimaryKey.Length <= 0) { continue; } // Add table heading if ((tables.Count > 1) || (ds.Tables.Count > 1)) { AddTableHeaderRow(Table, GetTableHeaderText(dt), null); } while (dt.Rows.Count > 0 || dtCompare.Rows.Count > 0) { // Add table header row TableCell labelCell = new TableHeaderCell(); labelCell.Text = GetString("General.FieldName"); TableCell valueCell = new TableHeaderCell(); valueCell.Text = GetString("General.Value"); TableCell valueCompare = new TableHeaderCell(); valueCompare.Text = GetString("General.Value"); AddRow(Table, labelCell, valueCell, valueCompare, "unigrid-head", true); DataRow srcDr; DataRow dstDr; if ((tables.Count == 1) && (dt.Rows.Count == 1) && (dtCompare.Rows.Count == 1)) { srcDr = dt.Rows[0]; dstDr = dtCompare.Rows[0]; } else { if (!DataHelper.DataSourceIsEmpty(dt)) { srcDr = dt.Rows[0]; dstDr = dtCompare.Rows.Find(GetPrimaryColumnsValue(dt, srcDr)); } else { dstDr = dtCompare.Rows[0]; srcDr = dt.Rows.Find(GetPrimaryColumnsValue(dtCompare, dstDr)); } // If match not find, try to find in guid column if ((srcDr == null) || (dstDr == null)) { DataTable dtToSearch; DataRow drTocheck; if (srcDr == null) { dtToSearch = dt; drTocheck = dstDr; } else { dtToSearch = dtCompare; drTocheck = srcDr; } GeneralizedInfo infoObj = ModuleManager.GetObject(drTocheck, dt.TableName.Replace("_", ".")); if ((infoObj != null) && ((infoObj.CodeNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) || (infoObj.TypeInfo.GUIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN))) { DataRow[] rows = dtToSearch.Select(infoObj.CodeNameColumn + "='" + drTocheck[infoObj.CodeNameColumn] + "'"); if (rows.Length > 0) { if (srcDr == null) { srcDr = rows[0]; } else { dstDr = rows[0]; } } else { rows = dtToSearch.Select(infoObj.TypeInfo.GUIDColumn + "='" + drTocheck[infoObj.TypeInfo.GUIDColumn] + "'"); if (rows.Length > 0) { if (srcDr == null) { srcDr = rows[0]; } else { dstDr = rows[0]; } } } } } } // Add values foreach (DataColumn dc in dt.Columns) { // Get content values string fieldContent = GetRowColumnContent(srcDr, dc, true); string fieldCompareContent = GetRowColumnContent(dstDr, dc, true); if (ShowAllFields || !String.IsNullOrEmpty(fieldContent) || !String.IsNullOrEmpty(fieldCompareContent)) { // Initialize comparators TextComparison comparefirst = new TextComparison(); comparefirst.SynchronizedScrolling = false; comparefirst.ComparisonMode = TextComparisonModeEnum.PlainTextWithoutFormating; comparefirst.EnsureHTMLLineEndings = true; TextComparison comparesecond = new TextComparison(); comparesecond.SynchronizedScrolling = false; comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText; comparesecond.EnsureHTMLLineEndings = true; comparefirst.PairedControl = comparesecond; // Set comparator content comparefirst.SourceText = fieldContent; comparefirst.DestinationText = fieldCompareContent; // Create set of cells labelCell = new TableCell(); labelCell.Text = "<strong>" + dc.ColumnName + "</strong>"; valueCell = new TableCell(); valueCell.Controls.Add(comparefirst); valueCompare = new TableCell(); valueCompare.Controls.Add(comparesecond); // Add comparison row AddRow(Table, labelCell, valueCell, valueCompare); } } // Remove rows from tables if (srcDr != null) { dt.Rows.Remove(srcDr); } if (dstDr != null) { dtCompare.Rows.Remove(dstDr); } if (dt.Rows.Count > 0 || dtCompare.Rows.Count > 0) { TableCell emptyCell = new TableCell(); emptyCell.Text = " "; AddRow(Table, emptyCell, null, null, "TableSeparator"); } } } plcContent.Controls.Add(Table); }
private void DoToolbarGUI() { GameViewSizes.instance.RefreshStandaloneAndRemoteDefaultSizes(); GUILayout.BeginHorizontal(EditorStyles.toolbar); { if (ModuleManager.ShouldShowMultiDisplayOption()) { int display = EditorGUILayout.Popup(m_TargetDisplay, DisplayUtility.GetDisplayNames(), EditorStyles.toolbarPopup, GUILayout.Width(80)); EditorGUILayout.Space(); if (display != m_TargetDisplay) { m_TargetDisplay = display; UpdateZoomAreaAndParent(); } } EditorGUILayout.GameViewSizePopup(currentSizeGroupType, selectedSizeIndex, this, EditorStyles.toolbarPopup, GUILayout.Width(160f)); DoZoomSlider(); if (FrameDebuggerUtility.IsLocalEnabled()) { GUILayout.FlexibleSpace(); Color oldCol = GUI.color; // This has nothing to do with animation recording. Can we replace this color with something else? GUI.color *= AnimationMode.recordedPropertyColor; GUILayout.Label(Styles.frameDebuggerOnContent, EditorStyles.miniLabel); GUI.color = oldCol; // Make frame debugger windows repaint after each time game view repaints. // We want them to always display the latest & greatest game view // rendering state. if (Event.current.type == EventType.Repaint) { FrameDebuggerWindow.RepaintAll(); } } GUILayout.FlexibleSpace(); if (RenderDoc.IsLoaded()) { using (new EditorGUI.DisabledScope(!RenderDoc.IsSupported())) { if (GUILayout.Button(Styles.renderdocContent, EditorStyles.toolbarButton)) { m_Parent.CaptureRenderDocScene(); GUIUtility.ExitGUI(); } } } // Allow the user to select how the XR device will be rendered during "Play In Editor" if (PlayerSettings.virtualRealitySupported) { int selectedRenderMode = EditorGUILayout.Popup(m_XRRenderMode, Styles.xrRenderingModes, EditorStyles.toolbarPopup, GUILayout.Width(80)); SetXRRenderMode(selectedRenderMode); } m_MaximizeOnPlay = GUILayout.Toggle(m_MaximizeOnPlay, Styles.maximizeOnPlayContent, EditorStyles.toolbarButton); EditorUtility.audioMasterMute = GUILayout.Toggle(EditorUtility.audioMasterMute, Styles.muteContent, EditorStyles.toolbarButton); m_Stats = GUILayout.Toggle(m_Stats, Styles.statsContent, EditorStyles.toolbarButton); Rect r = GUILayoutUtility.GetRect(Styles.gizmosContent, Styles.gizmoButtonStyle); Rect rightRect = new Rect(r.xMax - Styles.gizmoButtonStyle.border.right, r.y, Styles.gizmoButtonStyle.border.right, r.height); if (EditorGUI.DropdownButton(rightRect, GUIContent.none, FocusType.Passive, GUIStyle.none)) { Rect rect = GUILayoutUtility.topLevel.GetLast(); if (AnnotationWindow.ShowAtPosition(rect, true)) { GUIUtility.ExitGUI(); } } m_Gizmos = GUI.Toggle(r, m_Gizmos, Styles.gizmosContent, Styles.gizmoButtonStyle); } GUILayout.EndHorizontal(); }
public void GivenWhetherOrNotIAmInANonCombatModeIs(bool value) { ModuleManager.Setup(mm => mm.IsNonCombatMode).Returns(value); }
private void initModules() { ModuleManager.InitModules(Path.Combine(AppConfiguration.AppRoot, "Shell.Manifest.xml"), GlobalConfiguration.Configuration); // this should be called before RegisterAllAreas //AreaRegistration.RegisterAllAreas(GlobalConfiguration.Configuration); }
protected override void ProcessItem(Item item) { WriteObject(ModuleManager.GetItemModule(item), false); }
public static AssemblyTypeInfoGenerator.ClassInfo[] ExtractAssemblyTypeInfo(BuildTarget targetPlatform, bool isEditor, string assemblyPathName, string[] searchDirs) { try { ICompilationExtension compilationExtension = ModuleManager.GetCompilationExtension(ModuleManager.GetTargetStringFromBuildTarget(targetPlatform)); string[] extraAssemblyPaths = compilationExtension.GetCompilerExtraAssemblyPaths(isEditor, assemblyPathName); if (extraAssemblyPaths != null && extraAssemblyPaths.Length > 0) { List <string> stringList = new List <string>((IEnumerable <string>)searchDirs); stringList.AddRange((IEnumerable <string>)extraAssemblyPaths); searchDirs = stringList.ToArray(); } IAssemblyResolver assemblyResolver = compilationExtension.GetAssemblyResolver(isEditor, assemblyPathName, searchDirs); return((assemblyResolver != null ? new AssemblyTypeInfoGenerator(assemblyPathName, assemblyResolver) : new AssemblyTypeInfoGenerator(assemblyPathName, searchDirs)).GatherClassInfo()); } catch (Exception ex) { throw new Exception("ExtractAssemblyTypeInfo: Failed to process " + assemblyPathName + ", " + (object)ex); } }
public void Install(ModuleManager manager) { Nullcheck(Config.PastebinPassword, Config.PastebinUsername, Config.PastebinApiKey); _client = manager.Client; _dynPerms = _client.GetService <DynamicPermissionService>(); _pastebin = _client.GetService <PastebinService>(); manager.CreateCommands("dynperm", group => { group.MinPermissions((int)PermissionLevel.ServerAdmin); group.AddCheck((cmd, usr, chnl) => !chnl.IsPrivate); group.CreateCommand("set") .Description( "Sets the dynamic permissions for this server.**Pastebin links are supported.**Use the dynperm help command for more info.") .Parameter("perms", ParameterType.Unparsed) .Do(async e => { string input = e.GetArg("perms"); string error; if (input.StartsWith(PastebinIdentifier)) { string rawUrl = input.Insert(PastebinIdentifier.Length, RawPath); input = await Utils.AsyncDownloadRaw(rawUrl); } DynPermFullData perms = _dynPerms.SetDynPermFullData(e.Server.Id, input, out error); if (!string.IsNullOrEmpty(error)) { await e.Channel.SendMessage($"Failed parsing Dynamic Permissions. {error}"); return; } await e.Channel.SendMessage($"Parsed Dynamic Permissions:\r\n```" + $"- Role Rules: {perms.Perms.RolePerms.Count}\r\n" + $"- User Rules: {perms.Perms.UserPerms.Count}```"); }); // commands which can only be executed if the caller server has dynperms. group.CreateGroup("", existsGroup => { existsGroup.AddCheck((cmd, usr, chnl) => _dynPerms.GetPerms(chnl.Server.Id) != null); existsGroup.CreateCommand("show") .Description("Shows the Dynamic Permissions for this server.") .Do(async e => { DynPermFullData data = _dynPerms.GetPerms(e.Server.Id); if (string.IsNullOrEmpty(data.PastebinUrl) || data.IsDirty) { if (!_pastebin.IsLoggedIn) { await _pastebin.Login(Config.PastebinUsername, Config.PastebinPassword); } data.PastebinUrl = await _pastebin.Paste(new PastebinService.PasteBinEntry { Expiration = PastebinService.PasteBinExpiration.Never, Format = "json", Private = true, Text = JsonConvert.SerializeObject(data.Perms), Title = $"{e.Server.Name}@{DateTime.Now}" }); } await e.Channel.SendMessage($"Paste: {data.PastebinUrl}"); }); existsGroup.CreateCommand("clear") .Description( "Clears the Dynamic Permissions. This cannot be undone. Pass yes as an argument for this to work.") .Parameter("areyousure") .Do(async e => { string input = e.GetArg("areyousure").ToLowerInvariant(); if (input == "yes" || input == "y") { _dynPerms.DestroyServerPerms(e.Server.Id); await e.Channel.SendMessage("Dynamic Permissions have been wiped."); } }); }); group.CreateCommand("help") .Description("help") .Do( async e => await e.Channel.SendMessage("https://github.com/SSStormy/Stormbot/blob/master/docs/dynperm.md")); }); }
public override void Initialize(InsightServer insight, ModuleManager manager) { server = insight; RegisterHandlers(); }
/// <summary> /// Initializes group selector. /// </summary> private void HandleGroupsSelection() { // Display group selector only when group module is present if (ModuleManager.IsModuleLoaded(ModuleName.COMMUNITY) && (groupsSelector != null)) { // Global libraries item into group selector if (GlobalLibraries != AvailableLibrariesEnum.None) { // Add special item groupsSelector.SetValue("UseDisplayNames", true); groupsSelector.SetValue("DisplayGlobalValue", true); groupsSelector.SetValue("SiteID", SiteID); groupsSelector.SetValue("GlobalValueText", GetString("dialogs.media.globallibraries")); groupsSelector.IsLiveSite = IsLiveSite; } else { groupsSelector.SetValue("DisplayGlobalValue", false); } // If all groups should be displayed switch (Groups) { case AvailableGroupsEnum.All: // Set condition to load only groups related to the current site groupsSelector.SetValue("WhereCondition", String.Format("(GroupSiteID={0})", SiteID)); break; case AvailableGroupsEnum.OnlyCurrentGroup: // Load only current group and disable control int groupId = ModuleCommands.CommunityGetCurrentGroupID(); groupsSelector.SetValue("WhereCondition", String.Format("(GroupID={0})", groupId)); break; case AvailableGroupsEnum.OnlySingleGroup: if (!string.IsNullOrEmpty(GroupName)) { groupsSelector.SetValue("WhereCondition", String.Format("(GroupName = N'{0}' AND GroupSiteID={1})", SqlHelper.GetSafeQueryString(GroupName, false), SiteID)); } break; case AvailableGroupsEnum.None: // Just '(none)' displayed in the selection if (GlobalLibraries == AvailableLibrariesEnum.None) { groupsSelector.SetValue("DisplayNoneWhenEmpty", true); groupsSelector.SetValue("EnabledGroups", false); } groupsSelector.SetValue("WhereCondition", String.Format("({0})", SqlHelper.NO_DATA_WHERE)); break; } // Reload group selector based on recently passed settings ((IDataUserControl)groupsSelector).ReloadData(true); PreselectGroup(); } else { plcGroupSelector.Visible = false; } }
public override void Install(ModuleManager manager) { var client = NadekoBot.client; manager.CreateCommands("", cgb => { cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); commands.ForEach(cmd => cmd.Init(cgb)); cgb.CreateCommand("~yt") .Parameter("query", ParameterType.Unparsed) .Description("Searches youtubes and shows the first result") .Do(async e => { if (!(await SearchHelper.ValidateQuery(e.Channel, e.GetArg("query")))) { return; } var str = await SearchHelper.ShortenUrl(await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query"))); if (string.IsNullOrEmpty(str.Trim())) { await e.Channel.SendMessage("Query failed"); return; } await e.Channel.SendMessage(str); }); cgb.CreateCommand("~ani") .Alias("~anime").Alias("~aq") .Parameter("query", ParameterType.Unparsed) .Description("Queries anilist for an anime and shows the first result.") .Do(async e => { if (!(await SearchHelper.ValidateQuery(e.Channel, e.GetArg("query")))) { return; } var result = await SearchHelper.GetAnimeQueryResultLink(e.GetArg("query")); if (result == null) { await e.Channel.SendMessage("Failed to find that anime."); return; } await e.Channel.SendMessage(result.ToString()); }); cgb.CreateCommand("~mang") .Alias("~manga").Alias("~mq") .Parameter("query", ParameterType.Unparsed) .Description("Queries anilist for a manga and shows the first result.") .Do(async e => { if (!(await SearchHelper.ValidateQuery(e.Channel, e.GetArg("query")))) { return; } var result = await SearchHelper.GetMangaQueryResultLink(e.GetArg("query")); if (result == null) { await e.Channel.SendMessage("Failed to find that manga."); return; } await e.Channel.SendMessage(result.ToString()); }); cgb.CreateCommand("~randomcat") .Description("Shows a random cat image.") .Do(async e => { try { await e.Channel.SendMessage(JObject.Parse(new StreamReader( WebRequest.Create("http://www.random.cat/meow") .GetResponse() .GetResponseStream()) .ReadToEnd())["file"].ToString()); } catch { } }); cgb.CreateCommand("~i") .Description("Pulls a first image using a search parameter. Use ~ir for different results.\n**Usage**: ~i cute kitten") .Parameter("query", ParameterType.Unparsed) .Do(async e => { if (string.IsNullOrWhiteSpace(e.GetArg("query"))) { return; } try { var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}"; var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString)); await e.Channel.SendMessage(obj["items"][0]["link"].ToString()); } catch (Exception ex) { await e.Channel.SendMessage($"💢 {ex.Message}"); } }); cgb.CreateCommand("~ir") .Description("Pulls a random image using a search parameter.\n**Usage**: ~ir cute kitten") .Parameter("query", ParameterType.Unparsed) .Do(async e => { if (string.IsNullOrWhiteSpace(e.GetArg("query"))) { return; } try { var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ _r.Next(1, 150) }&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}"; var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString)); await e.Channel.SendMessage(obj["items"][0]["link"].ToString()); } catch (Exception ex) { await e.Channel.SendMessage($"💢 {ex.Message}"); } }); cgb.CreateCommand("lmgtfy") .Alias("~lmgtfy") .Description("Google something for an idiot.") .Parameter("ffs", ParameterType.Unparsed) .Do(async e => { if (e.GetArg("ffs") == null || e.GetArg("ffs").Length < 1) { return; } await e.Channel.SendMessage(await $"http://lmgtfy.com/?q={ Uri.EscapeUriString(e.GetArg("ffs").ToString()) }".ShortenUrl()); }); cgb.CreateCommand("~hs") .Description("Searches for a Hearthstone card and shows its image. Takes a while to complete.\n**Usage**:~hs Ysera") .Parameter("name", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("name"); if (string.IsNullOrWhiteSpace(arg)) { await e.Channel.SendMessage("💢 Please enter a card name to search for."); return; } await e.Channel.SendIsTyping(); var headers = new WebHeaderCollection(); headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey); var res = await SearchHelper.GetResponseAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers); try { var items = JArray.Parse(res); List <System.Drawing.Image> images = new List <System.Drawing.Image>(); if (items == null) { throw new KeyNotFoundException("Cannot find a card by that name"); } int cnt = 0; items.Shuffle(); foreach (var item in items) { if (cnt >= 4) { break; } if (!item.HasValues || item["img"] == null) { continue; } cnt++; images.Add(System.Drawing.Bitmap.FromStream(await SearchHelper.GetResponseStream(item["img"].ToString()))); } if (items.Count > 4) { await e.Channel.SendMessage("⚠ Found over 4 images. Showing random 4."); } Console.WriteLine("Start"); await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png)); Console.WriteLine("Finish"); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error {ex.Message}"); } }); cgb.CreateCommand("~osu") .Description("Shows osu stats for a player\n**Usage**:~osu Name") .Parameter("usr", ParameterType.Unparsed) .Do(async e => { if (string.IsNullOrWhiteSpace(e.GetArg("usr"))) { return; } using (WebClient cl = new WebClient()) { try { cl.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); cl.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.2; Win64; x64)"); cl.DownloadDataAsync(new Uri($"http://lemmmy.pw/osusig/sig.php?uname={ e.GetArg("usr") }&flagshadow&xpbar&xpbarhex&pp=2")); cl.DownloadDataCompleted += async(s, cle) => { try { await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)); await e.Channel.SendMessage($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`"); } catch { } }; } catch { await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\"); } } }); cgb.CreateCommand("~ud") .Description("Searches Urban Dictionary for a word\n**Usage**:~ud Pineapple") .Parameter("query", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("query"); if (string.IsNullOrWhiteSpace(arg)) { await e.Channel.SendMessage("💢 Please enter a search term."); return; } await e.Channel.SendIsTyping(); var headers = new WebHeaderCollection(); headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey); var res = await SearchHelper.GetResponseAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}", headers); try { var items = JObject.Parse(res); var sb = new System.Text.StringBuilder(); sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}"); sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}"); sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl()}>"); await e.Channel.SendMessage(sb.ToString()); } catch { await e.Channel.SendMessage("💢 Failed finding a definition for that term."); } }); // thanks to Blaubeerwald cgb.CreateCommand("~#") .Description("Searches Tagdef.com for a hashtag\n**Usage**:~# ff") .Parameter("query", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("query"); if (string.IsNullOrWhiteSpace(arg)) { await e.Channel.SendMessage("💢 Please enter a search term."); return; } await e.Channel.SendIsTyping(); var headers = new WebHeaderCollection(); headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey); var res = await SearchHelper.GetResponseAsync($"https://tagdef.p.mashape.com/one.{Uri.EscapeUriString(arg)}.json", headers); try { var items = JObject.Parse(res); var sb = new System.Text.StringBuilder(); sb.AppendLine($"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()}"); sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}"); sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl()}>"); await e.Channel.SendMessage(sb.ToString()); } catch { await e.Channel.SendMessage("💢 Failed finidng a definition for that tag"); } }); //todo when moved from parse /* * cgb.CreateCommand("~osubind") * .Description("Bind discord user to osu name\n**Usage**: ~osubind My osu name") * .Parameter("osu_name", ParameterType.Unparsed) * .Do(async e => { * var userName = e.GetArg("user_name"); * var osuName = e.GetArg("osu_name"); * var usr = e.Server.FindUsers(userName).FirstOrDefault(); * if (usr == null) { * await e.Channel.SendMessage("Cannot find that discord user."); * return; * } * }); */ }); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; manager.CreateCommands("", cgb => { cgb.MinPermissions((int)PermissionLevel.User); Random rand; rand = new Random(); string[] thanks; thanks = new string[] { "No problem!", "Anytime!", "Just ask!", "Your welcome!" }; #region ~say cgb.CreateCommand("say") .MinPermissions((int)PermissionLevel.ServerAdmin) .Description("Make the bot speak!") .Parameter("text", ParameterType.Unparsed) .Do(async e => { Message[] messagesToDelete; messagesToDelete = await e.Channel.DownloadMessages(1); await e.Channel.DeleteMessages(messagesToDelete); await e.Channel.SendMessage(e.GetArg("text")); }); #endregion #region ~ping cgb.CreateCommand("ping") .MinPermissions((int)PermissionLevel.User) .Description("Returns 'Pong!'") .Do(async e => { await e.Channel.SendMessage("Pong!"); }); #endregion #region ~greet cgb.CreateCommand("greet") .MinPermissions((int)PermissionLevel.User) .Description("Greets a person.") .Parameter("GreetedPerson", ParameterType.Required) .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} greets {e.GetArg("GreetedPerson")}"); }); #endregion #region ~thank cgb.CreateCommand("thanks") .MinPermissions((int)PermissionLevel.User) .Description("Thank Emily!") .Do(async e => { int randomThank = rand.Next(thanks.Length); string thankToSend = thanks[randomThank]; await e.Channel.SendMessage(thankToSend); }); #endregion #region ~vote cgb.CreateCommand("vote") .Description("Vote!") .MinPermissions((int)PermissionLevel.User) .Parameter("choice") .Do(async e => { }); #endregion }); }
/// <summary> /// Loads control parameters. /// </summary> private void LoadParameters() { string identifier = QueryHelper.GetString("params", null); parameters = (Hashtable)WindowHelper.GetItem(identifier); if (parameters != null) { ResourcePrefix = ValidationHelper.GetString(parameters["ResourcePrefix"], null); // Load values from session selectionMode = (SelectionModeEnum)parameters["SelectionMode"]; objectType = ValidationHelper.GetString(parameters["ObjectType"], null); returnColumnName = ValidationHelper.GetString(parameters["ReturnColumnName"], null); valuesSeparator = ValidationHelper.GetValue(parameters["ValuesSeparator"], ';'); filterControl = ValidationHelper.GetString(parameters["FilterControl"], null); useDefaultNameFilter = ValidationHelper.GetBoolean(parameters["UseDefaultNameFilter"], true); whereCondition = ValidationHelper.GetString(parameters["WhereCondition"], null); orderBy = ValidationHelper.GetString(parameters["OrderBy"], null); itemsPerPage = ValidationHelper.GetInteger(parameters["ItemsPerPage"], 10); emptyReplacement = ValidationHelper.GetString(parameters["EmptyReplacement"], " "); dialogGridName = ValidationHelper.GetString(parameters["DialogGridName"], dialogGridName); additionalColumns = ValidationHelper.GetString(parameters["AdditionalColumns"], null); callbackMethod = ValidationHelper.GetString(parameters["CallbackMethod"], null); allowEditTextBox = ValidationHelper.GetBoolean(parameters["AllowEditTextBox"], false); fireOnChanged = ValidationHelper.GetBoolean(parameters["FireOnChanged"], false); disabledItems = ";" + ValidationHelper.GetString(parameters["DisabledItems"], String.Empty) + ";"; GlobalObjectSuffix = ValidationHelper.GetString(parameters["GlobalObjectSuffix"], string.Empty); AddGlobalObjectSuffix = ValidationHelper.GetBoolean(parameters["AddGlobalObjectSuffix"], false); AddGlobalObjectNamePrefix = ValidationHelper.GetBoolean(parameters["AddGlobalObjectNamePrefix"], false); RemoveMultipleCommas = ValidationHelper.GetBoolean(parameters["RemoveMultipleCommas"], false); filterMode = ValidationHelper.GetString(parameters["FilterMode"], null); displayNameFormat = ValidationHelper.GetString(parameters["DisplayNameFormat"], null); additionalSearchColumns = ValidationHelper.GetString(parameters["AdditionalSearchColumns"], String.Empty); siteWhereCondition = ValidationHelper.GetString(parameters["SiteWhereCondition"], null); UseTypeCondition = ValidationHelper.GetBoolean(parameters["UseTypeCondition"], true); AllowLocalizedFiltering = ValidationHelper.GetBoolean(parameters["AllowLocalizedFiltering"], true); mZeroRowsText = ValidationHelper.GetString(parameters["ZeroRowsText"], string.Empty); mFilteredZeroRowsText = ValidationHelper.GetString(parameters["FilteredZeroRowsText"], string.Empty); mHasDependingFields = ValidationHelper.GetBoolean(parameters["HasDependingFields"], false); // Custom parameter loaded from session as i can't seem to append my data to the HashTable toolTipFormat = ValidationHelper.GetString(SessionHelper.GetValue("ToolTipFormat_" + identifier), ""); // Set item prefix if it was passed by UniSelector's AdditionalUrlParameters var itemPrefix = QueryHelper.GetString("ItemPrefix", null); if (!String.IsNullOrEmpty(itemPrefix)) { ItemPrefix = itemPrefix; } // Init object if (!string.IsNullOrEmpty(objectType)) { iObjectType = ModuleManager.GetReadOnlyObject(objectType); if (iObjectType == null) { throw new Exception("[UniSelector.SelectionDialog]: Object type '" + objectType + "' not found."); } if (returnColumnName == null) { returnColumnName = iObjectType.TypeInfo.IDColumn; } } // Pre-select unigrid values passed from parent window if (!RequestHelper.IsPostBack()) { string values = (string)parameters["Values"]; if (!String.IsNullOrEmpty(values)) { hidItem.Value = values; parameters["Values"] = null; } } } }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); cgb.CreateCommand("~hentai") .Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { string tag = e.GetArg("tag"); if (tag == null) { tag = ""; } await e.Channel.SendMessage(":heart: Gelbooru: " + await SearchHelper.GetGelbooruImageLink(tag)); await e.Channel.SendMessage(":heart: Danbooru: " + await SearchHelper.GetDanbooruImageLink(tag)); }); cgb.CreateCommand("~danbooru") .Description("Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~danbooru yuri+kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { string tag = e.GetArg("tag"); if (tag == null) { tag = ""; } await e.Channel.SendMessage(await SearchHelper.GetDanbooruImageLink(tag)); }); cgb.CreateCommand("~gelbooru") .Description("Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { string tag = e.GetArg("tag"); if (tag == null) { tag = ""; } await e.Channel.SendMessage(await SearchHelper.GetGelbooruImageLink(tag)); }); cgb.CreateCommand("~e621") .Description("Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags.\n**Usage**: ~e621 yuri kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { string tag = e.GetArg("tag"); if (tag == null) { tag = ""; } await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag)); }); cgb.CreateCommand("~cp") .Description("We all know where this will lead you to.") .Parameter("anything", ParameterType.Unparsed) .Do(async e => { await e.Channel.SendMessage("http://i.imgur.com/MZkY1md.jpg"); }); cgb.CreateCommand("~boobs") .Description("Real adult content.") .Do(async e => { try { var obj = JArray.Parse(await SearchHelper.GetResponseAsync($"http://api.oboobs.ru/boobs/{_r.Next(0, 9304)}"))[0]; await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }"); } catch (Exception ex) { await e.Channel.SendMessage($"💢 {ex.Message}"); } }); }); }
internal static void StopPlayerConnectionSupport(string deviceId) { IDevice device = ModuleManager.GetDevice(deviceId); device.StopPlayerConnectionSupport(); }
public void GivenAModuleManager() { ModuleManager = new ModuleManager(); ModuleManager.ModuleLoaded += (sender, args) => { ModuleLoadedEventArgs = args; }; ModuleManager.ModuleUnloaded += (sender, args) => { ModuleUnloadedEventArgs = args; }; }
internal static void StopRemoteSupport(string deviceId) { IDevice device = ModuleManager.GetDevice(deviceId); device.StopRemoteSupport(); }
public SimpleWebServer(string prefixes, X509Certificate2 certificate = null) { Uri uri = new Uri(prefixes); this.port = uri.Port; this.certificate = certificate; _worker = new HttpWorker(); ModuleManager moduleManager = new ModuleManager(); moduleManager.Add(_worker); _listener = new HttpServer(moduleManager); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Check 'Manage objects tasks' permission if (!CurrentUser.IsAuthorizedPerResource("cms.staging", "ManageObjectsTasks")) { RedirectToAccessDenied("cms.staging", "ManageObjectsTasks"); } CurrentMaster.DisplaySiteSelectorPanel = true; // Check enabled servers var isCallback = RequestHelper.IsCallback(); if (!isCallback && !ServerInfoProvider.IsEnabledServer(SiteContext.CurrentSiteID)) { ShowInformation(GetString("ObjectStaging.NoEnabledServer")); CurrentMaster.PanelHeader.Visible = false; plcContent.Visible = false; pnlFooter.Visible = false; return; } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Setup server dropdown selectorElem.DropDownList.AutoPostBack = true; selectorElem.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged; // Set server ID SelectedServerID = ValidationHelper.GetInteger(selectorElem.Value, QueryHelper.GetInteger("serverId", 0)); // All servers if (SelectedServerID == UniSelector.US_ALL_RECORDS) { SelectedServerID = 0; selectorElem.Value = UniSelector.US_ALL_RECORDS; } else { selectorElem.Value = SelectedServerID.ToString(); } ltlScript.Text += ScriptHelper.GetScript("var currentServerId = " + SelectedServerID + ";"); HeaderActions.ActionPerformed += HeaderActions_ActionPerformed; if (!isCallback) { // Check 'Manage object tasks' permission if (!CurrentUser.IsAuthorizedPerResource("cms.staging", "ManageObjectsTasks")) { RedirectToAccessDenied("cms.staging", "ManageObjectsTasks"); } synchronizedSiteId = QueryHelper.GetInteger("siteid", 0); CurrentSiteID = SiteContext.CurrentSiteID; ucDisabledModule.SettingsKeys = "CMSStagingLogObjectChanges"; ucDisabledModule.ParentPanel = pnlNotLogged; if (synchronizedSiteId == -1) { ucDisabledModule.InfoText = GetString("objectstaging.globalandsitenotlogged"); ucDisabledModule.KeyScope = DisabledModuleScope.CurrentSiteAndGlobal; ucDisabledModule.GlobalButtonText = GetString("objectstaging.enableglobalandsiteobjects"); } else if (synchronizedSiteId == 0) { ucDisabledModule.InfoText = GetString("objectstaging.globalnotlogged"); ucDisabledModule.KeyScope = DisabledModuleScope.Global; ucDisabledModule.GlobalButtonText = GetString("objectstaging.enableglobalobjects"); } else { ucDisabledModule.InfoText = GetString("ObjectStaging.SiteNotLogged"); ucDisabledModule.KeyScope = DisabledModuleScope.Site; ucDisabledModule.SiteButtonText = GetString("objectstaging.enablesiteobjects"); } // Check logging if (!ucDisabledModule.Check()) { CurrentMaster.PanelHeader.Visible = false; plcContent.Visible = false; return; } // Get object type objectType = QueryHelper.GetString("objecttype", string.Empty); // Create "synchronize current" header action for tree root, nodes or objects with database representation if (String.IsNullOrEmpty(objectType) || objectType.StartsWithCSafe("##") || (ModuleManager.GetReadOnlyObject(objectType) != null)) { HeaderActions.AddAction(new HeaderAction { Text = GetString("ObjectTasks.SyncCurrent"), EventName = SYNCHRONIZE_CURRENT }); } // Add CSS class to panels wrapper in order it could be stacked CurrentMaster.PanelHeader.AddCssClass("header-container-multiple-panels"); // Setup title ctlAsyncLog.TitleText = GetString("Synchronization.Title"); // Get the selected types ObjectTypeTreeNode selectedNode = StagingTaskInfoProvider.ObjectTree.FindNode(objectType, (synchronizedSiteId > 0)); objectType = (selectedNode != null) ? selectedNode.GetObjectTypes(true) : string.Empty; if (!ControlsHelper.CausedPostBack(HeaderActions, btnSyncSelected, btnSyncAll)) { // Register the dialog script ScriptHelper.RegisterDialogScript(this); plcContent.Visible = true; // Initialize buttons btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");"; btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");"; btnSyncSelected.OnClientClick = "return !" + gridTasks.GetCheckSelectionScript(); // Initialize grid gridTasks.ZeroRowsText = GetString("Tasks.NoTasks"); gridTasks.OnDataReload += gridTasks_OnDataReload; gridTasks.ShowActionsMenu = true; gridTasks.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount"; StagingTaskInfo ti = new StagingTaskInfo(); gridTasks.AllColumns = SqlHelper.MergeColumns(ti.ColumnNames); pnlLog.Visible = false; TaskTypeCategories = TaskHelper.TASK_TYPE_CATEGORY_GENERAL + ";" + TaskHelper.TASK_TYPE_CATEGORY_OBJECTS + ";" + TaskHelper.TASK_TYPE_CATEGORY_DATA; } } }
public override void Install(ModuleManager manager) { throw new NotImplementedException(); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; _http = _client.GetService <HttpService>(); _settings = _client.GetService <SettingsService>() .AddModule <TwitchModule, Settings>(manager); manager.CreateCommands("streams", group => { group.MinPermissions((int)PermissionLevel.BotOwner); group.CreateCommand("list") .Do(async e => { StringBuilder builder = new StringBuilder(); var settings = _settings.Load(e.Server); foreach (var channel in settings.Channels) { builder.AppendLine($"{_client.GetChannel(channel.Key)}:\n {string.Join(", ", channel.Value.Streams.Select(x => x.Key))}"); } await _client.Reply(e, "Linked Streams", builder.ToString()); }); group.CreateCommand("add") .Parameter("twitchuser") .Parameter("channel", ParameterType.Optional) .Do(async e => { var settings = _settings.Load(e.Server); Channel channel; if (e.Args[1] != "") { channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text); } else { channel = e.Channel; } if (channel == null) { return; } var channelSettings = settings.GetOrAddChannel(channel.Id); if (channelSettings.AddStream(e.Args[0])) { await _settings.Save(e.Server, settings); await _client.Reply(e, $"Linked stream {e.Args[0]} to {channel.Name}."); } else { await _client.Reply(e, $"Stream {e.Args[0]} is already linked to {channel.Name}."); } }); group.CreateCommand("remove") .Parameter("twitchuser") .Parameter("channel", ParameterType.Optional) .Do(async e => { var settings = _settings.Load(e.Server); Channel channel; if (e.Args[1] != "") { channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text); } else { channel = e.Channel; } if (channel == null) { return; } var channelSettings = settings.GetOrAddChannel(channel.Id); if (channelSettings.RemoveStream(e.Args[0])) { await _settings.Save(e.Server.Id, settings); await _client.Reply(e, $"Unlinked stream {e.Args[0]} from {channel.Name}."); } else { await _client.Reply(e, $"Stream {e.Args[0]} is not currently linked to {channel.Name}."); } }); group.CreateGroup("set", set => { set.CreateCommand("sticky") .Parameter("value") .Parameter("channel", ParameterType.Optional) .Do(async e => { bool value = false; bool.TryParse(e.Args[0], out value); Channel channel; if (e.Args[1] != "") { channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text); } else { channel = e.Channel; } if (channel == null) { return; } var settings = _settings.Load(e.Server); var channelSettings = settings.GetOrAddChannel(channel.Id); if (channelSettings.UseSticky && !value && channelSettings.StickyMessageId != null) { var msg = channel.GetMessage(channelSettings.StickyMessageId.Value); try { await msg.Delete(); } catch (HttpException ex) when(ex.StatusCode == HttpStatusCode.NotFound) { } } channelSettings.UseSticky = value; await _settings.Save(e.Server, settings); await _client.Reply(e, $"Stream sticky for {channel.Name} set to {value}."); }); }); }); _client.Ready += (s, e) => { if (!_isRunning) { Task.Run(Run); _isRunning = true; } }; }
private static void UpgradeApplication(Func <bool> versionSpecificMethod, string newVersion, string packageName) { // Increase the timeout for upgrade request due to expensive operations like macro signing and conversion (needed for large DBs) HttpContext.Current.Server.ScriptTimeout = 14400; EventLogProvider.LogInformation(EventLogSource, "Upgrade - Start"); // Set the path to the upgrade package (this has to be done here, not in the Import method, because it's an async procedure without HttpContext) mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/" + packageName); mWebsitePath = HttpContext.Current.Server.MapPath("~/"); var dtm = new TableManager(null); using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; if (dtm.TableExists(FORM_DEFINITION_TABLE)) { UpdateClasses(); UpdateAlternativeForms(); DropTempDefinitionTable(dtm); } } // Update all views dtm.RefreshDocumentViews(); RefreshCustomViews(dtm); // Set data version SettingsKeyInfoProvider.SetValue("CMSDataVersion", newVersion); SettingsKeyInfoProvider.SetValue("CMSDBVersion", newVersion); // Clear hashtables ModuleManager.ClearHashtables(); // Clear the cache CacheHelper.ClearCache(null, true); // Drop the routes CMSDocumentRouteHelper.DropAllRoutes(); // Init the Mimetype helper (required for the Import) MimeTypeHelper.LoadMimeTypes(); // Call version specific operations if (versionSpecificMethod != null) { using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; versionSpecificMethod.Invoke(); } } // Import upgrade package with webparts, widgets... UpgradeImportPackage(); }
internal static RemoteAddress StartRemoteSupport(string deviceId) { IDevice device = ModuleManager.GetDevice(deviceId); return(device.StartRemoteSupport()); }
public static void Initialize(ContentManager content, GraphicsDevice device) { Check.NullArgument (content, "content"); Check.NullArgument (device, "device"); TileEngine.TextureManager = new TextureManager(content, device, "Graphics"); TileEngine.Player = null; // Cannot assign to abstract class, removed player TileEngine.ModuleManager = new ModuleManager(); TileEngine.Configuration = null; TileEngine.WorldManager = new WorldManager(); TileEngine.NetworkManager = new NetworkClientConnection(); TileEngine.NetworkPlayerCache = new Dictionary<uint, BaseCharacter>(); TileEngine.GraphicsDevice = device; }
public void Stop(string moduleName) { var module = GetModuleFromManager(moduleName); ModuleManager.StopModule(module); }
public ProjectService() { _projectManager = new ProjectManager(); _moduleManager = new ModuleManager(); _ideationQuestionManager = new IdeationQuestionManager(); }
private void BtnSave_Click(object sender, EventArgs e) { var id = Utility.Escape(TxtId.Text); if (string.IsNullOrEmpty(id)) { _isValid = false; LblIdValidation.Visible = true; } else { _isValid = true; LblIdValidation.Visible = false; } var name = Utility.Escape(TxtName.Text); if (string.IsNullOrEmpty(name)) { _isValid = false; LblNameValidation.Visible = true; } else { _isValid = true; LblNameValidation.Visible = false; } var birthPlace = Utility.Escape(TxtPlace.Text); var birthDate = dtpBirth.Text; var address = Utility.Escape(rTxtAddress.Text); var phone = Utility.Escape(TxtPhone.Text); if (_isValid) { if (_updateMode) { var set = "\"Name\"= '" + name + "', " + "\"BirthPlace\"= '" + birthPlace + "', " + "\"BirthDate\"= '" + birthDate + "', " + "\"Address\"= '" + address + "', " + "\"Phone\"= '" + phone + "'"; var where = "\"UserId\"='" + Employee.EmployeeId + "'"; ModuleManager.GetInstance().Update(TMConstants.Table.EMPLOYEE, set, where); } else { string values = "('" + id + "', " + "'" + name + "', " + "'" + birthPlace + "', " + "'" + birthDate + "', " + "'" + address + "', " + "'" + phone + "')"; ModuleManager.GetInstance().Insert(TMConstants.Table.EMPLOYEE, values); } this.Close(); } }