public override void Accept(Plugins.IVisitor visitor) { base.Accept(visitor); Params = VisitAndReplace(Params, visitor); Condition = VisitAndReplace(Condition, visitor, true); }
public IEnumerable<IPlugin> GetDependentPluginsOn(Plugins.IPlugin plugin) { var openGenericType = typeof(IDependsOnPlugin<>); var closedGenericType = openGenericType.MakeGenericType(plugin.GetType()); return kernel.GetAll(closedGenericType).Select(pluginObject => { return (IPlugin)pluginObject; }); }
/// <summary> /// Gets the plugins form. /// </summary> /// <param name="settingsService">The settings service.</param> /// <param name="viewModelNames">The view model names.</param> /// <param name="plugins">The plugins.</param> /// <returns>The plugins form.</returns> public IPluginsView GetPluginsForm( ISettingsService settingsService, IEnumerable<string> viewModelNames, Plugins plugins) { return new PluginsForm( settingsService, viewModelNames, plugins); }
/// <summary> /// Initializes a new instance of the <see cref="PluginsForm" /> class. /// </summary> /// <param name="settingsService">The settings service.</param> /// <param name="viewModelNames">The view model names.</param> /// <param name="plugins">The plugins.</param> public PluginsForm( ISettingsService settingsService, IEnumerable<string> viewModelNames, Plugins plugins) { this.InitializeComponent(); this.Presenter = new PluginsPresenter(this, settingsService); this.Presenter.Load(viewModelNames, plugins.Items); }
/// <summary> /// 构造函数 /// </summary> /// <param name="plugindir"></param> /// <param name="plugis"></param> /// <param name="loaded"></param> public Plugin(DirectoryInfo plugindir, Plugins plugis, string name, int[] version, bool loaded) { this.PluginDir = plugindir; this.Plugins = plugis; this.Name = name; this.Version = version; this.DefaultLoad = loaded; appDomainToPlugin.Add(plugindir.FullName, this); attributeStore = new AssemblyStore(); attributeStore.Update(plugindir); addinstore = new AddInStore(attributeStore); }
/// <summary> /// Initializes a new instance of the <see cref="PluginsForm" /> class. /// </summary> /// <param name="settingsService">The settings service.</param> /// <param name="viewModelNames">The view model names.</param> /// <param name="plugins">The plugins.</param> public PluginsForm( ISettingsService settingsService, IEnumerable<string> viewModelNames, Plugins plugins) { this.InitializeComponent(); this.mvxListViewCore.SetBorderVisibility(BorderStyle.None); this.mvxListViewCommunity.SetBorderVisibility(BorderStyle.None); this.mvxListViewUser.SetBorderVisibility(BorderStyle.None); this.Presenter = new PluginsPresenter(this, settingsService); this.Presenter.Load(viewModelNames, plugins.Items); }
// TODO: about box should list all of the loaded plugins along with // their version numbers private static void DoLoadPlugins() { Gear.Helpers.Unused.Value = typeof(IStartup); // force shared.dll to load (we need to do this or the plugins will fail when they try to use shared types from Bosses.xml) string loc = Assembly.GetExecutingAssembly().Location; string root = Path.GetDirectoryName(loc); string path = Path.Combine(root, "plugins"); Log.WriteLine(TraceLevel.Verbose, "Startup", "loading plugins using '{0}'", path); // TODO: we might want required and optional plugins Plugins plugins = new Plugins(path, "*.dll"); foreach (KeyValuePair<string, Exception> entry in plugins.Failures) { Console.Error.WriteLine("Failed to load {0}: {1}", entry.Key, entry.Value.Message); if (entry.Value.InnerException != null) Console.Error.WriteLine(" Inner Exception: {0}", entry.Value.InnerException); } }
static void Main(string[] args) { Plugins<IPlugin> plugins = new Plugins<IPlugin>(); plugins.LoadFrom(@"./"); plugins[1].Do(); Plugins<IMyPlugin> myPlugins = new Plugins<IMyPlugin>(); myPlugins.LoadFrom(@"./"); foreach (IMyPlugin plugin in myPlugins) { plugin.DIY(); } GenericMEFPluginLoader<IPlugin> loader = new GenericMEFPluginLoader<IPlugin>(@"./MEFPlugins"); List<IPlugin> MEFPlugins = loader.Plugins; foreach(var item in MEFPlugins) { item.Do(); } MEFPlugins[0].Do(); Console.ReadKey(); }
private void SetClickHandlerForSubMenu(Plugins.MenuItem menu) { foreach (ToolStripDropDownItem subMenuItem in menu.UnderlyingMenuItem.DropDownItems) { subMenuItem.Click += PluginMenuItem_Click; SetClickHandlerForSubMenu((Plugins.MenuItem)(subMenuItem.Tag)); } }
public override void Configure(Container container) { if (Use != null) { Use(container); } if (EnableRazor) { Plugins.Add(new RazorFormat()); } Plugins.Add(new SwaggerFeature()); Plugins.Add(new RequestInfoFeature()); Plugins.Add(new RequestLogsFeature()); Plugins.Add(new ServerEventsFeature()); Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(AutoValidationValidator).Assembly); var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider); container.Register <IDbConnectionFactory>(dbFactory); dbFactory.RegisterConnection("testdb", "~/App_Data/test.sqlite".MapAbsolutePath(), SqliteDialect.Provider); using (var db = dbFactory.OpenDbConnection()) { db.DropAndCreateTable <Rockstar>(); //Create table if not exists db.Insert(Rockstar.SeedData); //Populate with seed data } using (var db = dbFactory.OpenDbConnection("testdb")) { db.DropAndCreateTable <Rockstar>(); //Create table if not exists db.Insert(new Rockstar(1, "Test", "Database", 27)); } SetConfig(new HostConfig { AdminAuthSecret = "secret", DebugMode = true, }); if (EnableAuth) { Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(AppSettings), new CredentialsAuthProvider(AppSettings), new ApiKeyAuthProvider(AppSettings) { RequireSecureConnection = false }, new JwtAuthProvider(AppSettings) { AuthKey = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? null : AesUtils.CreateKey(), RequireSecureConnection = false, HashAlgorithm = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? "RS256" : "HS256", PublicKey = JwtRsaPublicKey, PrivateKey = JwtRsaPrivateKey, EncryptPayload = JwtEncryptPayload, FallbackAuthKeys = FallbackAuthKeys, FallbackPublicKeys = FallbackPublicKeys, }, }) { IncludeRegistrationService = true, }); container.Resolve <IAuthRepository>().InitSchema(); } }
internal void OnMainMenuOpening(Plugins.MainMenuLocation menu, SelectedNodes selectedNodes) { }
private void setupMapCursorLocation(ref Plugins.MapCursorLocation mcl, int mx, int my) { mcl.m.X = mcl.mx = mx; mcl.m.Y = mcl.my = my; mcl.p.X = mcl.px = mx / ZoomLevel + hscrollbar.Value; mcl.p.Y = mcl.py = my / ZoomLevel + vscrollbar.Value; mcl.t.X = mcl.tx = mcl.px / 16; mcl.t.Y = mcl.ty = mcl.py / 16; Global.InvokeCursorMove(true, mcl.tx, mcl.ty); }
public void registerPlugin(Plugins.IMapPlugin mapPlugin, Guid guid) { tools[guid] = mapPlugin; }
private Message create_plugin_list(PluginManager manager) { Message message = new Message(); message.type = Message.Type.Plugins; message.creator_plugin_hash = this.GetHashCode().ToString(); Plugins message_content = new Plugins(); Hashtable plugins = new Hashtable(); Plugins plugin_message = new Plugins(); ArrayList loaded_plugins = manager.get_all(); PluginInfo info; foreach(Plugin plug in loaded_plugins) { info = new PluginInfo(); info.name = plug.name; info.hash = plug.GetHashCode().ToString(); info.version = plug.version; plugins[info.name] = info; } message_content.plugins = plugins; message.content = message_content; return message; }
public override void Accept(Plugins.IVisitor visitor) { Value = VisitAndReplace(Value, visitor); }
public override void Configure(Funq.Container container) { var appSettings = new AppSettings(); var successRedirectUrlFilter = ConfigurationManager.AppSettings["SuccessRedirectUrlFilter"]; var authServerUrl = appSettings.GetString("oauth.auth0.OAuthServerUrl"); Plugins.Add(new AuthFeature(() => new AuthUserSession(), //Use your own typed Custom UserSession type new IAuthProvider[] { new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials new TwitterAuthProvider(appSettings) { SuccessRedirectUrlFilter = (authProvider, url) => successRedirectUrlFilter }, //Sign-in with Twitter new FacebookAuthProvider(appSettings) { SuccessRedirectUrlFilter = (authProvider, url) => successRedirectUrlFilter }, //Sign-in with Facebook new DigestAuthProvider(appSettings), //Sign-in with Digest Auth new BasicAuthProvider(), //Sign-in with Basic Auth new GoogleOAuth2Provider(appSettings), //Sign-in with Google OpenId new LinkedInOAuth2Provider(appSettings), new VkAuthProvider(appSettings) { ApplicationId = "5205626", SecureKey = "Vjbd20LrrW1stdaWONty", SuccessRedirectUrlFilter = (authProvider, url) => successRedirectUrlFilter }, new FourSquareOAuth2Provider(appSettings), new GithubAuthProvider(appSettings), new Auth0Provider(appSettings, authServerUrl) })); Plugins.Add(new SessionFeature()); var allowDomainForCors = new List <string>(ConfigurationManager.AppSettings["allowDomainForCORS"].Split(new[] { ';' })); Plugins.Add(new RegistrationFeature()); var cors = new CorsFeature( allowOriginWhitelist: allowDomainForCors, allowCredentials: true, allowedHeaders: "Content-Type, Allow, Authorization"); Plugins.Add(cors); var connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString; var dbConFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider); container.Register <IDbConnectionFactory>(dbConFactory); container.Register <IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())); var authRepo = (OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>(); authRepo.InitSchema(); CreateAdmine(authRepo); container.Register(new ProjectDbContext(connectionString)); container.Register(c => new UnitOfWork(c.Resolve <ProjectDbContext>())); container.Register(c => new UserProfileRepository(c.Resolve <ProjectDbContext>())); container.Register(c => new UserProfileService(c.Resolve <UserProfileRepository>(), c.Resolve <UnitOfWork>())); }
/// <summary> /// Application specific configuration /// This method should initialize any IoC resources utilized by your web service classes. /// </summary> // public override void Configure(Container container) // { // authKey = AesUtils.CreateKey(); // fallbackAuthKey = AesUtils.CreateKey(); // var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); // var publicKey = privateKey.ToPublicRsaParameters(); // var privateKeyXml = privateKey.ToPrivateKeyXml(); // var publicKeyXml = privateKey.ToPublicKeyXml(); // AppSettings = new DictionarySettings(new Dictionary<string, string> { // { "jwt.AuthKeyBase64", Convert.ToBase64String(authKey) }, // { "jwt.AuthKeyBase64.1", Convert.ToBase64String(fallbackAuthKey) }, // {"PrivateKeyXml" ,"{PrivateKey2016Xml}"}, // { "jwt.RequireSecureConnection", "False" }, // {"oauth.GoogleOAuth.ConsumerKey","485362488543-e1eiujr63lmf88hd4v5roaq2hrtsfgul.apps.googleusercontent.com" }, // {"oauth.GoogleOAuth.ConsumerSecret","ryNIz_W-2KDmQ6E4RPXQcJEM" } // }); // SetConfig(new HostConfig // { // DebugMode = true, // UseCamelCase = true, // }); // SetConfig(new HostConfig // { // DefaultContentType = MimeTypes.Json // }); // // Plugins.Add(new CorsFeature()); // Plugins.Add(new PostmanFeature()); // Plugins.Add(new SwaggerFeature()); // Plugins.Add(new AdminFeature()); // Plugins.Add(new ValidationFeature()); // string[] allowOrgins = new string[] {"http://*****:*****@#qwe;MultipleActiveResultSets=True", SqlServerDialect.Provider); // container.Register<IDbConnectionFactory>(dbFactory); // container.Register<IAuthRepository>(c => // new OrmLiteAuthRepository(dbFactory) { UseDistinctRoleTables = true }); // //Create UserAuth RDBMS Tables // container.Resolve<IAuthRepository>().InitSchema(); // //Also store User Sessions in SQL Server // container.RegisterAs<OrmLiteCacheClient, ICacheClient>(); // container.Resolve<ICacheClient>().InitSchema(); // // Plugins.Add(new SessionFeature() { }); // //Add Support for // Plugins.Add(new AuthFeature(() => new AuthUserSession(), // new IAuthProvider[] { // new CredentialsAuthProvider(){ PersistSession = true}, // new BasicAuthProvider(), // new JwtAuthProvider(AppSettings) { // PersistSession = true, // //HashAlgorithm = "RS256", // //PrivateKeyXml = AppSettings.GetString("PrivateKeyXml") // AuthKey = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? null : AesUtils.CreateKey(), // RequireSecureConnection = false, // HashAlgorithm = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? "RS256" : "HS256", // PublicKey = JwtRsaPublicKey, // PrivateKey = JwtRsaPrivateKey, // EncryptPayload = JwtEncryptPayload, // FallbackAuthKeys = FallbackAuthKeys, // FallbackPublicKeys = FallbackPublicKeys, // // ExpireTokensIn = TimeSpan.FromDays(365), // ExpireRefreshTokensIn = TimeSpan.FromDays(365), // Refresh Token Expiry // Provider = "mp", // SaveExtendedUserInfo = true, // SetBearerTokenOnAuthenticateResponse = true, // SessionExpiry = TimeSpan.FromDays(365), // Issuer="MF", // ExpireTokensInDays = 20 // }, // //new ApiKeyAuthProvider(AppSettings), //Sign-in with API Key // //new CredentialsAuthProvider(), //Sign-in with UserName/Password credentials // // new BasicAuthProvider(), //Sign-in with HTTP Basic Auth // //new DigestAuthProvider(AppSettings), //Sign-in with HTTP Digest Auth // //new TwitterAuthProvider(AppSettings), //Sign-in with Twitter // //new FacebookAuthProvider(AppSettings), //Sign-in with Facebook // //new YahooOpenIdOAuthProvider(AppSettings), //Sign-in with Yahoo OpenId // //new OpenIdOAuthProvider(AppSettings), //Sign-in with Custom OpenId // //new GoogleOAuth2Provider(AppSettings), //Sign-in with Google OAuth2 Provider // //new LinkedInOAuth2Provider(AppSettings), //Sign-in with LinkedIn OAuth2 Provider // //new GithubAuthProvider(AppSettings), //Sign-in with GitHub OAuth Provider // //new YandexAuthProvider(AppSettings), //Sign-in with Yandex OAuth Provider // //new VkAuthProvider(AppSettings), //Sign-in with VK.com OAuth Provider // })); // // Plugins.Add(new AuthFeature(() => new AuthUserSession(), // //new IAuthProvider[] { // // new JwtAuthProvider(AppSettings) { AuthKey = AesUtils.CreateKey() }, // // new CredentialsAuthProvider(AppSettings), // // //... // //})); // Plugins.Add(new RegistrationFeature()); // } public override void Configure(Container container) { //Store UserAuth in SQL Server var dbFactory = new OrmLiteConnectionFactory( "server=.;Database=IdentityDB;user=sa;pwd=123!@#qwe;MultipleActiveResultSets=True", SqlServerDialect.Provider); container.Register <IDbConnectionFactory>(dbFactory); container.Register <IAuthRepository>(c => new OrmLiteAuthRepository(dbFactory) { UseDistinctRoleTables = true }); //Create UserAuth RDBMS Tables container.Resolve <IAuthRepository>().InitSchema(); //Also store User Sessions in SQL Server container.RegisterAs <OrmLiteCacheClient, ICacheClient>(); container.Resolve <ICacheClient>().InitSchema(); var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); var publicKey = privateKey.ToPublicRsaParameters(); var privateKeyXml = privateKey.ToPrivateKeyXml(); var publicKeyXml = privateKey.ToPublicKeyXml(); // just for testing, create a privateKeyXml on every instance Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new JwtAuthProvider { HashAlgorithm = "RS256", PrivateKeyXml = privateKeyXml, RequireSecureConnection = false, }, new CredentialsAuthProvider() })); this.GlobalRequestFilters.Add((httpReq, httpRes, requestDto) => { httpReq.SetSessionId("2MFD2Q706bNlpgG4MdMq"); //IRequest req = httpReq; //req.Items[Keywords.Session] = null; }); Plugins.Add(new RegistrationFeature()); // uncomment to create a first new user //var authRepo = GetAuthRepository(); //authRepo.CreateUserAuth(new UserAuth //{ // Id = 1, // UserName = "******", // FirstName = "First", // LastName = "Last", // DisplayName = "Display", //}, "p@55word"); }
//After configure called public static void AfterInit() { StartedAt = DateTime.UtcNow; if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) { config.IgnoreFormatsInMetadata.Add("xml"); } if ((Feature.Json & config.EnableFeatures) != Feature.Json) { config.IgnoreFormatsInMetadata.Add("json"); } if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) { config.IgnoreFormatsInMetadata.Add("jsv"); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { config.IgnoreFormatsInMetadata.Add("csv"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { config.IgnoreFormatsInMetadata.Add("html"); } if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) { config.IgnoreFormatsInMetadata.Add("soap11"); } if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) { config.IgnoreFormatsInMetadata.Add("soap12"); } } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { Plugins.RemoveAll(x => x is HtmlFormat); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { Plugins.RemoveAll(x => x is CsvFormat); } if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) { Plugins.RemoveAll(x => x is MarkdownFormat); } if ((Feature.PredefinedRoutes & config.EnableFeatures) != Feature.PredefinedRoutes) { Plugins.RemoveAll(x => x is PredefinedRoutesFeature); } if ((Feature.Metadata & config.EnableFeatures) != Feature.Metadata) { Plugins.RemoveAll(x => x is MetadataFeature); } if ((Feature.RequestInfo & config.EnableFeatures) != Feature.RequestInfo) { Plugins.RemoveAll(x => x is RequestInfoFeature); } if ((Feature.Razor2 & config.EnableFeatures) != Feature.Razor2) { Plugins.RemoveAll(x => x is IRazor2Plugin); //external } if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) { Plugins.RemoveAll(x => x is IProtoBufPlugin); //external } if ((Feature.MsgPack & config.EnableFeatures) != Feature.MsgPack) { Plugins.RemoveAll(x => x is IMsgPackPlugin); //external } if (ExceptionHandler == null) { ExceptionHandler = (httpReq, httpRes, operationName, ex) => { var errorMessage = String.Format("Error occured while Processing Request: {0}", ex.Message); var statusCode = ex.ToStatusCode(); //httpRes.WriteToResponse always calls .Close in it's finally statement so //if there is a problem writing to response, by now it will be closed if (!httpRes.IsClosed) { httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode); } }; } if (config.ServiceStackHandlerFactoryPath != null) { config.ServiceStackHandlerFactoryPath = config.ServiceStackHandlerFactoryPath.TrimStart('/'); } var specifiedContentType = config.DefaultContentType; //Before plugins loaded ConfigurePlugins(); AppHost.LoadPlugin(Plugins.ToArray()); pluginsLoaded = true; AfterPluginsLoaded(specifiedContentType); var registeredCacheClient = AppHost.TryResolve <ICacheClient>(); using (registeredCacheClient) { if (registeredCacheClient == null) { Container.Register <ICacheClient>(new MemoryCacheClient()); } } ReadyAt = DateTime.UtcNow; }
// public override async Task ProcessRequest(HttpContext context, Func<Task> next) // { // await context.Response.WriteAsync("Hello World!"); // } public override void Configure(Container container) { JsConfig.DateHandler = DateHandler.ISO8601; container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(Path.Combine(_dataDir, "db.sqlite"), SqliteDialect.Provider)); var dbFactory = TryResolve <IDbConnectionFactory>(); // var hostConfig = new HostConfig // { // DebugMode = false, // enables some debugging features // EnableFeatures = Feature.All.Remove(Feature.Csv), // removes the CSV format // HandlerFactoryPath = "/api" // moves the ServiceStack api surface under a sub-route // }; // hostConfig.GlobalResponseHeaders["X-Powered-By"] = "FoxValley Power"; // SetConfig(hostConfig); // Routes.Add(typeof(PingRequest), "/pinger", "GET"); Plugins.Add(new PostmanFeature()); Plugins.Add(new CorsFeature()); Plugins.Add(new YamlFormat(true)); var authProviders = new IAuthProvider[] { new CredentialsAuthProvider(), new BasicAuthProvider(), new ApiKeyAuthProvider(), new JwtAuthProvider() { RequireSecureConnection = false, HashAlgorithm = "RS256", PrivateKeyXml = GetPrivateKeyXml() }, new DigestAuthProvider(this.AppSettings), new FacebookAuthProvider(this.AppSettings), new TwitterAuthProvider(this.AppSettings), new GithubAuthProvider(this.AppSettings) }; Plugins.Add(new AuthFeature(() => new AuthUserSession(), authProviders) { SaveUserNamesInLowerCase = true, }); Plugins.Add(new RegistrationFeature() { AtRestPath = "/register" }); // CACHING // container.Register<IRedisClientsManager>(c => new RedisManagerPool("localhost:6379")); if (container.TryResolve <IRedisClientsManager>() != null) // caching redis { container.Register(c => c.Resolve <IRedisClientsManager>().GetCacheClient()); } else if (dbFactory != null) // caching database { container.Register <ICacheClient>(new OrmLiteCacheClient() { DbFactory = dbFactory }); } else // caching in-memory { container.Register <ICacheClient>(new MemoryCacheClient()); } (TryResolve <ICacheClient>() as IRequiresSchema)?.InitSchema(); // AUTHENTICATION IAuthRepository authRepository; if (dbFactory != null) { authRepository = new OrmLiteAuthRepository(dbFactory); } else { authRepository = new InMemoryAuthRepository(); } Register <IAuthRepository>(authRepository); (TryResolve <IAuthRepository>() as IRequiresSchema)?.InitSchema(); var authRepo = TryResolve <IAuthRepository>(); if (authRepo != null) { var adminUser = authRepo.GetUserAuthByUserName("admin"); if (adminUser == null) { adminUser = authRepo.CreateUserAuth( new UserAuth { UserName = "******", DisplayName = "Administrator", Email = "*****@*****.**" }, "admin"); } var roles = authRepo.GetRoles(adminUser); if (!roles.Contains("Admin")) { authRepo.AssignRoles(adminUser, new [] { "Admin" }); } var guestUser = authRepo.GetUserAuthByUserName("guest"); if (guestUser == null) { guestUser = authRepo.CreateUserAuth( new UserAuth { UserName = "******", DisplayName = "Guest", Email = "*****@*****.**" }, "guest"); } } if (dbFactory != null) { using (var db = dbFactory.OpenDbConnection()) { db.CreateTableIfNotExists(typeof(Bookmark)); var bkFile = Path.Combine(_dataDir, "bookmarks.csv"); var bkFileOld = bkFile + ".old"; if (File.Exists(bkFileOld)) { File.Delete(bkFile); } if (File.Exists(bkFile)) { using (var stream = File.OpenRead(bkFile)) { var bookmarks = BookmarkUtils.ToBookmarks(stream); foreach (var bookmark in bookmarks) { bookmark.CreatedBy = "admin"; bookmark.CreatedById = 1; bookmark.CreatedOn = DateTime.UtcNow; bookmark.ModifiedBy = "admin"; bookmark.ModifiedById = 1; bookmark.ModifiedOn = DateTime.UtcNow; try { db.Insert(bookmark); } catch {} } } File.Move(bkFile, bkFile + ".old"); } } var autoQuery = new AutoQueryFeature { MaxLimit = 100 }; Plugins.Add(autoQuery); } Plugins.Add(new OpenApiFeature() { UseCamelCaseSchemaPropertyNames = true }); }
private async void Application_Startup(object sender, StartupEventArgs e) { if (Config.local.showloadingscreen) { splash = new Views.SplashScreen(); splash.Show(); splash.BusyContent = "Loading main window"; } AutomationHelper.syncContext = System.Threading.SynchronizationContext.Current; System.Threading.Thread.CurrentThread.Name = "UIThread"; if (!Config.local.isagent) { if (!Config.local.showloadingscreen) { notifyIcon.Visible = true; } } else { notifyIcon.Visible = true; } if (Config.local.files_pending_deletion.Length > 0) { bool sucess = true; foreach (var f in Config.local.files_pending_deletion) { try { if (System.IO.File.Exists(f)) { System.IO.File.Delete(f); } } catch (Exception ex) { sucess = false; Log.Error(ex.ToString()); } } if (sucess) { Config.local.files_pending_deletion = new string[] { }; Config.Save(); } } RobotInstance.instance.Status += App_Status; Input.InputDriver.Instance.initCancelKey(Config.local.cancelkey); await Task.Run(async() => { try { if (Config.local.showloadingscreen) { splash.BusyContent = "loading plugins"; } // Plugins.LoadPlugins(RobotInstance.instance, Interfaces.Extensions.ProjectsDirectory); Plugins.LoadPlugins(RobotInstance.instance, Interfaces.Extensions.PluginsDirectory, false); if (Config.local.showloadingscreen) { splash.BusyContent = "Initialize main window"; } await RobotInstance.instance.init(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }); }
public override void ExecuteBuild() { var UEProjectRoot = ParseParamValue("UEProjectRoot"); if (UEProjectRoot == null) { UEProjectRoot = CmdEnv.LocalRoot; } var UEProjectDirectory = ParseParamValue("UEProjectDirectory"); if (UEProjectDirectory == null) { throw new AutomationException("Missing required command line argument: 'UEProjectDirectory'"); } var UEProjectName = ParseParamValue("UEProjectName"); if (UEProjectName == null) { UEProjectName = ""; } var LocalizationProjectNames = new List <string>(); { var LocalizationProjectNamesStr = ParseParamValue("LocalizationProjectNames"); if (LocalizationProjectNamesStr != null) { foreach (var ProjectName in LocalizationProjectNamesStr.Split(',')) { LocalizationProjectNames.Add(ProjectName.Trim()); } } } var LocalizationProviderName = ParseParamValue("LocalizationProvider"); if (LocalizationProviderName == null) { LocalizationProviderName = ""; } var LocalizationStepNames = new List <string>(); { var LocalizationStepNamesStr = ParseParamValue("LocalizationSteps"); if (LocalizationStepNamesStr == null) { LocalizationStepNames.AddRange(new string[] { "Download", "Gather", "Import", "Export", "Compile", "GenerateReports", "Upload" }); } else { foreach (var StepName in LocalizationStepNamesStr.Split(',')) { LocalizationStepNames.Add(StepName.Trim()); } } LocalizationStepNames.Add("Monolithic"); // Always allow the monolithic scripts to run as we don't know which steps they do } var ShouldGatherPlugins = ParseParam("IncludePlugins"); var IncludePlugins = new List <string>(); var ExcludePlugins = new List <string>(); if (ShouldGatherPlugins) { var IncludePluginsStr = ParseParamValue("IncludePlugins"); if (IncludePluginsStr != null) { foreach (var PluginName in IncludePluginsStr.Split(',')) { IncludePlugins.Add(PluginName.Trim()); } } var ExcludePluginsStr = ParseParamValue("ExcludePlugins"); if (ExcludePluginsStr != null) { foreach (var PluginName in ExcludePluginsStr.Split(',')) { ExcludePlugins.Add(PluginName.Trim()); } } } var ShouldGatherPlatforms = ParseParam("IncludePlatforms"); var AdditionalCommandletArguments = ParseParamValue("AdditionalCommandletArguments"); if (AdditionalCommandletArguments == null) { AdditionalCommandletArguments = ""; } var EnableParallelGather = ParseParam("ParallelGather"); var StartTime = DateTime.UtcNow; var LocalizationBatches = new List <LocalizationBatch>(); // Add the static set of localization projects as a batch if (LocalizationProjectNames.Count > 0) { LocalizationBatches.Add(new LocalizationBatch(UEProjectDirectory, UEProjectDirectory, "", LocalizationProjectNames)); } // Build up any additional batches needed for platforms if (ShouldGatherPlatforms) { var PlatformsRootDirectory = new DirectoryReference(CombinePaths(UEProjectRoot, UEProjectDirectory, "Platforms")); if (DirectoryReference.Exists(PlatformsRootDirectory)) { foreach (DirectoryReference PlatformDirectory in DirectoryReference.EnumerateDirectories(PlatformsRootDirectory)) { // Find the localization targets defined for this platform var PlatformTargetNames = GetLocalizationTargetsFromDirectory(new DirectoryReference(CombinePaths(PlatformDirectory.FullName, "Config", "Localization"))); if (PlatformTargetNames.Count > 0) { var RootRelativePluginPath = PlatformDirectory.MakeRelativeTo(new DirectoryReference(UEProjectRoot)); RootRelativePluginPath = RootRelativePluginPath.Replace('\\', '/'); // Make sure we use / as these paths are used with P4 LocalizationBatches.Add(new LocalizationBatch(UEProjectDirectory, RootRelativePluginPath, "", PlatformTargetNames)); } } } } // Build up any additional batches needed for plugins if (ShouldGatherPlugins) { var PluginsRootDirectory = new DirectoryReference(CombinePaths(UEProjectRoot, UEProjectDirectory)); IReadOnlyList <PluginInfo> AllPlugins = Plugins.ReadPluginsFromDirectory(PluginsRootDirectory, "Plugins", UEProjectName.Length == 0 ? PluginType.Engine : PluginType.Project); // Add a batch for each plugin that meets our criteria var AvailablePluginNames = new HashSet <string>(); foreach (var PluginInfo in AllPlugins) { AvailablePluginNames.Add(PluginInfo.Name); bool ShouldIncludePlugin = (IncludePlugins.Count == 0 || IncludePlugins.Contains(PluginInfo.Name)) && !ExcludePlugins.Contains(PluginInfo.Name); if (ShouldIncludePlugin && PluginInfo.Descriptor.LocalizationTargets != null && PluginInfo.Descriptor.LocalizationTargets.Length > 0) { var RootRelativePluginPath = PluginInfo.Directory.MakeRelativeTo(new DirectoryReference(UEProjectRoot)); RootRelativePluginPath = RootRelativePluginPath.Replace('\\', '/'); // Make sure we use / as these paths are used with P4 var PluginTargetNames = new List <string>(); foreach (var LocalizationTarget in PluginInfo.Descriptor.LocalizationTargets) { PluginTargetNames.Add(LocalizationTarget.Name); } LocalizationBatches.Add(new LocalizationBatch(UEProjectDirectory, RootRelativePluginPath, PluginInfo.Name, PluginTargetNames)); } } // If we had an explicit list of plugins to include, warn if any were missing foreach (string PluginName in IncludePlugins) { if (!AvailablePluginNames.Contains(PluginName)) { LogWarning("The plugin '{0}' specified by -IncludePlugins wasn't found and will be skipped.", PluginName); } } } // Create a single changelist to use for all changes int PendingChangeList = 0; if (P4Enabled) { var ChangeListCommitMessage = String.Format("Localization Automation using CL {0}", P4Env.Changelist); if (File.Exists(CombinePaths(CmdEnv.LocalRoot, @"Engine/Restricted/NotForLicensees/Build/EpicInternal.txt"))) { ChangeListCommitMessage += "\n#okforgithub ignore"; } PendingChangeList = P4.CreateChange(P4Env.Client, ChangeListCommitMessage); } // Prepare to process each localization batch var LocalizationTasks = new List <LocalizationTask>(); foreach (var LocalizationBatch in LocalizationBatches) { var LocalizationTask = new LocalizationTask(LocalizationBatch, UEProjectRoot, LocalizationProviderName, PendingChangeList, this); LocalizationTasks.Add(LocalizationTask); // Make sure the Localization configs and content is up-to-date to ensure we don't get errors later on if (P4Enabled) { LogInformation("Sync necessary content to head revision"); P4.Sync(P4Env.Branch + "/" + LocalizationTask.Batch.LocalizationTargetDirectory + "/Config/Localization/..."); P4.Sync(P4Env.Branch + "/" + LocalizationTask.Batch.LocalizationTargetDirectory + "/Content/Localization/..."); } // Generate the info we need to gather for each project foreach (var ProjectName in LocalizationTask.Batch.LocalizationProjectNames) { LocalizationTask.ProjectInfos.Add(GenerateProjectInfo(LocalizationTask.RootLocalizationTargetDirectory, ProjectName, LocalizationStepNames)); } } // Hash the current PO files on disk so we can work out whether they actually change Dictionary <string, byte[]> InitalPOFileHashes = null; if (P4Enabled) { InitalPOFileHashes = GetPOFileHashes(LocalizationBatches, UEProjectRoot); } // Download the latest translations from our localization provider if (LocalizationStepNames.Contains("Download")) { foreach (var LocalizationTask in LocalizationTasks) { if (LocalizationTask.LocProvider != null) { foreach (var ProjectInfo in LocalizationTask.ProjectInfos) { LocalizationTask.LocProvider.DownloadProjectFromLocalizationProvider(ProjectInfo.ProjectName, ProjectInfo.ImportInfo); } } } } // Begin the gather command for each task // These can run in parallel when ParallelGather is enabled { var EditorExe = CombinePaths(CmdEnv.LocalRoot, @"Engine/Binaries/Win64/UE4Editor-Cmd.exe"); // Set the common basic editor arguments var EditorArguments = P4Enabled ? String.Format("-SCCProvider=Perforce -P4Port={0} -P4User={1} -P4Client={2} -P4Passwd={3} -P4Changelist={4} -EnableSCC -DisableSCCSubmit", P4Env.ServerAndPort, P4Env.User, P4Env.Client, P4.GetAuthenticationToken(), PendingChangeList) : "-SCCProvider=None"; if (IsBuildMachine) { EditorArguments += " -BuildMachine"; } EditorArguments += " -Unattended -LogLocalizationConflicts"; if (EnableParallelGather) { EditorArguments += " -multiprocess"; } if (!String.IsNullOrEmpty(AdditionalCommandletArguments)) { EditorArguments += " " + AdditionalCommandletArguments; } // Set the common process run options var CommandletRunOptions = ERunOptions.Default | ERunOptions.NoLoggingOfRunCommand; // Disable logging of the run command as it will print the exit code which GUBP can pick up as an error (we do that ourselves later) if (EnableParallelGather) { CommandletRunOptions |= ERunOptions.NoWaitForExit; } foreach (var LocalizationTask in LocalizationTasks) { var ProjectArgument = String.IsNullOrEmpty(UEProjectName) ? "" : String.Format("\"{0}\"", Path.Combine(LocalizationTask.RootWorkingDirectory, String.Format("{0}.uproject", UEProjectName))); foreach (var ProjectInfo in LocalizationTask.ProjectInfos) { var LocalizationConfigFiles = new List <string>(); foreach (var LocalizationStep in ProjectInfo.LocalizationSteps) { if (LocalizationStepNames.Contains(LocalizationStep.Name)) { LocalizationConfigFiles.Add(LocalizationStep.LocalizationConfigFile); } } if (LocalizationConfigFiles.Count > 0) { var Arguments = String.Format("{0} -run=GatherText -config=\"{1}\" {2}", ProjectArgument, String.Join(";", LocalizationConfigFiles), EditorArguments); LogInformation("Running localization commandlet for '{0}': {1}", ProjectInfo.ProjectName, Arguments); LocalizationTask.GatherProcessResults.Add(Run(EditorExe, Arguments, null, CommandletRunOptions)); } else { LocalizationTask.GatherProcessResults.Add(null); } } } } // Wait for each commandlet process to finish and report the result. // This runs even for non-parallel execution to log the exit state of the process. foreach (var LocalizationTask in LocalizationTasks) { for (int ProjectIndex = 0; ProjectIndex < LocalizationTask.ProjectInfos.Count; ++ProjectIndex) { var ProjectInfo = LocalizationTask.ProjectInfos[ProjectIndex]; var RunResult = LocalizationTask.GatherProcessResults[ProjectIndex]; if (RunResult != null) { RunResult.WaitForExit(); RunResult.OnProcessExited(); RunResult.DisposeProcess(); if (RunResult.ExitCode == 0) { LogInformation("The localization commandlet for '{0}' exited with code 0.", ProjectInfo.ProjectName); } else { LogWarning("The localization commandlet for '{0}' exited with code {1} which likely indicates a crash.", ProjectInfo.ProjectName, RunResult.ExitCode); } } } } // Upload the latest sources to our localization provider if (LocalizationStepNames.Contains("Upload")) { foreach (var LocalizationTask in LocalizationTasks) { if (LocalizationTask.LocProvider != null) { // Upload all text to our localization provider for (int ProjectIndex = 0; ProjectIndex < LocalizationTask.ProjectInfos.Count; ++ProjectIndex) { var ProjectInfo = LocalizationTask.ProjectInfos[ProjectIndex]; var RunResult = LocalizationTask.GatherProcessResults[ProjectIndex]; if (RunResult != null && RunResult.ExitCode == 0) { // Recalculate the split platform paths before doing the upload, as the export may have changed them ProjectInfo.ExportInfo.CalculateSplitPlatformNames(LocalizationTask.RootLocalizationTargetDirectory); LocalizationTask.LocProvider.UploadProjectToLocalizationProvider(ProjectInfo.ProjectName, ProjectInfo.ExportInfo); } else { LogWarning("Skipping upload to the localization provider for '{0}' due to an earlier commandlet failure.", ProjectInfo.ProjectName); } } } } } // Clean-up the changelist so it only contains the changed files, and then submit it (if we were asked to) if (P4Enabled) { // Revert any PO files that haven't changed aside from their header { var POFilesToRevert = new List <string>(); var CurrentPOFileHashes = GetPOFileHashes(LocalizationBatches, UEProjectRoot); foreach (var CurrentPOFileHashPair in CurrentPOFileHashes) { byte[] InitialPOFileHash; if (InitalPOFileHashes.TryGetValue(CurrentPOFileHashPair.Key, out InitialPOFileHash) && InitialPOFileHash.SequenceEqual(CurrentPOFileHashPair.Value)) { POFilesToRevert.Add(CurrentPOFileHashPair.Key); } } if (POFilesToRevert.Count > 0) { var P4RevertArgsFilename = CombinePaths(CmdEnv.LocalRoot, "Engine", "Intermediate", String.Format("LocalizationP4RevertArgs-{0}.txt", Guid.NewGuid().ToString())); using (StreamWriter P4RevertArgsWriter = File.CreateText(P4RevertArgsFilename)) { foreach (var POFileToRevert in POFilesToRevert) { P4RevertArgsWriter.WriteLine(POFileToRevert); } } P4.LogP4(String.Format("-x{0} revert", P4RevertArgsFilename)); DeleteFile_NoExceptions(P4RevertArgsFilename); } } // Revert any other unchanged files P4.RevertUnchanged(PendingChangeList); // Submit that single changelist now if (AllowSubmit) { int SubmittedChangeList; P4.Submit(PendingChangeList, out SubmittedChangeList); } } var RunDuration = (DateTime.UtcNow - StartTime).TotalMilliseconds; LogInformation("Localize command finished in {0} seconds", RunDuration / 1000); }
public PluginManager(Plugins p) { plugins = p; InitializeComponent(); }
protected void OnLogReady(IPlugin plugin, Plugins.Primitives.LogEntry entry) { if (LogReady != null) LogReady(plugin, entry); }
private void Call() { Plugins.PlacePhoneCall(this.Celular); }
void pluginMngr_pluginLoaded(Plugins.Plugin plugin) { lbLoadedScripts.Invoke(new MethodInvoker(delegate { lbLoadedScripts.Items.Add(plugin); })); }
private async void SMS() { await Plugins.SendSms("Test prueba", new string[] { this.Celular }); }
public void Refresh() { _objects = new Objects(_jee); if(_objects.Loaded) { _eqLogics = new EqLogics(_jee, this); if (_eqLogics.Loaded) { _commands = new Commands(_jee, this); if (_commands.Loaded) { _plugins = new Plugins(_jee); if (_plugins.Loaded) { _scenarios = new Scenarios(_jee); if (_scenarios.Loaded) { _messages = new Messages(_jee); if (_messages.Loaded) { _loaded = true; } else { _error = _scenarios.Error; _loaded = false; } } else { _error = _messages.Error; _loaded = false; } } else { _error = _plugins.Error; _loaded = false; } } else { _error = _commands.Error; _loaded = false; } } else { _error = _eqLogics.Error; _loaded = false; } } else { _error = _objects.Error; _loaded = false; } }
private void InitValidations(Container container) { Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(SMSServices).Assembly); }
/// <summary> /// Gets the plugins. /// </summary> /// <param name="plugins">The plugins.</param> /// <param name="includeCommunityPlugins">if set to <c>true</c> [community plugins].</param> /// <returns>The view Models.</returns> internal ObservableCollection<SelectableItemViewModel<Plugin>> GetPlugins( Plugins plugins, bool includeCommunityPlugins) { if (plugins == null) { return null; } ObservableCollection<SelectableItemViewModel<Plugin>> viewModels = new ObservableCollection<SelectableItemViewModel<Plugin>>(); foreach (SelectableItemViewModel<Plugin> viewModel in from plugin in plugins.Items where plugin.IsCommunityPlugin == includeCommunityPlugins && plugin.Frameworks.Contains(this.settingsService.FrameworkType) select new SelectableItemViewModel<Plugin>(plugin)) { viewModels.Add(viewModel); } return viewModels; }
public override void Configure(Container container) { IocShared.Configure(this); JsConfig.EmitCamelCaseNames = true; ServiceStack.Auth.RegisterService.AllowUpdates = true; this.PreRequestFilters.Add((req, res) => { req.Items["_DataSetAtPreRequestFilters"] = true; }); this.GlobalRequestFilters.Add((req, res, dto) => { req.Items["_DataSetAtRequestFilters"] = true; if (dto is RequestFilter requestFilter) { res.StatusCode = requestFilter.StatusCode; if (!requestFilter.HeaderName.IsNullOrEmpty()) { res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue); } res.Close(); } if (dto is IRequiresSession secureRequests) { res.ReturnAuthRequired(); } }); Plugins.Add(new SoapFormat()); Plugins.Add(new MiniProfilerFeature()); this.Container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory( "~/App_Data/db.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); this.Container.Register <ICacheClient>(new MemoryCacheClient()); //this.Container.Register<ICacheClient>(new BasicRedisClientManager()); ConfigureAuth(container); //this.Container.Register<ISessionFactory>( // c => new SessionFactory(c.Resolve<ICacheClient>())); var dbFactory = this.Container.Resolve <IDbConnectionFactory>(); using (var db = dbFactory.Open()) db.DropAndCreateTable <Movie>(); ModelConfig <Movie> .Id(x => x.Title); Routes .Add <Movies>("/custom-movies", "GET, OPTIONS") .Add <Movies>("/custom-movies/genres/{Genre}") .Add <Movie>("/custom-movies", "POST,PUT") .Add <Movie>("/custom-movies/{Id}") .Add <MqHostStats>("/mqstats"); var resetMovies = this.Container.Resolve <ResetMoviesService>(); resetMovies.Post(null); container.Register <IRedisClientsManager>(c => new RedisManagerPool()); Plugins.Add(new TemplatePagesFeature()); Plugins.Add(new ValidationFeature()); Plugins.Add(new SessionFeature()); Plugins.Add(new ProtoBufFormat()); Plugins.Add(new RequestLogsFeature { //RequestLogger = new RedisRequestLogger(container.Resolve<IRedisClientsManager>()) RequestLogger = new CsvRequestLogger(), }); Plugins.Add(new SwaggerFeature { //UseBootstrapTheme = true OperationFilter = x => x.Consumes = x.Produces = new[] { MimeTypes.Json, MimeTypes.Xml }.ToList(), RouteSummary = { { "/swaggerexamples", "Swagger Examples Summary" } } }); Plugins.Add(new PostmanFeature()); Plugins.Add(new CorsFeature()); Plugins.Add(new AutoQueryFeature { MaxLimit = 100 }); Plugins.Add(new AdminFeature()); container.RegisterValidators(typeof(CustomersValidator).Assembly); typeof(ResponseStatus) .AddAttributes(new ServiceStack.DataAnnotations.DescriptionAttribute("This is the Response Status!")); typeof(ResponseStatus) .GetProperty("Message") .AddAttributes(new ServiceStack.DataAnnotations.DescriptionAttribute("A human friendly error message")); //var onlyEnableFeatures = Feature.All.Remove(Feature.Jsv | Feature.Soap); SetConfig(new HostConfig { AdminAuthSecret = AuthTestsBase.AuthSecret, ApiVersion = "0.2.0", //EnableFeatures = onlyEnableFeatures, DebugMode = true, //Show StackTraces for easier debugging RedirectPaths = { { "/swagger-ui", "/swagger-ui/" } } }); if (StartMqHost) { var redisManager = new BasicRedisClientManager(); var mqHost = new RedisMqServer(redisManager); mqHost.RegisterHandler <Reverse>(ExecuteMessage); mqHost.Start(); this.Container.Register((IMessageService)mqHost); } }
public ToolEventArgs(Plugins.IMapPlugin imp) { selectedPlugin=imp; }
public virtual void Execute() { try { var plugins = DiscoverPlugins(); Logger.LogInfo($"{plugins.Count} plugin{(plugins.Count == 1 ? "" : "s")} to load"); var sortedPlugins = ModifyLoadOrder(plugins); var invalidPlugins = new HashSet <string>(); var processedPlugins = new Dictionary <string, Version>(); var loadedAssemblies = new Dictionary <string, Assembly>(); foreach (var plugin in sortedPlugins) { var dependsOnInvalidPlugin = false; var missingDependencies = new List <BepInDependency>(); foreach (var dependency in plugin.Dependencies) { bool IsHardDependency(BepInDependency dep) => (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0; // If the dependency wasn't already processed, it's missing altogether bool dependencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion); if (!dependencyExists || pluginVersion < dependency.MinimumVersion) { // If the dependency is hard, collect it into a list to show if (IsHardDependency(dependency)) { missingDependencies.Add(dependency); } continue; } // If the dependency is a hard and is invalid (e.g. has missing dependencies), report that to the user if (invalidPlugins.Contains(dependency.DependencyGUID) && IsHardDependency(dependency)) { dependsOnInvalidPlugin = true; break; } } processedPlugins.Add(plugin.Metadata.GUID, plugin.Metadata.Version); if (dependsOnInvalidPlugin) { string message = $"Skipping [{plugin}] because it has a dependency that was not loaded. See previous errors for details."; DependencyErrors.Add(message); Logger.LogWarning(message); continue; } if (missingDependencies.Count != 0) { bool IsEmptyVersion(Version v) => v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0; string message = $@"Could not load [{plugin}] because it has missing dependencies: { string.Join(", ", missingDependencies.Select(s => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray()) }" ; DependencyErrors.Add(message); Logger.LogError(message); invalidPlugins.Add(plugin.Metadata.GUID); continue; } try { Logger.LogInfo($"Loading [{plugin}]"); if (!loadedAssemblies.TryGetValue(plugin.Location, out var ass)) { loadedAssemblies[plugin.Location] = ass = Assembly.LoadFile(plugin.Location); } Plugins[plugin.Metadata.GUID] = plugin; plugin.Instance = LoadPlugin(plugin, ass); //_plugins.Add((TPlugin)plugin.Instance); } catch (Exception ex) { invalidPlugins.Add(plugin.Metadata.GUID); Plugins.Remove(plugin.Metadata.GUID); Logger.LogError($"Error loading [{plugin}] : {ex.Message}"); if (ex is ReflectionTypeLoadException re) { Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re)); } else { Logger.LogDebug(ex); } } } }
/// <summary> /// Gets the plugins. /// </summary> /// <param name="plugins">The plugins.</param> /// <param name="includeCommunityPlugins">if set to <c>true</c> [community plugins].</param> /// <returns> /// The view Models. /// </returns> internal ObservableCollection<SelectableItemViewModel<Plugin>> GetPlugins( Plugins plugins, bool includeCommunityPlugins) { ObservableCollection<SelectableItemViewModel<Plugin>> viewModels = new ObservableCollection<SelectableItemViewModel<Plugin>>(); foreach (SelectableItemViewModel<Plugin> viewModel in from plugin in plugins.Items where plugin.IsCommunityPlugin == includeCommunityPlugins && plugin.Frameworks.Contains(this.visualStudioService.GetFrameworkType()) select new SelectableItemViewModel<Plugin>(plugin)) { viewModels.Add(viewModel); } return viewModels; }
/// <summary> /// Application specific configuration /// This method should initialize any IoC resources utilized by your web service classes. /// </summary> /// <param name="container"></param> public override void Configure(Container container) { SetConfig(new HostConfig { DebugMode = AppSettings.Get("DebugMode", Env.IsWindows), }); // override config var quartzConfig = ConfigureQuartz(); // register plugin, will scan assemblies by default for jobs var quartzFeature = new QuartzFeature(); Plugins.Add(quartzFeature); Plugins.Add(new PostmanFeature()); // or you can register the plugin with custom config source Plugins.AddIfNotExists(new QuartzFeature { Config = quartzConfig }); // or you can register plugin with custom job assemblies Plugins.AddIfNotExists(new QuartzFeature { ScanAppHostAssemblies = false, JobAssemblies = new[] { typeof(HelloJob).Assembly, typeof(AppHost).Assembly } }); // now you can setup a job to run with a trigger quartzFeature.RegisterJob <HelloJob>( trigger => trigger.WithSimpleSchedule(s => s.WithInterval(TimeSpan.FromMinutes(1)) .RepeatForever() ) .Build() ); // or setup a job to run with a trigger and some data quartzFeature.RegisterJob <HelloJob>( trigger => trigger.WithSimpleSchedule(s => s.WithIntervalInMinutes(1) .WithRepeatCount(10) ) .Build(), builder => builder.UsingJobData("Name", "Bob").Build() ); // you can setup jobs with data and triggers however you like // lets create a trigger with our preferred identity var everyHourTrigger = TriggerBuilder.Create() .WithDescription("This is my trigger!") .WithIdentity("everyHour", "Continuous") .WithCronSchedule("0 0 0/1 1/1 * ? *") .Build(); var jobData = JobBuilder.Create <HelloJob>().UsingJobData("Name", "Sharon").Build(); quartzFeature.RegisterJob <HelloJob>(everyHourTrigger); quartzFeature.RegisterJob <HelloJob>(everyHourTrigger, jobData); }
/// <summary> /// Gets the category nuget packages. /// </summary> /// <param name="plugins">The plugins.</param> /// <param name="category">The category.</param> /// <returns>A collection of plugins.</returns> protected ObservableCollection<SelectableItemViewModel<Plugin>> GetCategoryNugetPackages( Plugins plugins, string category) { if (plugins == null) { return new ObservableCollection<SelectableItemViewModel<Plugin>>(); } var viewModels = new ObservableCollection<SelectableItemViewModel<Plugin>>(); foreach (var viewModel in from plugin in plugins.Items where plugin.Frameworks.Contains(this.settingsService.FrameworkType) && plugin.Category == category select new SelectableItemViewModel<Plugin>(plugin)) { viewModels.Add(viewModel); } return new ObservableCollection<SelectableItemViewModel<Plugin>>(viewModels.OrderBy(x => x.Item.FriendlyName)); }
private static bool RequiresTempTarget(FileReference RawProjectPath, List <UnrealTargetPlatform> ClientTargetPlatforms, bool AssetNativizationRequested) { // check to see if we already have a Target.cs file if (File.Exists(Path.Combine(Path.GetDirectoryName(RawProjectPath.FullName), "Source", RawProjectPath.GetFileNameWithoutExtension() + ".Target.cs"))) { return(false); } else if (Directory.Exists(Path.Combine(Path.GetDirectoryName(RawProjectPath.FullName), "Source"))) { // wasn't one in the main Source directory, let's check all sub-directories //@todo: may want to read each target.cs to see if it has a target corresponding to the project name as a final check FileInfo[] Files = (new DirectoryInfo(Path.Combine(Path.GetDirectoryName(RawProjectPath.FullName), "Source")).GetFiles("*.Target.cs", SearchOption.AllDirectories)); if (Files.Length > 0) { return(false); } } // // once we reach this point, we can surmise that this is an asset- // only (code free) project if (AssetNativizationRequested) { // we're going to be converting some of the project's assets // into native code, so we require a distinct target (executable) // be generated for this project return(true); } // no Target file, now check to see if build settings have changed List <UnrealTargetPlatform> TargetPlatforms = ClientTargetPlatforms; if (ClientTargetPlatforms == null || ClientTargetPlatforms.Count < 1) { // No client target platforms, add all in TargetPlatforms = new List <UnrealTargetPlatform>(); foreach (UnrealTargetPlatform TargetPlatformType in Enum.GetValues(typeof(UnrealTargetPlatform))) { if (TargetPlatformType != UnrealTargetPlatform.Unknown) { TargetPlatforms.Add(TargetPlatformType); } } } // Change the working directory to be the Engine/Source folder. We are running from Engine/Binaries/DotNET string oldCWD = Directory.GetCurrentDirectory(); if (BuildConfiguration.RelativeEnginePath == "../../Engine/") { string EngineSourceDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation()), "..", "..", "..", "Engine", "Source"); if (!Directory.Exists(EngineSourceDirectory)) // only set the directory if it exists, this should only happen if we are launching the editor from an artist sync { EngineSourceDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation()), "..", "..", "..", "Engine", "Binaries"); } Directory.SetCurrentDirectory(EngineSourceDirectory); } // Read the project descriptor, and find all the plugins available to this project ProjectDescriptor Project = ProjectDescriptor.FromFile(RawProjectPath.FullName); DirectoryReference EngineDirectory = new DirectoryReference(BuildConfiguration.RelativeEnginePath); List <PluginInfo> AvailablePlugins = Plugins.ReadAvailablePlugins(EngineDirectory, RawProjectPath, Project.AdditionalPluginDirectories); // check the target platforms for any differences in build settings or additional plugins bool RetVal = false; foreach (UnrealTargetPlatform TargetPlatformType in TargetPlatforms) { UEBuildPlatform BuildPlat = UEBuildPlatform.GetBuildPlatform(TargetPlatformType, true); if (!Automation.IsEngineInstalled() && BuildPlat != null && !(BuildPlat as UEBuildPlatform).HasDefaultBuildConfig(TargetPlatformType, RawProjectPath.Directory)) { RetVal = true; break; } // find if there are any plugins enabled or disabled which differ from the default foreach (PluginInfo Plugin in AvailablePlugins) { bool bPluginEnabledForProject = UProjectInfo.IsPluginEnabledForProject(Plugin, Project, TargetPlatformType, TargetRules.TargetType.Game); if ((bPluginEnabledForProject && !Plugin.Descriptor.bEnabledByDefault) || (bPluginEnabledForProject && Plugin.Descriptor.bInstalled)) { // NOTE: this code was only marking plugins that compiled for the platform to upgrade to code project, however // this doesn't work in practice, because the runtime code will look for the plugin, without a .uplugin file, // and will fail. This is the safest way to make sure all platforms are acting the same. However, if you // whitelist the plugin in the .uproject file, the above UProjectInfo.IsPluginEnabledForProject check won't pass // so you won't get in here. Leaving this commented out code in there, because someone is bound to come looking // for why a non-whitelisted platform module is causing a project to convert to code-based. // As an aside, if you run the project with UE4Game (not your Project's binary) from the debugger, it will work // _in this case_ because the .uplugin file will have been staged, and there is no needed library // if(Plugin.Descriptor.Modules.Any(Module => Module.IsCompiledInConfiguration(TargetPlatformType, TargetRules.TargetType.Game, bBuildDeveloperTools: false, bBuildEditor: false))) { RetVal = true; break; } } } } // Change back to the original directory Directory.SetCurrentDirectory(oldCWD); return(RetVal); }
private void InsertMenuItems(Plugins.MenuItem[] menuItems, NodeContextMenu nodeContextMenu) { ContextMenuStrip contextMenu = nodeContextMenu; int index = contextMenu.Items.IndexOf(nodeContextMenu.mSepPluginEnd); contextMenu.Items.Insert(index++, new ToolStripSeparator()); foreach (Plugins.MenuItem menu in menuItems) { contextMenu.Items.Insert(index++, menu.UnderlyingMenuItem); menu.UnderlyingMenuItem.Click += PluginMenuItem_Click; SetClickHandlerForSubMenu(menu); } }
public ScriptContext RemovePlugins(Predicate <IScriptPlugin> match) { Plugins.RemoveAll(match); return(this); }
public override void Accept(Plugins.IVisitor visitor) { Features = VisitAndReplace(Features, visitor, true); if (_importAction == ImportAction.ImportLess) { InnerRoot = VisitAndReplace(InnerRoot, visitor); } }
public ScriptContext Init() { if (HasInit) { return(this); } HasInit = true; if (InsertScriptMethods.Count > 0) { ScriptMethods.InsertRange(0, InsertScriptMethods); } if (InsertScriptBlocks.Count > 0) { ScriptBlocks.InsertRange(0, InsertScriptBlocks); } if (InsertPlugins.Count > 0) { Plugins.InsertRange(0, InsertPlugins); } foreach (var assembly in ScanAssemblies.Safe()) { foreach (var type in assembly.GetTypes()) { if (typeof(IScriptPlugin).IsAssignableFrom(type)) { if (Plugins.All(x => x.GetType() != type)) { Container.AddSingleton(type); var plugin = (IScriptPlugin)Container.Resolve(type); Plugins.Add(plugin); } } } } Args[ScriptConstants.Debug] = DebugMode; Container.AddSingleton(() => this); Container.AddSingleton(() => Pages); var beforePlugins = Plugins.OfType <IScriptPluginBefore>(); foreach (var plugin in beforePlugins) { plugin.BeforePluginsLoaded(this); } foreach (var plugin in Plugins) { plugin.Register(this); } OnAfterPlugins?.Invoke(this); foreach (var type in ScanTypes) { ScanType(type); } foreach (var assembly in ScanAssemblies.Safe()) { foreach (var type in assembly.GetTypes()) { ScanType(type); } } foreach (var method in ScriptMethods) { InitMethod(method); } foreach (var block in ScriptBlocks) { InitBlock(block); blocksMap[block.Name] = block; } ScriptLanguagesArray = ScriptLanguages.Distinct().ToArray(); foreach (var scriptLanguage in ScriptLanguagesArray) { scriptLanguagesMap[scriptLanguage.Name] = scriptLanguage; if (scriptLanguage is IConfigureScriptContext init) { init.Configure(this); } } ScriptNamespaces = ScriptNamespaces.Distinct().ToList(); var allTypes = new List <Type>(ScriptTypes); foreach (var asm in ScriptAssemblies) { allTypes.AddRange(asm.GetTypes()); } foreach (var type in allTypes) { if (!ScriptTypeNameMap.ContainsKey(type.Name)) { ScriptTypeNameMap[type.Name] = type; } var qualifiedName = ProtectedMethods.typeQualifiedName(type); if (!ScriptTypeQualifiedNameMap.ContainsKey(qualifiedName)) { ScriptTypeQualifiedNameMap[qualifiedName] = type; } } var afterPlugins = Plugins.OfType <IScriptPluginAfter>(); foreach (var plugin in afterPlugins) { plugin.AfterPluginsLoaded(this); } return(this); }
private void InitPlugin(Plugins.IInitInterface plugin) { try { plugin.Init(); } catch (PluginException) { DisablePlugin(plugin); } }
/// <summary> /// Check if an assembly is loaded. /// </summary> /// <param name="path">The path to check from.</param> /// <returns>Returns whether the assembly is loaded or not.</returns> public static bool IsAssemblyLoaded(string path) => Plugins.Any(plugin => plugin.Location() == path);
public override bool ShutDown(Plugins.Interfaces.PluginShutDownReason shutDownReason) { return false; }
private void SaveSettings() { if (EnableWindowsIntegration) { ShellRegister("Directory"); ShellRegister("Drive"); ShellRegister("*"); ShellRegister("here"); } else { ShellUnregister("Directory"); ShellUnregister("Drive"); ShellUnregister("*"); ShellUnregister("here"); } if (EnableStartupAcceleration) { StartupRegister(); } else { StartupUnregister(); } ApplicationFontFamily = EditApplicationFontFamily; MainFormFontSize = EditMainFormFontSize; ReplaceFormFontSize = EditReplaceFormFontSize; DialogFontSize = EditDialogFontSize; Settings.Set(GrepSettings.Key.EnableUpdateChecking, EnableCheckForUpdates); Settings.Set(GrepSettings.Key.UpdateCheckInterval, CheckForUpdatesInterval); Settings.Set(GrepSettings.Key.CustomEditor, CustomEditorPath); Settings.Set(GrepSettings.Key.CustomEditorArgs, CustomEditorArgs); Settings.Set(GrepSettings.Key.CompareApplication, CompareApplicationPath); Settings.Set(GrepSettings.Key.CompareApplicationArgs, CompareApplicationArgs); Settings.Set(GrepSettings.Key.ShowFilePathInResults, ShowFilePathInResults); Settings.Set(GrepSettings.Key.AllowSearchingForFileNamePattern, AllowSearchWithEmptyPattern); Settings.Set(GrepSettings.Key.DetectEncodingForFileNamePattern, DetectEncodingForFileNamePattern); Settings.Set(GrepSettings.Key.ExpandResults, AutoExpandSearchTree); Settings.Set(GrepSettings.Key.ShowVerboseMatchCount, ShowVerboseMatchCount); Settings.Set(GrepSettings.Key.ShowFileInfoTooltips, ShowFileInfoTooltips); Settings.Set(GrepSettings.Key.MatchTimeout, MatchTimeout); Settings.Set(GrepSettings.Key.FuzzyMatchThreshold, MatchThreshold); Settings.Set(GrepSettings.Key.ShowLinesInContext, ShowLinesInContext); Settings.Set(GrepSettings.Key.ContextLinesBefore, ContextLinesBefore); Settings.Set(GrepSettings.Key.ContextLinesAfter, ContextLinesAfter); Settings.Set(GrepSettings.Key.MaxSearchBookmarks, MaxSearchBookmarks); Settings.Set(GrepSettings.Key.MaxPathBookmarks, MaxPathBookmarks); Settings.Set(GrepSettings.Key.MaxExtensionBookmarks, MaxExtensionBookmarks); Settings.Set(GrepSettings.Key.OptionsOnMainPanel, OptionsLocation == PanelSelection.MainPanel); Settings.Set(GrepSettings.Key.FollowWindowsTheme, FollowWindowsTheme); Settings.Set(GrepSettings.Key.CurrentTheme, CurrentTheme); Settings.Set(GrepSettings.Key.UseDefaultFont, UseDefaultFont); Settings.Set(GrepSettings.Key.ApplicationFontFamily, ApplicationFontFamily); Settings.Set(GrepSettings.Key.MainFormFontSize, MainFormFontSize); Settings.Set(GrepSettings.Key.ReplaceFormFontSize, ReplaceFormFontSize); Settings.Set(GrepSettings.Key.DialogFontSize, DialogFontSize); Settings.Set(GrepSettings.Key.PdfToTextOptions, PdfToTextOptions); if (ArchiveOptions.IsChanged) { string nameKey = "Archive"; string addKey = "Add" + nameKey + "Extensions"; string remKey = "Rem" + nameKey + "Extensions"; Settings.Set(addKey, CleanExtensions(ArchiveOptions.AddExtensions)); Settings.Set(remKey, CleanExtensions(ArchiveOptions.RemExtensions)); ArchiveOptions.SetUnchanged(); ArchiveDirectory.Reinitialize(); } bool pluginsChanged = Plugins.Any(p => p.IsChanged); foreach (var plugin in Plugins) { string nameKey = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(plugin.Name); string enabledkey = nameKey + "Enabled"; string addKey = "Add" + nameKey + "Extensions"; string remKey = "Rem" + nameKey + "Extensions"; Settings.Set(enabledkey, plugin.IsEnabled); Settings.Set(addKey, CleanExtensions(plugin.AddExtensions)); Settings.Set(remKey, CleanExtensions(plugin.RemExtensions)); plugin.SetUnchanged(); } Settings.Save(); if (pluginsChanged) { GrepEngineFactory.ReloadPlugins(); } }
protected void RegisterPlugin(IEcsRxPlugin plugin) { Plugins.Add(plugin); }
private void LoadSettings() { CheckIfAdmin(); if (!IsAdministrator) { PanelTooltip = "To change these options run dnGREP as Administrator."; } else { WindowsIntegrationTooltip = "Enables starting dnGrep from the Windows Explorer right-click context menu."; StartupAccelerationTooltip = "Startup acceleration loads application libraries on machine start to improve application startup time."; } EnableWindowsIntegration = IsShellRegistered("Directory"); EnableStartupAcceleration = IsStartupRegistered(); EnableCheckForUpdates = Settings.Get <bool>(GrepSettings.Key.EnableUpdateChecking); CheckForUpdatesInterval = Settings.Get <int>(GrepSettings.Key.UpdateCheckInterval); CustomEditorPath = Settings.Get <string>(GrepSettings.Key.CustomEditor); CustomEditorArgs = Settings.Get <string>(GrepSettings.Key.CustomEditorArgs); CompareApplicationPath = Settings.Get <string>(GrepSettings.Key.CompareApplication); CompareApplicationArgs = Settings.Get <string>(GrepSettings.Key.CompareApplicationArgs); ShowFilePathInResults = Settings.Get <bool>(GrepSettings.Key.ShowFilePathInResults); AllowSearchWithEmptyPattern = Settings.Get <bool>(GrepSettings.Key.AllowSearchingForFileNamePattern); DetectEncodingForFileNamePattern = Settings.Get <bool>(GrepSettings.Key.DetectEncodingForFileNamePattern); AutoExpandSearchTree = Settings.Get <bool>(GrepSettings.Key.ExpandResults); ShowVerboseMatchCount = Settings.Get <bool>(GrepSettings.Key.ShowVerboseMatchCount); ShowFileInfoTooltips = Settings.Get <bool>(GrepSettings.Key.ShowFileInfoTooltips); MatchTimeout = Settings.Get <double>(GrepSettings.Key.MatchTimeout); MatchThreshold = Settings.Get <double>(GrepSettings.Key.FuzzyMatchThreshold); ShowLinesInContext = Settings.Get <bool>(GrepSettings.Key.ShowLinesInContext); ContextLinesBefore = Settings.Get <int>(GrepSettings.Key.ContextLinesBefore); ContextLinesAfter = Settings.Get <int>(GrepSettings.Key.ContextLinesAfter); MaxSearchBookmarks = Settings.Get <int>(GrepSettings.Key.MaxSearchBookmarks); MaxPathBookmarks = Settings.Get <int>(GrepSettings.Key.MaxPathBookmarks); MaxExtensionBookmarks = Settings.Get <int>(GrepSettings.Key.MaxExtensionBookmarks); OptionsLocation = Settings.Get <bool>(GrepSettings.Key.OptionsOnMainPanel) ? PanelSelection.MainPanel : PanelSelection.OptionsExpander; UseDefaultFont = Settings.Get <bool>(GrepSettings.Key.UseDefaultFont); ApplicationFontFamily = EditApplicationFontFamily = ValueOrDefault(GrepSettings.Key.ApplicationFontFamily, SystemFonts.MessageFontFamily.Source); MainFormFontSize = EditMainFormFontSize = ValueOrDefault(GrepSettings.Key.MainFormFontSize, SystemFonts.MessageFontSize); ReplaceFormFontSize = EditReplaceFormFontSize = ValueOrDefault(GrepSettings.Key.ReplaceFormFontSize, SystemFonts.MessageFontSize); DialogFontSize = EditDialogFontSize = ValueOrDefault(GrepSettings.Key.DialogFontSize, SystemFonts.MessageFontSize); // current values may not equal the saved settings value CurrentTheme = AppTheme.Instance.CurrentThemeName; FollowWindowsTheme = AppTheme.Instance.FollowWindowsTheme; PdfToTextOptions = Settings.Get <string>(GrepSettings.Key.PdfToTextOptions); { string nameKey = "Archive"; string addKey = "Add" + nameKey + "Extensions"; string remKey = "Rem" + nameKey + "Extensions"; string addCsv = string.Empty; if (GrepSettings.Instance.ContainsKey(addKey)) { addCsv = GrepSettings.Instance.Get <string>(addKey).Trim(); } string remCsv = string.Empty; if (GrepSettings.Instance.ContainsKey(remKey)) { remCsv = GrepSettings.Instance.Get <string>(remKey).Trim(); } ArchiveOptions = new PluginOptions("Archive", true, string.Join(", ", ArchiveDirectory.DefaultExtensions), addCsv, remCsv); } Plugins.Clear(); foreach (var plugin in GrepEngineFactory.AllPlugins.OrderBy(p => p.Name)) { string nameKey = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(plugin.Name); string enabledkey = nameKey + "Enabled"; string addKey = "Add" + nameKey + "Extensions"; string remKey = "Rem" + nameKey + "Extensions"; bool isEnabled = true; if (GrepSettings.Instance.ContainsKey(enabledkey)) { isEnabled = GrepSettings.Instance.Get <bool>(enabledkey); } string addCsv = string.Empty; if (GrepSettings.Instance.ContainsKey(addKey)) { addCsv = GrepSettings.Instance.Get <string>(addKey).Trim(); } string remCsv = string.Empty; if (GrepSettings.Instance.ContainsKey(remKey)) { remCsv = GrepSettings.Instance.Get <string>(remKey).Trim(); } var pluginOptions = new PluginOptions( plugin.Name, isEnabled, string.Join(", ", plugin.DefaultExtensions), addCsv, remCsv); Plugins.Add(pluginOptions); } }
public override void Accept(Plugins.IVisitor visitor) { Features = VisitAndReplace(Features, visitor); Ruleset = VisitAndReplace(Ruleset, visitor); }
/// <summary> /// Configure the Web Application host. /// </summary> /// <param name="container">The container.</param> public override void Configure(Container container) { var nativeTypes = this.GetPlugin <NativeTypesFeature>(); nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek)); nativeTypes.MetadataTypesConfig.IgnoreTypes.Add(typeof(IgnoreInMetadataConfig)); //nativeTypes.MetadataTypesConfig.GlobalNamespace = "Check.ServiceInterface"; // Change ServiceStack configuration this.SetConfig(new HostConfig { DebugMode = true, //UseHttpsLinks = true, AppendUtf8CharsetOnContentTypes = new HashSet <string> { MimeTypes.Html }, UseCamelCase = true, //AllowJsConfig = false, // Set to return JSON if no request content type is defined // e.g. text/html or application/json //DefaultContentType = MimeTypes.Json, // Disable SOAP endpoints //EnableFeatures = Feature.All.Remove(Feature.Soap) //EnableFeatures = Feature.All.Remove(Feature.Metadata) }); container.Register <IServiceClient>(c => new JsonServiceClient("http://localhost:55799/") { CaptureSynchronizationContext = true, }); //ProxyFetureTests Plugins.Add(new ProxyFeature( matchingRequests: req => req.PathInfo.StartsWith("/proxy/test"), resolveUrl: req => "http://test.servicestack.net".CombineWith(req.RawUrl.Replace("/test", "/")))); Plugins.Add(new ProxyFeature( matchingRequests: req => req.PathInfo.StartsWith("/techstacks"), resolveUrl: req => "http://techstacks.io".CombineWith(req.RawUrl.Replace("/techstacks", "/")))); Plugins.Add(new AutoQueryFeature { MaxLimit = 100 }); Plugins.Add(new AutoQueryDataFeature() .AddDataSource(ctx => ctx.MemorySource(GetRockstars()))); Plugins.Add(new AdminFeature()); Plugins.Add(new PostmanFeature()); Plugins.Add(new CorsFeature()); GlobalRequestFilters.Add((req, res, dto) => { if (dto is AlwaysThrowsGlobalFilter) { throw new Exception(dto.GetType().Name); } }); Plugins.Add(new RequestLogsFeature { RequestLogger = new CsvRequestLogger(), }); Plugins.Add(new DynamicallyRegisteredPlugin()); container.Register <IDbConnectionFactory>( new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)); using (var db = container.Resolve <IDbConnectionFactory>().Open()) { db.DropAndCreateTable <Rockstar>(); db.InsertAll(GetRockstars()); } var dbFactory = (OrmLiteConnectionFactory)container.Resolve <IDbConnectionFactory>(); dbFactory.RegisterConnection("SqlServer", new OrmLiteConnectionFactory( "Server=localhost;Database=test;User Id=test;Password=test;", SqlServerDialect.Provider) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); dbFactory.RegisterConnection("pgsql", new OrmLiteConnectionFactory( "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200", PostgreSqlDialect.Provider)); using (var db = dbFactory.OpenDbConnection("pgsql")) { db.DropAndCreateTable <Rockstar>(); db.DropAndCreateTable <PgRockstar>(); db.Insert(new Rockstar { Id = 1, FirstName = "PostgreSQL", LastName = "Connection", Age = 1 }); db.Insert(new PgRockstar { Id = 1, FirstName = "PostgreSQL", LastName = "Named Connection", Age = 1 }); } //this.GlobalHtmlErrorHttpHandler = new RazorHandler("GlobalErrorHandler.cshtml"); // Configure JSON serialization properties. this.ConfigureSerialization(container); // Configure ServiceStack database connections. this.ConfigureDataConnection(container); // Configure ServiceStack Authentication plugin. this.ConfigureAuth(container); // Configure ServiceStack Fluent Validation plugin. this.ConfigureValidation(container); // Configure ServiceStack Razor views. this.ConfigureView(container); this.StartUpErrors.Add(new ResponseStatus("Mock", "Startup Error")); }
protected virtual void SetupAllPluginSystems() { Plugins.SelectMany(x => x.GetSystemForRegistration(Container)) .ForEachRun(x => SystemExecutor.AddSystem(x)); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { bool bQuitting = false; base.Initialize(); #if DEBUG Log = new Core.Logger.OutputLogger(this); Log.LogLevel = LogLevels.Debug; #else Log = new Core.Logger.NullLogger(); Log.LogLevel = LogLevels.Warning; #endif Log.Debug("BIDSHelper Package Initialize Starting"); string sAddInTypeName = string.Empty; try { StatusBar = new Core.VsIntegration.StatusBar(this); StatusBar.Text = "Loading BIDSHelper (" + this.GetType().Assembly.GetName().Version.ToString() + ")..."; VsShell = (IVsShell)this.GetService(typeof(SVsShell)); DTE2 = this.GetService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE)) as EnvDTE80.DTE2; DebuggerService.AdviseDebuggerEvents(this, out debugEventCookie); if (SwitchVsixManifest()) { bQuitting = true; RestartVisualStudio(); return; } System.Collections.Generic.List <Exception> pluginExceptions = new System.Collections.Generic.List <Exception>(); Type[] types = null; try { types = Assembly.GetExecutingAssembly().GetTypes(); } catch (ReflectionTypeLoadException loadEx) { types = loadEx.Types; //if some types can't be loaded (possibly because SSIS SSDT isn't installed, just SSAS?) then proceed with the types that work pluginExceptions.Add(loadEx); Log.Exception("Problem loading BIDS Helper types list", loadEx); } foreach (Type t in types) { if (//typeof(IBIDSHelperPlugin).IsAssignableFrom(t.GetType()) t != null && t.GetInterfaces().Contains(typeof(IBIDSHelperPlugin)) && (!object.ReferenceEquals(t, typeof(IBIDSHelperPlugin))) && (!t.IsAbstract)) { sAddInTypeName = t.Name; Log.Verbose(string.Format("Loading Plugin: {0}", sAddInTypeName)); BIDSHelperPluginBase feature; Type[] @params = { typeof(BIDSHelperPackage) }; System.Reflection.ConstructorInfo con; con = t.GetConstructor(@params); if (con == null) { System.Windows.Forms.MessageBox.Show("Problem loading type " + t.Name + ". No constructor found."); continue; } try { feature = (BIDSHelperPluginBase)con.Invoke(new object[] { this }); Plugins.Add(feature.FullName, feature); } catch (Exception ex) { pluginExceptions.Add(new Exception("BIDS Helper plugin constructor failed on " + sAddInTypeName + ": " + ex.Message + "\r\n" + ex.StackTrace, ex)); Log.Exception("BIDS Helper plugin constructor failed on " + sAddInTypeName, ex); } } } if (pluginExceptions.Count > 0) { string sException = ""; foreach (Exception pluginEx in pluginExceptions) { sException += string.Format("BIDS Helper encountered an error when Visual Studio started:\r\n{0}\r\n{1}" , pluginEx.Message , pluginEx.StackTrace); Exception innerEx = pluginEx.InnerException; while (innerEx != null) { sException += string.Format("\r\nInner exception:\r\n{0}\r\n{1}" , innerEx.Message , innerEx.StackTrace); innerEx = innerEx.InnerException; } ReflectionTypeLoadException ex = pluginEx as ReflectionTypeLoadException; if (ex == null) { ex = pluginEx.InnerException as ReflectionTypeLoadException; } if (ex != null) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(); sb.AppendLine(exSub.Message); System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException; if (exFileNotFound != null) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } sException += sb.ToString(); } } AddInLoadException = new Exception(sException); } #if DENALI //handle assembly reference problems when the compiled reference doesn't exist in that version of Visual Studio //doesn't appear to be needed for VS2013 AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(currentDomain_AssemblyResolve); #endif } catch (Exception ex) { //don't show a popup anymore since this exception is viewable in the Version dialog in the Tools menu if (string.IsNullOrEmpty(sAddInTypeName)) { AddInLoadException = ex; Log.Exception("Problem loading BIDS Helper", ex); //System.Windows.Forms.MessageBox.Show("Problem loading BIDS Helper: " + ex.Message + "\r\n" + ex.StackTrace); } else { AddInLoadException = new Exception("Problem loading BIDS Helper. Problem type was " + sAddInTypeName + ": " + ex.Message + "\r\n" + ex.StackTrace, ex); Log.Exception("Problem loading BIDS Helper. Problem type was " + sAddInTypeName, ex); //System.Windows.Forms.MessageBox.Show("Problem loading BIDS Helper. Problem type was " + sAddInTypeName + ": " + ex.Message + "\r\n" + ex.StackTrace); } } finally { if (!bQuitting) { StatusBar.Clear(); } } }
private void SetupButton(ref Plugins.IMapPlugin plugin, Plugins.IMapPlugin pluginInstance, ToolPalette.ToolButton tb) { plugin = pluginInstance; Global.pluginManager.addPlugin(plugin); toolPalette.registerButton(tb, plugin); plugin.SetButton(tb); ((Bitmap)tb.Image).MakeTransparent(Color.Magenta); }
private void ConfigureAuth(Container container, string authDbcs) { //Store UserAuth in SQL Server var dbFactory = new OrmLiteConnectionFactory(authDbcs, SqlServerDialect.Provider); container.Register <IDbConnectionFactory>(dbFactory); //If you're using custom RDBMS tables, use the generic constructors to tell OrmLiteAuthRepository which tables to use container.Register <IAuthRepository>(c => new OrmLiteAuthRepository <AuthUser, UserAuthDetails>(dbFactory) { UseDistinctRoleTables = true }); //Create UserAuth RDBMS Tables var authRepo = container.Resolve <IAuthRepository>(); authRepo.InitSchema(); // TODO: don't seed generic users in production // seed with test user if (authRepo.GetUserAuthByUserName("admin") == null) { authRepo.CreateUserAuth(new Auth.AuthUser { UserName = "******", Email = "*****@*****.**", Roles = { ServiceStack.Configuration.RoleNames.Admin }, ShopId = 99999, }, "admin123"); var adminUser = authRepo.GetUserAuthByUserName("admin"); authRepo.AssignRoles(adminUser, new[] { "Admin" }); authRepo.CreateUserAuth(new Auth.AuthUser { UserName = "******", Email = "*****@*****.**", Roles = { "Estimator", "Mixer", "Painter" }, ShopId = 99999, }, "password123"); var testUser = authRepo.GetUserAuthByUserName("TestUser"); authRepo.AssignRoles(testUser, new[] { "User" }); } //Also store User Sessions in SQL Server container.RegisterAs <OrmLiteCacheClient, ICacheClient>(); var cacheClient = container.Resolve <ICacheClient>(); cacheClient.InitSchema(); // purge all cache session records effectively invalidating all previous tokens when this service starts up cacheClient.FlushAll(); //Add Support for Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new JwtAuthProvider(AppSettings) { HashAlgorithm = "HS256", //consider re-using `jwt.AuthKeyBase64` AppSetting the JWT AuthProvider uses AuthKey = GetSecurityKeyBytes(AppSettings.Get <string>("JwtSecurityKey", String.Empty)), // allow override with app.config //ExpireTokensInDays = 1, // FUTURE: make this a more reasonable expiration in production ExpireTokensInDays = 7, // 1 Week Issuer = "SvrAppHost", //setting unnecessary JWT headers bloats the payload unnecessarily //Audience = "http://*:8080", // FUTURE: Should this reflect api listening port? SetBearerTokenOnAuthenticateResponse = true, /* * This should get handled when we move to production * HUGE TODO: get a valid SSL cert * and have this auth piece handled over HTTPS * also having ServiceStack bind/listen on HTTP *AND* HTTPS */ RequireSecureConnection = false, }, //new ApiKeyAuthProvider(AppSettings), //Sign-in with API Key new CredentialsAuthProvider(), //Sign-in with UserName/Password credentials //new BasicAuthProvider(), //Sign-in with HTTP Basic Auth //new DigestAuthProvider(AppSettings), //Sign-in with HTTP Digest Auth //new TwitterAuthProvider(AppSettings), //Sign-in with Twitter //new FacebookAuthProvider(AppSettings), //Sign-in with Facebook //new YahooOpenIdOAuthProvider(AppSettings), //Sign-in with Yahoo OpenId //new OpenIdOAuthProvider(AppSettings), //Sign-in with Custom OpenId //new GoogleOAuth2Provider(AppSettings), //Sign-in with Google OAuth2 Provider //new LinkedInOAuth2Provider(AppSettings), //Sign-in with LinkedIn OAuth2 Provider //new GithubAuthProvider(AppSettings), //Sign-in with GitHub OAuth Provider //new YandexAuthProvider(AppSettings), //Sign-in with Yandex OAuth Provider //new VkAuthProvider(AppSettings), //Sign-in with VK.com OAuth Provider })); //Provide service for new users to register so they can login with supplied credentials. Plugins.Add(new RegistrationFeature { DisableUpdates = true, //requires v4.5.15 on MyGet }); //If you're using your own custom RegistrationFeature you're taking over complete control over the implementation //which no longer uses ServiceStack's built-in implementation }
public ITextComponent SetText(Plugins.Localization.LocalizationKey key, params object[] parameters) { this.lastTextLocalization = true; this.lastTextLocalizationKey = key; this.lastTextLocalizationParameters = parameters; return this.SetText(Plugins.Localization.LocalizationSystem.Get(key, parameters)); }
/// <summary> /// Application specific configuration /// This method should initialize any IoC resources utilized by your web service classes. /// </summary> public override void Configure(Container container) { //Set JSON web services to return idiomatic JSON camelCase properties //ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //use Config.UseCamelCase // overrides to default ServiceStack configuration SetConfig(new HostConfig { UseCamelCase = true, //recommended EnableFeatures = Feature.All, DefaultContentType = "application/json", DebugMode = true, // show stack traces WriteErrorsToResponse = true, AdminAuthSecret = "A0verrid3" // TODO: drop this in Production }); Plugins.Add(new CorsFeature( allowedOrigins: "*", allowedHeaders: "Content-Type, Authorization", allowCredentials: true )); Plugins.Add(new RequestLogsFeature { }); Plugins.Add(new SwaggerFeature { DisableAutoDtoInBodyParam = false, }); // return dates like this: 2012-08-21T11:02:32.0449348-04:00 ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601; // make sure default connection profile exists var custData = System.Configuration.ConfigurationManager.ConnectionStrings["dbCustData"].ConnectionString; var data = System.Configuration.ConfigurationManager.ConnectionStrings["dbData"].ConnectionString; // TODO: setup correct db... We use SQL Server var cp = "Data Source=localhost;Initial Catalog=AuthDb;User ID=sa;Password=123;Connect Timeout=3600"; //Register IOC dependencies //Consider ReuseScope.None, RequestScope is very rarely what you want container.Register <DbContext>(ctx => new DbContext(cp)).ReusedWithin(ReuseScope.None); // Only override default behavior if you need to // handle exceptions in services this.ServiceExceptionHandlers.Add((httpReq, requestDto, ex) => { return(DtoUtils.CreateErrorResponse(requestDto, ex)); }); // handle exceptions not in services this.UncaughtExceptionHandlers.Add((httpReq, httpResp, operationName, ex) => { // TODO: Figure out what changed between ServiceStack -Version 4.0.33 -> 4.0.62 as this throws an error as HttpResponse has already been submitted //httpResp.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message)); httpResp.EndRequest(skipHeaders: true); // FUTURE: perhaps save errors to db }); this.GlobalRequestFilters.Add((req, res, dto) => { Stopwatch sw = new Stopwatch(); sw.Start(); req.Items.Add("StopWatch", sw); }); this.GlobalResponseFilters.Add((req, res, dto) => { if (req.Items.ContainsKey("StopWatch")) { var sw = req.Items["StopWatch"] as Stopwatch; sw.Stop(); } ; }); /* TODO: determine which db to house auth info in * for now, dump into CustData* (NA as default) */ ConfigureAuth(container, cp); }
public void registerButton(ToolButton tb, Plugins.IMapPlugin mapPlugin) { tb.guid = mapPlugin.guid; tools[mapPlugin.guid] = mapPlugin; tb.CheckedChanged += new EventHandler(toolchanged); }
public IPlugin GetPlugin(string pluginId) { return(Plugins.FirstOrDefault(x => x.PluginId == pluginId)); }
public override void Accept(Plugins.IVisitor visitor) { Rules = VisitAndReplace(Rules, visitor); }
public override void ExecuteBuild() { var UEProjectRoot = ParseParamValue("UEProjectRoot"); if (UEProjectRoot == null) { UEProjectRoot = CmdEnv.LocalRoot; } var UEProjectDirectory = ParseParamValue("UEProjectDirectory"); if (UEProjectDirectory == null) { throw new AutomationException("Missing required command line argument: 'UEProjectDirectory'"); } var UEProjectName = ParseParamValue("UEProjectName"); if (UEProjectName == null) { UEProjectName = ""; } var LocalizationProjectNames = new List <string>(); { var LocalizationProjectNamesStr = ParseParamValue("LocalizationProjectNames"); if (LocalizationProjectNamesStr != null) { foreach (var ProjectName in LocalizationProjectNamesStr.Split(',')) { LocalizationProjectNames.Add(ProjectName.Trim()); } } } var LocalizationProviderName = ParseParamValue("LocalizationProvider"); if (LocalizationProviderName == null) { LocalizationProviderName = "OneSky"; } var LocalizationSteps = new List <string>(); { var LocalizationStepsStr = ParseParamValue("LocalizationSteps"); if (LocalizationStepsStr == null) { LocalizationSteps.AddRange(new string[] { "Download", "Gather", "Import", "Export", "Compile", "GenerateReports", "Upload" }); } else { foreach (var StepName in LocalizationStepsStr.Split(',')) { LocalizationSteps.Add(StepName.Trim()); } } LocalizationSteps.Add("Monolithic"); // Always allow the monolithic scripts to run as we don't know which steps they do } var ShouldGatherPlugins = ParseParam("IncludePlugins"); var IncludePlugins = new List <string>(); var ExcludePlugins = new List <string>(); if (ShouldGatherPlugins) { var IncludePluginsStr = ParseParamValue("IncludePlugins"); if (IncludePluginsStr != null) { foreach (var PluginName in IncludePluginsStr.Split(',')) { IncludePlugins.Add(PluginName.Trim()); } } var ExcludePluginsStr = ParseParamValue("ExcludePlugins"); if (ExcludePluginsStr != null) { foreach (var PluginName in ExcludePluginsStr.Split(',')) { ExcludePlugins.Add(PluginName.Trim()); } } } var AdditionalCommandletArguments = ParseParamValue("AdditionalCommandletArguments"); if (AdditionalCommandletArguments == null) { AdditionalCommandletArguments = ""; } var LocalizationBatches = new List <LocalizationBatch>(); // Add the static set of localization projects as a batch if (LocalizationProjectNames.Count > 0) { LocalizationBatches.Add(new LocalizationBatch(UEProjectDirectory, UEProjectDirectory, "", LocalizationProjectNames)); } // Build up any additional batches needed for plugins if (ShouldGatherPlugins) { var PluginsRootDirectory = CombinePaths(UEProjectRoot, UEProjectDirectory, "Plugins"); IReadOnlyList <PluginInfo> AllPlugins = Plugins.ReadPluginsFromDirectory(new DirectoryReference(PluginsRootDirectory), UEProjectName.Length == 0 ? PluginType.Engine : PluginType.Project); // Add a batch for each plugin that meets our criteria foreach (var PluginInfo in AllPlugins) { bool ShouldIncludePlugin = (IncludePlugins.Count == 0 || IncludePlugins.Contains(PluginInfo.Name)) && !ExcludePlugins.Contains(PluginInfo.Name); if (ShouldIncludePlugin && PluginInfo.Descriptor.LocalizationTargets != null && PluginInfo.Descriptor.LocalizationTargets.Length > 0) { var RootRelativePluginPath = PluginInfo.Directory.MakeRelativeTo(new DirectoryReference(UEProjectRoot)); RootRelativePluginPath = RootRelativePluginPath.Replace('\\', '/'); // Make sure we use / as these paths are used with P4 var PluginTargetNames = new List <string>(); foreach (var LocalizationTarget in PluginInfo.Descriptor.LocalizationTargets) { PluginTargetNames.Add(LocalizationTarget.Name); } LocalizationBatches.Add(new LocalizationBatch(UEProjectDirectory, RootRelativePluginPath, PluginInfo.Name, PluginTargetNames)); } } } // Create a single changelist to use for all changes, and hash the current PO files on disk so we can work out whether they actually change int PendingChangeList = 0; Dictionary <string, byte[]> InitalPOFileHashes = null; if (P4Enabled) { PendingChangeList = P4.CreateChange(P4Env.Client, "Localization Automation"); InitalPOFileHashes = GetPOFileHashes(LocalizationBatches, UEProjectRoot); } // Process each localization batch foreach (var LocalizationBatch in LocalizationBatches) { ProcessLocalizationProjects(LocalizationBatch, PendingChangeList, UEProjectRoot, UEProjectName, LocalizationProviderName, LocalizationSteps, AdditionalCommandletArguments); } // Submit that single changelist now if (P4Enabled && AllowSubmit) { // Revert any PO files that haven't changed aside from their header { var POFilesToRevert = new List <string>(); var CurrentPOFileHashes = GetPOFileHashes(LocalizationBatches, UEProjectRoot); foreach (var CurrentPOFileHashPair in CurrentPOFileHashes) { byte[] InitialPOFileHash; if (InitalPOFileHashes.TryGetValue(CurrentPOFileHashPair.Key, out InitialPOFileHash) && InitialPOFileHash.SequenceEqual(CurrentPOFileHashPair.Value)) { POFilesToRevert.Add(CurrentPOFileHashPair.Key); } } if (POFilesToRevert.Count > 0) { var P4RevertArgsFilename = CombinePaths(CmdEnv.LocalRoot, "Engine", "Intermediate", String.Format("LocalizationP4RevertArgs-{0}.txt", Guid.NewGuid().ToString())); using (StreamWriter P4RevertArgsWriter = File.CreateText(P4RevertArgsFilename)) { foreach (var POFileToRevert in POFilesToRevert) { P4RevertArgsWriter.WriteLine(POFileToRevert); } } P4.LogP4(String.Format("-x{0} revert", P4RevertArgsFilename)); DeleteFile_NoExceptions(P4RevertArgsFilename); } } // Revert any other unchanged files P4.RevertUnchanged(PendingChangeList); int SubmittedChangeList; P4.Submit(PendingChangeList, out SubmittedChangeList); } }
public override void Configure(Container container) { Plugins.RemoveAll(x => x is NativeTypesFeature); GetPlugin <MetadataFeature>().EnableNav = false; }
public void UnloadAllPlugins() { DeactivateAllPlugins(); Plugins.Clear(); }