示例#1
0
        private void loadPlugin(string name, string pluginSpec, ref string[] cmdArgs)
        {
            Debug.Assert(_communicator != null);

            //
            // Split the entire property value into arguments. An entry point containing spaces
            // must be enclosed in quotes.
            //
            string[] args = null;
            try
            {
                args = IceUtilInternal.Options.split(pluginSpec);
            }
            catch (IceUtilInternal.Options.BadQuote ex)
            {
                PluginInitializationException e = new PluginInitializationException();
                e.reason = "invalid arguments for plug-in `" + name + "':\n" + ex.Message;
                throw e;
            }

            Debug.Assert(args.Length > 0);

            string entryPoint = args[0];

            //
            // Shift the arguments.
            //
            string[] tmp = new string[args.Length - 1];
            Array.Copy(args, 1, tmp, 0, args.Length - 1);
            args = tmp;

            //
            // Convert command-line options into properties. First
            // we convert the options from the plug-in
            // configuration, then we convert the options from the
            // application command-line.
            //
            Properties properties = _communicator.getProperties();

            args    = properties.parseCommandLineOptions(name, args);
            cmdArgs = properties.parseCommandLineOptions(name, cmdArgs);

            //
            // Extract the assembly name and the class name.
            //
            string err    = "unable to load plug-in `" + entryPoint + "': ";
            int    sepPos = entryPoint.IndexOf(':');

            if (sepPos != -1)
            {
                const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                if (entryPoint.Length > 3 &&
                    sepPos == 1 &&
                    driveLetters.IndexOf(entryPoint[0]) != -1 &&
                    (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if (sepPos == -1)
            {
                PluginInitializationException e = new PluginInitializationException();
                e.reason = err + "invalid entry point format";
                throw e;
            }

            System.Reflection.Assembly pluginAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            string className    = entryPoint.Substring(sepPos + 1);

            try
            {
                //
                // First try to load the assembly using Assembly.Load, which will succeed
                // if a fully-qualified name is provided or if a partial name has been qualified
                // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                // if a file name is configured or a partial name is configured and DEVPATH is used.
                //
                try
                {
                    pluginAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch (System.IO.IOException ex)
                {
                    try
                    {
                        pluginAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch (System.IO.IOException)
                    {
                        throw ex;
                    }
                }
            }
            catch (System.Exception ex)
            {
                PluginInitializationException e = new PluginInitializationException();
                e.reason = err + "unable to load assembly: `" + assemblyName + "': " + ex.ToString();
                throw e;
            }

            //
            // Instantiate the class.
            //
            PluginFactory pluginFactory = null;

            System.Type c = null;
            try
            {
                c = pluginAssembly.GetType(className, true);
            }
            catch (System.Exception ex)
            {
                PluginInitializationException e = new PluginInitializationException(ex);
                e.reason = err + "GetType failed for `" + className + "'";
                throw e;
            }

            try
            {
                pluginFactory = (PluginFactory)IceInternal.AssemblyUtil.createInstance(c);
                if (pluginFactory == null)
                {
                    PluginInitializationException e = new PluginInitializationException();
                    e.reason = err + "can't find constructor for `" + className + "'";
                    throw e;
                }
            }
            catch (System.InvalidCastException ex)
            {
                PluginInitializationException e = new PluginInitializationException(ex);
                e.reason = err + "InvalidCastException to Ice.PluginFactory";
                throw e;
            }
            catch (System.UnauthorizedAccessException ex)
            {
                PluginInitializationException e = new PluginInitializationException(ex);
                e.reason = err + "UnauthorizedAccessException: " + ex.ToString();
                throw e;
            }
            catch (System.Exception ex)
            {
                PluginInitializationException e = new PluginInitializationException(ex);
                e.reason = err + "System.Exception: " + ex.ToString();
                throw e;
            }

            Plugin plugin = null;

            try
            {
                plugin = pluginFactory.create(_communicator, name, args);
            }
            catch (PluginInitializationException ex)
            {
                ex.reason = err + ex.reason;
                throw;
            }
            catch (System.Exception ex)
            {
                PluginInitializationException e = new PluginInitializationException(ex);
                e.reason = err + "System.Exception in factory.create: " + ex.ToString();
                throw e;
            }

            if (plugin == null)
            {
                PluginInitializationException ex = new PluginInitializationException();
                ex.reason = err + "factory.create returned null plug-in";
                throw ex;
            }

            PluginInfo info = new PluginInfo();

            info.name   = name;
            info.plugin = plugin;
            _plugins.Add(info);
        }
示例#2
0
        public static void InitializeConstraints(IConstraintFactory constraintFactory, PluginFactory pluginFactory, DbContext entityContext)
        {
            var constraintTypes = entityContext.Set <ConstraintDefinition>();
            Dictionary <string, object> emptyDict = new Dictionary <string, object>
            {
                { "Ask", Ask.Value },
                { "AskType", typeof(Ask) }
            };

            foreach (var constraintType in constraintTypes)
            {
                Type targetType           = (Type)ExpressionParser.Parse(constraintType.ConstraintType, emptyDict, a => { DefaultCallbacks.PrepareDefaultCallbacks(a.Scope, a.ReplSession); });
                ConstraintConstructor cst = new ConstraintConstructor(targetType,
                                                                      constraintType.ConstraintIdentifier);
                constraintType.Parameters.OrderBy(n => n.ParameterOrder)
                .ForEach(
                    n =>
                    cst.Parameters.Add(
                        new ConstructorParameter(ExpressionParser.Parse(n.ParameterValue, emptyDict, a => { DefaultCallbacks.PrepareDefaultCallbacks(a.Scope, a.ReplSession); }),
                                                 (Type)ExpressionParser.Parse(n.ParameterType, emptyDict, a => { DefaultCallbacks.PrepareDefaultCallbacks(a.Scope, a.ReplSession); }))));
                constraintFactory.RegisterType(cst);
            }

            var dc = new DeciderContext {
                PluginFactory = pluginFactory, ConstraintFactory = constraintFactory, DbContext = entityContext
            };

            factory2Decisions.TryAdd(constraintFactory, dc);
            context2Decisions.TryAdd(entityContext, dc);
            constraintFactory.Disposed += UnRegisterFactory;
        }
 void IHandler.HandleItem(object item)
 {
     HandleItem(PluginFactory.GetInstance().GetAssemblyDefinition(item));
 }
 /// <summary>
 /// Assembly unloaded
 /// </summary>
 /// <param name="sender">Event sender</param>
 /// <param name="e">Event parameters</param>
 protected virtual void AssemblyUnloaded(object sender, EventArgs e)
 {
     PluginFactory.GetInstance().ReloadAssemblies(Assemblies);
     PluginFactory.GetInstance().SynchronizeAssemblyContexts(Assemblies);
 }
示例#5
0
 private void SyncWarningForm_Load(object sender, System.EventArgs e)
 {
     LabWarning.Text = string.Format(LabWarning.Text, PluginFactory.GetInstance().HostApplication);
 }
示例#6
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="configuration">Configuration</param>
 /// <param name="baseFolder">Base folder</param>
 /// <param name="pluginFolder">Plugin folder</param>
 /// <param name="firstDayOfWeek">First day of week</param>
 public Engine(IConfiguration configuration, ILogger logger)
 {
     _pluginFactory = new PluginFactory(logger);
     _configuration = configuration;
     _logger        = logger;
 }
        public static async Task <int> Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            var parsedArgs = await Args.ParseAsync <CredentialProviderArgs>(args);

            var multiLogger = new MultiLogger();
            var fileLogger  = GetFileLogger();

            if (fileLogger != null)
            {
                multiLogger.Add(fileLogger);
            }

            // Cancellation listener
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
            {
                // ConsoleCancelEventArgs.Cancel defaults to false which terminates the current process.
                multiLogger.Verbose(Resources.CancelMessage);
                tokenSource.Cancel();
            };

            var authUtil                    = new AuthUtil(multiLogger);
            var adalTokenCache              = AdalTokenCacheUtils.GetAdalTokenCache(multiLogger);
            var adalTokenProviderFactory    = new VstsAdalTokenProviderFactory(adalTokenCache);
            var bearerTokenProvidersFactory = new BearerTokenProvidersFactory(multiLogger, adalTokenProviderFactory);
            var vstsSessionTokenProvider    = new VstsSessionTokenFromBearerTokenProvider(authUtil, multiLogger);

            List <ICredentialProvider> credentialProviders = new List <ICredentialProvider>
            {
                new VstsBuildTaskServiceEndpointCredentialProvider(multiLogger),
                new VstsBuildTaskCredentialProvider(multiLogger),
                new VstsCredentialProvider(multiLogger, authUtil, bearerTokenProvidersFactory, vstsSessionTokenProvider),
            };

            try
            {
                IRequestHandlers requestHandlers = new RequestHandlerCollection
                {
                    { MessageMethod.GetAuthenticationCredentials, new GetAuthenticationCredentialsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.GetOperationClaims, new GetOperationClaimsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.Initialize, new InitializeRequestHandler(multiLogger) },
                    { MessageMethod.SetLogLevel, new SetLogLevelRequestHandler(multiLogger) },
                    { MessageMethod.SetCredentials, new SetCredentialsRequestHandler(multiLogger) },
                };

                // Help
                if (parsedArgs.Help)
                {
                    Console.WriteLine(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));
                    Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                    Console.WriteLine(
                        string.Format(
                            Resources.EnvironmentVariableHelp,
                            EnvUtil.LogPathEnvVar,
                            EnvUtil.SessionTokenCacheEnvVar,
                            EnvUtil.AuthorityEnvVar,
                            EnvUtil.AdalFileCacheEnvVar,
                            EnvUtil.PpeHostsEnvVar,
                            EnvUtil.SupportedHostsEnvVar,
                            EnvUtil.SessionTimeEnvVar,
                            EnvUtil.TokenTypeEnvVar,
                            EnvUtil.BuildTaskUriPrefixes,
                            EnvUtil.BuildTaskAccessToken,
                            EnvUtil.BuildTaskExternalEndpoints,
                            EnvUtil.AdalTokenCacheLocation,
                            EnvUtil.SessionTokenCacheLocation,
                            EnvUtil.WindowsIntegratedAuthenticationEnvVar,
                            EnvUtil.DeviceFlowTimeoutEnvVar
                            ));
                    return(0);
                }

                // Plug-in mode
                if (parsedArgs.Plugin)
                {
                    using (IPlugin plugin = await PluginFactory.CreateFromCurrentProcessAsync(requestHandlers, ConnectionOptions.CreateDefault(), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false))
                    {
                        multiLogger.Add(new PluginConnectionLogger(plugin.Connection));
                        multiLogger.Verbose(Resources.RunningInPlugin);
                        multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                        await RunNuGetPluginsAsync(plugin, multiLogger, TimeSpan.FromMinutes(2), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
                    }

                    return(0);
                }

                // Stand-alone mode
                if (requestHandlers.TryGet(MessageMethod.GetAuthenticationCredentials, out IRequestHandler requestHandler) && requestHandler is GetAuthenticationCredentialsRequestHandler getAuthenticationCredentialsRequestHandler)
                {
                    // Don't use ConsoleLogger in JSON output mode, since emitting other messages as well as the loglevel prefix would corrupt the pure JSON output
                    if (parsedArgs.OutputFormat == OutputFormat.HumanReadable)
                    {
                        multiLogger.Add(new ConsoleLogger());
                    }

                    multiLogger.SetLogLevel(parsedArgs.Verbosity);
                    multiLogger.Verbose(Resources.RunningInStandAlone);
                    multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                    if (parsedArgs.Uri == null)
                    {
                        Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                        return(1);
                    }

                    GetAuthenticationCredentialsRequest  request  = new GetAuthenticationCredentialsRequest(parsedArgs.Uri, isRetry: parsedArgs.IsRetry, isNonInteractive: parsedArgs.NonInteractive, parsedArgs.CanShowDialog);
                    GetAuthenticationCredentialsResponse response = await getAuthenticationCredentialsRequestHandler.HandleRequestAsync(request).ConfigureAwait(continueOnCapturedContext: false);

                    string resultUsername = response?.Username;
                    string resultPassword = parsedArgs.RedactPassword ? Resources.Redacted : response?.Password;
                    if (parsedArgs.OutputFormat == OutputFormat.Json)
                    {
                        // Manually write the JSON output, since we don't use ConsoleLogger in JSON mode (see above)
                        Console.WriteLine(JsonConvert.SerializeObject(new CredentialResult(resultUsername, resultPassword)));
                    }
                    else
                    {
                        multiLogger.Info($"{Resources.Username}: {resultUsername}");
                        multiLogger.Info($"{Resources.Password}: {resultPassword}");
                    }
                    return(0);
                }

                return(-1);
            }
            finally
            {
                foreach (ICredentialProvider credentialProvider in credentialProviders)
                {
                    credentialProvider.Dispose();
                }
            }
        }
 bool IHandler.IsItemHandled(object item)
 {
     return(PluginFactory.GetInstance().IsAssemblyNameReferenceHandled(item));
 }
 void IHandler.HandleItem(object item)
 {
     HandleItem(PluginFactory.GetInstance().GetAssemblyNameReference(item));
 }
示例#10
0
        public async override Task <bool> Stop()
        {
            await PluginFactory.Stop(this);

            return(await base.Stop());
        }
        public ServiceHubProvider(ITVComponents.InterProcessCommunication.MessagingShared.Hub.IServiceHubProvider parent, string hubAddresses, PluginFactory factory)
        {
            if (instance != null)
            {
                throw new NotSupportedException("Can have only one active Instance of ServiceHubProvider at a time");
            }

            instance                      = this;
            this.hubAddresses             = hubAddresses;
            this.factory                  = factory;
            appConfigProviders            = new List <IAppConfigureProvider>();
            serviceConfigProviders        = new List <IServicesConfigureProvider>();
            webHostBuilderConfigProviders = new List <IWebHostBuilderConfigureProvider>();
            endPointInitializers          = new List <IEndPointInitializer>();
            listenOptionsConfigurators    = new List <IEndPointDefaultsConfigurator>();
            Broker     = parent.Broker;
            ownsBroker = false;
        }
示例#12
0
        public static async Task <int> Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            var parsedArgs = await Args.ParseAsync <CredentialProviderArgs>(args);

            var multiLogger = new MultiLogger();

            var fileLogger = GetFileLogger();

            if (fileLogger != null)
            {
                multiLogger.Add(fileLogger);
            }

            // Cancellation listener
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
            {
                // ConsoleCancelEventArgs.Cancel defaults to false which terminates the current process.
                tokenSource.Cancel();
            };

            List <ICredentialProvider> credentialProviders = new List <ICredentialProvider>
            {
                new VstsBuildTaskServiceEndpointCredentialProvider(multiLogger),
                new VstsBuildTaskCredentialProvider(multiLogger),
                new VstsCredentialProvider(multiLogger),
            };

            try
            {
                IRequestHandlers requestHandlers = new RequestHandlerCollection
                {
                    { MessageMethod.GetAuthenticationCredentials, new GetAuthenticationCredentialsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.GetOperationClaims, new GetOperationClaimsRequestHandler(multiLogger, credentialProviders) },
                    { MessageMethod.Initialize, new InitializeRequestHandler(multiLogger) },
                    { MessageMethod.SetLogLevel, new SetLogLevelRequestHandler(multiLogger) },
                    { MessageMethod.SetCredentials, new SetCredentialsRequestHandler(multiLogger) },
                };

                multiLogger.Verbose(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));

                // Help
                if (parsedArgs.Help)
                {
                    Console.WriteLine(string.Format(Resources.CommandLineArgs, Program.Version, Environment.CommandLine));
                    Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                    Console.WriteLine(
                        string.Format(
                            Resources.EnvironmentVariableHelp,
                            EnvUtil.LogPathEnvVar,
                            EnvUtil.SessionTokenCacheEnvVar,
                            EnvUtil.AuthorityEnvVar,
                            EnvUtil.AdalFileCacheEnvVar,
                            EnvUtil.PpeHostsEnvVar,
                            EnvUtil.SupportedHostsEnvVar,
                            EnvUtil.SessionTimeEnvVar,
                            EnvUtil.BuildTaskUriPrefixes,
                            EnvUtil.BuildTaskAccessToken,
                            EnvUtil.BuildTaskExternalEndpoints,
                            EnvUtil.AdalTokenCacheLocation,
                            EnvUtil.SessionTokenCacheLocation
                            ));
                    return(0);
                }

                // Plug-in mode
                if (parsedArgs.Plugin)
                {
                    multiLogger.Verbose(Resources.RunningInPlugin);

                    using (IPlugin plugin = await PluginFactory.CreateFromCurrentProcessAsync(requestHandlers, ConnectionOptions.CreateDefault(), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false))
                    {
                        multiLogger.Add(new PluginConnectionLogger(plugin.Connection));
                        await RunNuGetPluginsAsync(plugin, multiLogger, TimeSpan.FromMinutes(2), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
                    }

                    return(0);
                }

                // Stand-alone mode
                if (requestHandlers.TryGet(MessageMethod.GetAuthenticationCredentials, out IRequestHandler requestHandler) && requestHandler is GetAuthenticationCredentialsRequestHandler getAuthenticationCredentialsRequestHandler)
                {
                    multiLogger.Add(new ConsoleLogger());
                    multiLogger.SetLogLevel(parsedArgs.Verbosity);
                    multiLogger.Verbose(Resources.RunningInStandAlone);

                    if (parsedArgs.Uri == null)
                    {
                        Console.WriteLine(ArgUsage.GenerateUsageFromTemplate <CredentialProviderArgs>());
                        return(1);
                    }

                    GetAuthenticationCredentialsRequest  request  = new GetAuthenticationCredentialsRequest(parsedArgs.Uri, isRetry: parsedArgs.IsRetry, isNonInteractive: parsedArgs.NonInteractive, parsedArgs.CanShowDialog);
                    GetAuthenticationCredentialsResponse response = await getAuthenticationCredentialsRequestHandler.HandleRequestAsync(request).ConfigureAwait(continueOnCapturedContext: false);

                    multiLogger.Info($"{Resources.Username}: {response?.Username}");
                    multiLogger.Info($"{Resources.Password}: {(parsedArgs.RedactPassword ? Resources.Redacted : response?.Password)}");
                    return(0);
                }

                return(-1);
            }
            finally
            {
                foreach (ICredentialProvider credentialProvider in credentialProviders)
                {
                    credentialProvider.Dispose();
                }
            }
        }
示例#13
0
        private List <ApplicationDataModel> ImportData(string importPluginName, string importDataPath)
        {
            if (PluginFactory.AvailablePlugins.Count == 0)
            {
                Console.WriteLine("PluginFactory: no plugins available");
                return(null);
            }

            // Get ImportPlugin
            // ToDo: [Check] version of plugin
            // ToDo: Read importDataPath with all available plugins
            var importPlugin = PluginFactory.GetPlugin(importPluginName);

            if (importPlugin == null)
            {
                Console.WriteLine($"Could not find ImportPlugin {importPluginName}");
                return(null);
            }
            // Initialise Plugin
            if (ImportSettings != null)
            {
                if (!string.IsNullOrEmpty(ImportSettings.InitialiseString))
                {
                    importPlugin.Initialize(ImportSettings.InitialiseString);
                }
            }

            // [Check] if data path is correct
            if (!Directory.Exists(importDataPath))
            {
                Console.WriteLine($"Incorrect importDataPath {importDataPath}");
                return(null);
            }

            List <ApplicationDataModel> adms = new List <ApplicationDataModel>();

            // To Do (check if possible/needed): Task.Run(() => {});
            Console.WriteLine("Starting ADAPT import");
            DateTime startTime = DateTime.Now;

            // Check if Plugin supports the data
            if (importPlugin.IsDataCardSupported(importDataPath))
            {
                if (ImportSettings != null)
                {
                    if (ImportSettings.GetProperties() != null)
                    {
                        adms.AddRange(importPlugin.Import(importDataPath, ImportSettings.GetProperties()));
                    }
                }
                else
                {
                    adms.AddRange(importPlugin.Import(importDataPath));
                }
                TimeSpan conversionTime = DateTime.Now.Subtract(startTime);
                Console.WriteLine($"Completed ADAPT import in {conversionTime}, imported {adms.Count} ApplicationDataModels");
                return(adms);
            }
            else
            {
                Console.WriteLine($"ImportPlugin cannot read the data, not imported!");
                return(null);
            }
        }
        public MainWindow(MinecraftServer minecraft, WonderlandClient wonderlandClient, IOptions <Settings> settings, RelayEventHandler relayEventHandler, PluginFactory pluginLoader, MinecraftState minecraftState)
        {
            InitializeComponent();
            DataContext = new
            {
                Minecraft = _minecraftConsole,
                Discord   = _discordConsole,
                Plugin    = _pluginConsole,
                Settings  = _settings
            };

            _settings = settings.Value;

            Loaded += MainWindow_Loaded;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            _minecraft         = minecraft;
            _wonderlandClient  = wonderlandClient;
            _relayEventHandler = relayEventHandler;
            _pluginLoader      = pluginLoader;
            _minecraftState    = minecraftState;
        }
示例#15
0
 public bool IsItemHandled(object item)
 {
     return(PluginFactory.GetInstance().IsLinkedResourceHandled(item));
 }
示例#16
0
 public MonoDevelopPluginFactory(TimeSpan idleTimeout)
 {
     pluginFactory = new PluginFactory(idleTimeout);
 }
示例#17
0
 public void HandleItem(object item)
 {
     HandleItem(PluginFactory.GetInstance().GetLinkedResource(item));
 }
示例#18
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var pluginManager = SimpleIoc.Default.GetInstance <ViewModel.PluginManagerViewModel>();

                // Create plugin directory
                if (!Directory.Exists(pluginManager.PluginPath))
                {
                    Directory.CreateDirectory(pluginManager.PluginPath);
                }

                //  Move standard panels dll to plugin directory
                string standardPanelsTargetPath = Path.Combine(pluginManager.PluginPath, "StandardPanels.dll");
                if (!File.Exists(standardPanelsTargetPath))
                {
                    string standardPanelsSourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "StandardPanels.dll");
                    File.Copy(standardPanelsSourcePath, standardPanelsTargetPath, true);
                }

                // Load plugins from plugin directory
                List <Exception> errors = PluginFactory.LoadPlugins(pluginManager.PluginPath);

                foreach (var ex in errors)
                {
                    await MainViewModel.DialogService.ShowError(ex.InnerException, ex.Message, "Continue", null);
                }
            }
            catch (Exception ex)
            {
                await MainViewModel.DialogService.ShowError(ex.Message, "Could not load plugins", "Continue", null);

                AppTelemetry.ReportError("Loading", ex);
            }

            // Add local factories which will not be found because they are not in dll's.
            PluginFactory.PanelFactories.Add(PluginFactory.CreatePanelFactory(typeof(Factory.MarkerPanelFactory)));
            PluginFactory.PanelFactories.Add(PluginFactory.CreatePanelFactory(typeof(Factory.ProjectPanelFactory)));

            MainViewModel.PropertyChanged += Main_PropertyChanged;

            foreach (var item in PluginFactory.PanelFactories)
            {
                // Add if it has no attribute set or if the attribute is set check the visible flag
                PanelPluginAttribute attr = item.GetType().GetCustomAttribute <PanelPluginAttribute>(false);
                if (attr == null || attr.Visible)
                {
                    MainViewModel.Windows.Add(item);
                }
            }

            MainViewModel.NewProjectCommand.Execute(null);

            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments != null && AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null && AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0)
            {
                string filename = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0].ToString();
                try
                {
                    MainViewModel.Project.AddLogFile(filename);
                }
                catch (FileLoadException)
                {
                    MessageBox.Show("There is no available log file reader that can read that file.");
                    return;
                }
            }

            // If this is first run show news
            try
            {
                bool firstrun = Properties.Settings.Default.FirstRun;
                if (firstrun)
                {
                    MainViewModel.ShowWebPageCommand.Execute(@"https://wolkesson.github.io/SampleCrunch/getting-started");
                    Properties.Settings.Default.AppTelemetry = (MessageBox.Show(
                                                                    "Sample Crunch uses volentary telemetry to track usage and find bugs. Do you approve to send annonumous data?",
                                                                    "Allow telemetry?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes);
                    Properties.Settings.Default.FirstRun = false;
                    Properties.Settings.Default.Save();
                }
            }
            catch (System.Deployment.Application.InvalidDeploymentException)
            {
                // We will end up here if application is not installed, but run locally.
            }

            try
            {
                // Block App telemetry if user has disapproved it
                AppTelemetry.DoNotSend = !Properties.Settings.Default.AppTelemetry;
                if (string.IsNullOrEmpty(Properties.Settings.Default.AppTelemetryUID))
                {
                    AppTelemetry.RegisterUser(CultureInfo.InstalledUICulture.EnglishName, MainViewModel.Version);
                }
            }
            catch
            { }
        }
示例#19
0
        /// <summary>
        /// Get the piece corners by finding the biggest rectangle of the contour points
        /// </summary>
        /// <param name="pieceID">ID of the piece</param>
        /// <param name="pieceImgBw">Black white image of piece</param>
        /// <param name="pieceImgColor">Color image of piece</param>
        /// <returns>List with corner points</returns>
        public override List <Point> FindCorners(string pieceID, Bitmap pieceImgBw, Bitmap pieceImgColor)
        {
            PluginFactory.LogHandle.Report(new LogEventInfo(pieceID + " Finding corners by finding the maximum rectangle within candidate points"));

            List <Point> corners = new List <Point>();

            // Find all dominant corner points using the GFTTDetector (this uses the Harris corner detector)
            GFTTDetector detector = new GFTTDetector(500, 0.01, 5, 2, true, 0.04);

            MKeyPoint[]  keyPoints       = detector.Detect(new Image <Gray, byte>(pieceImgBw));
            List <Point> possibleCorners = keyPoints.Select(k => Point.Round(k.Point)).ToList();

            if (possibleCorners.Count > 0)
            {
                // Sort the dominant corners by the distance to upper left corner of the bounding rectangle (0, 0) and keep only the corners that are near enough to this point
                List <Point> possibleCornersSortedUpperLeft = new List <Point>(possibleCorners);
                possibleCornersSortedUpperLeft.Sort(new DistanceToPointComparer(new Point(0, 0), DistanceOrders.NEAREST_FIRST));
                double minCornerDistUpperLeft = Utils.Distance(possibleCornersSortedUpperLeft[0], new PointF(0, 0));
                possibleCornersSortedUpperLeft = possibleCornersSortedUpperLeft.Where(c => Utils.Distance(c, new PointF(0, 0)) < minCornerDistUpperLeft * PieceFindCornersMaxCornerDistRatio).ToList();

                // Sort the dominant corners by the distance to upper right corner of the bounding rectangle (ImageWidth, 0) and keep only the corners that are near enough to this point
                List <Point> possibleCornersSortedUpperRight = new List <Point>(possibleCorners);
                possibleCornersSortedUpperRight.Sort(new DistanceToPointComparer(new Point(pieceImgBw.Width, 0), DistanceOrders.NEAREST_FIRST));
                double minCornerDistUpperRight = Utils.Distance(possibleCornersSortedUpperRight[0], new PointF(pieceImgBw.Width, 0));
                possibleCornersSortedUpperRight = possibleCornersSortedUpperRight.Where(c => Utils.Distance(c, new PointF(pieceImgBw.Width, 0)) < minCornerDistUpperRight * PieceFindCornersMaxCornerDistRatio).ToList();

                // Sort the dominant corners by the distance to lower right corner of the bounding rectangle (ImageWidth, ImageHeight) and keep only the corners that are near enough to this point
                List <Point> possibleCornersSortedLowerRight = new List <Point>(possibleCorners);
                possibleCornersSortedLowerRight.Sort(new DistanceToPointComparer(new Point(pieceImgBw.Width, pieceImgBw.Height), DistanceOrders.NEAREST_FIRST));
                double minCornerDistLowerRight = Utils.Distance(possibleCornersSortedLowerRight[0], new PointF(pieceImgBw.Width, pieceImgBw.Height));
                possibleCornersSortedLowerRight = possibleCornersSortedLowerRight.Where(c => Utils.Distance(c, new PointF(pieceImgBw.Width, pieceImgBw.Height)) < minCornerDistLowerRight * PieceFindCornersMaxCornerDistRatio).ToList();

                // Sort the dominant corners by the distance to lower left corner of the bounding rectangle (0, ImageHeight) and keep only the corners that are near enough to this point
                List <Point> possibleCornersSortedLowerLeft = new List <Point>(possibleCorners);
                possibleCornersSortedLowerLeft.Sort(new DistanceToPointComparer(new Point(0, pieceImgBw.Height), DistanceOrders.NEAREST_FIRST));
                double minCornerDistLowerLeft = Utils.Distance(possibleCornersSortedLowerLeft[0], new PointF(0, pieceImgBw.Height));
                possibleCornersSortedLowerLeft = possibleCornersSortedLowerLeft.Where(c => Utils.Distance(c, new PointF(0, pieceImgBw.Height)) < minCornerDistLowerLeft * PieceFindCornersMaxCornerDistRatio).ToList();

                // Combine all possibleCorners from the four lists and discard all combination with too bad angle differences
                List <FindCornerRectangleScore> scores = new List <FindCornerRectangleScore>();
                for (int indexUpperLeft = 0; indexUpperLeft < possibleCornersSortedUpperLeft.Count; indexUpperLeft++)
                {
                    for (int indexUpperRight = 0; indexUpperRight < possibleCornersSortedUpperRight.Count; indexUpperRight++)
                    {
                        for (int indexLowerRight = 0; indexLowerRight < possibleCornersSortedLowerRight.Count; indexLowerRight++)
                        {
                            for (int indexLowerLeft = 0; indexLowerLeft < possibleCornersSortedLowerLeft.Count; indexLowerLeft++)
                            {
                                if (PluginFactory.CancelToken.IsCancellationRequested)
                                {
                                    PluginFactory.CancelToken.ThrowIfCancellationRequested();
                                }

                                // Possible corner combination
                                Point[] tmpCorners = new Point[]
                                {
                                    possibleCornersSortedUpperLeft[indexUpperLeft],         // the corners are ordered beginning in the upper left corner and going counter clock wise
                                    possibleCornersSortedLowerLeft[indexLowerLeft],
                                    possibleCornersSortedLowerRight[indexLowerRight],
                                    possibleCornersSortedUpperRight[indexUpperRight]
                                };
                                double angleDiff = RectangleDifferenceAngle(tmpCorners);
                                if (angleDiff > PieceFindCornersMaxAngleDiff)
                                {
                                    continue;
                                }

                                double area = CvInvoke.ContourArea(new VectorOfPoint(tmpCorners));
                                FindCornerRectangleScore score = new FindCornerRectangleScore()
                                {
                                    AngleDiff = angleDiff, RectangleArea = area, PossibleCorners = tmpCorners
                                };
                                scores.Add(score);
                            }
                        }
                    }
                }

                // Order the scores by rectangle area (biggest first) and take the PossibleCorners of the biggest rectangle as corners
                scores = scores.OrderByDescending(s => s.RectangleArea).ToList();
                if (scores.Count > 0)
                {
                    corners.AddRange(scores[0].PossibleCorners);
                }
            }

            if (corners.Count != 4)
            {
                PluginFactory.LogHandle.Report(new LogEventError(pieceID + " Failed to find correct number of corners. " + corners.Count + " found."));
            }

            if (PluginFactory.GetGeneralSettingsPlugin().SolverShowDebugResults)
            {
                using (Image <Rgb, byte> imgCorners = new Image <Rgb, byte>(pieceImgColor))
                {
                    Features2DToolbox.DrawKeypoints(imgCorners, new VectorOfKeyPoint(keyPoints), imgCorners, new Bgr(0, 0, 255));       // Draw the dominant key points

                    for (int i = 0; i < corners.Count; i++)
                    {
                        CvInvoke.Circle(imgCorners, Point.Round(corners[i]), 4, new MCvScalar(0, Math.Max(255 - i * 50, 50), 0), 3);
                    }
                    PluginFactory.LogHandle.Report(new LogEventImage(pieceID + " Corners", imgCorners.Bitmap));
                    imgCorners.Dispose();
                }
            }
            return(corners);
        }
示例#20
0
        private async Task <ActionResult> ShowClaim(Claim claim)
        {
            var error = WithClaim(claim);

            if (error != null)
            {
                return(error);
            }

            var printPlugins = claim.HasMasterAccess(CurrentUserId) && claim.IsApproved
              ? PluginFactory.GetProjectOperations <IPrintCardPluginOperation>(claim.Project).Where(
                p => p.AllowPlayerAccess || claim.HasMasterAccess(CurrentUserId))
              : Enumerable.Empty <PluginOperationData <IPrintCardPluginOperation> >();

            var currentUser = await GetCurrentUserAsync().ConfigureAwait(false);

            var plots = claim.IsApproved && claim.Character != null
              ? await _plotRepository.GetPlotsForCharacter(claim.Character).ConfigureAwait(false)
              : new PlotElement[]
            {
            };

            IEnumerable <ProjectAccommodationType>        availableAccommodation  = null;
            IEnumerable <AccommodationRequest>            requestForAccommodation = null;
            IEnumerable <AccommodationPotentialNeighbors> potentialNeighbors      = null;
            IEnumerable <AccommodationInvite>             incomingInvite          = null;
            IEnumerable <AccommodationInvite>             outgoingInvite          = null;


            if (claim.Project.Details.EnableAccommodation)
            {
                availableAccommodation = await
                                         _accommodationRepository.GetAccommodationForProject(claim.ProjectId).ConfigureAwait(false);

                requestForAccommodation = await _accommodationRequestRepository
                                          .GetAccommodationRequestForClaim(claim.ClaimId).ConfigureAwait(false);

                var acceptedRequest = requestForAccommodation
                                      .FirstOrDefault(request => request.IsAccepted == AccommodationRequest.InviteState.Accepted);
                var acceptedRequestId = acceptedRequest?.Id;
                var acceptedRequestAccommodationTypeIdId = acceptedRequest?.AccommodationTypeId;

                if (acceptedRequestId != null)
                {
                    var sameRequest = (await
                                       _accommodationRequestRepository.GetClaimsWithSameAccommodationTypeToInvite(
                                           acceptedRequestAccommodationTypeIdId.Value).ConfigureAwait(false)).Where(c => c.ClaimId != claim.ClaimId)
                                      .Select(c => new AccommodationPotentialNeighbors(c, NeighborType.WithSameType));;
                    var noRequest = (await
                                     _accommodationRequestRepository.GetClaimsWithOutAccommodationRequest(claim.ProjectId).ConfigureAwait(false)).Select(c => new AccommodationPotentialNeighbors(c, NeighborType.NoRequest));;
                    var currentNeighbors = (await
                                            _accommodationRequestRepository.GetClaimsWithSameAccommodationRequest(
                                                acceptedRequestId.Value).ConfigureAwait(false)).Select(c => new AccommodationPotentialNeighbors(c, NeighborType.Current));
                    potentialNeighbors = sameRequest.Union(noRequest).Where(element => currentNeighbors.All(el => el.ClaimId != element.ClaimId));
                }

                incomingInvite = await AccommodationInviteRepository.GetIncomingInviteForClaim(claim).ConfigureAwait(false);

                outgoingInvite = await AccommodationInviteRepository.GetOutgoingInviteForClaim(claim).ConfigureAwait(false);
            }

            var claimViewModel = new ClaimViewModel(currentUser, claim, printPlugins, plots, UriService, availableAccommodation, requestForAccommodation, potentialNeighbors, incomingInvite, outgoingInvite);

            if (claim.CommentDiscussion.Comments.Any(c => !c.IsReadByUser(CurrentUserId)))
            {
                await
                _claimService.UpdateReadCommentWatermark(claim.ProjectId, claim.CommentDiscussion.CommentDiscussionId,
                                                         claim.CommentDiscussion.Comments.Max(c => c.CommentId)).ConfigureAwait(false);
            }


            var parents = claim.GetTarget().GetParentGroupsToTop();

            claimViewModel.SubscriptionTooltip =
                claimViewModel.GetFullSubscriptionTooltip(parents, currentUser.Subscriptions, claimViewModel.ClaimId);

            return(View("Edit", claimViewModel));
        }
示例#21
0
        public void Load(IServiceProvider serviceProvider)
        {
            PluginFactory.Register(new ReflectorPlugin(this));

            _sp  = serviceProvider;
            _wm  = GetService <IWindowManager>();
            _ab  = GetService <IAssemblyBrowser>();
            _cbm = GetService <ICommandBarManager>();
            _am  = GetService <IAssemblyManager>();

            // Main Window
            _items         = new List <UIContext>();
            ReflexilWindow = new Forms.ReflexilWindow();
            _wm.Windows.Add(ReflexilWindowId, ReflexilWindow, ReflexilWindowText);

            // Main button
            AddButtonSeparatorIfNeeded(ReflectorToolsId);
            _items.Add(new ButtonUIContext(_cbm.CommandBars[ReflectorToolsId], ReflexilButtonText, MainButtonClick, BasePlugin.ReflexilImage));

            AddButtonSeparatorIfNeeded(ReflectorToolBarId);
            _items.Add(new ButtonUIContext(_cbm.CommandBars[ReflectorToolBarId], ReflexilButtonText, MainButtonClick, BasePlugin.ReflexilImage));

            using (var browserimages = new ImageList())
            {
                browserimages.Images.AddStrip(PluginFactory.GetInstance().GetAllBrowserImages());
                browserimages.TransparentColor = Color.Green;

                using (var barimages = new ImageList())
                {
                    barimages.Images.AddStrip(PluginFactory.GetInstance().GetAllBarImages());

                    // Menus
                    var typemenu        = AddMenu(ReflectorTypedecId);
                    var assemblymenu    = AddMenu(ReflectorAssemblyId);
                    var assemblyrefmenu = AddMenu(ReflectorAssemblyrefId);
                    var modulemenu      = AddMenu(ReflectorModuleId);
                    var methodmenu      = AddMenu(ReflectorMethoddecId);
                    var fieldmenu       = AddMenu(ReflectorFielddecId);
                    var propertymenu    = AddMenu(ReflectorPropertydecId);
                    var eventmenu       = AddMenu(ReflectorEventdecId);
                    var resmenu         = AddMenu(ReflectorResourceId);

                    var allmenus = new UIContext[]
                    { typemenu, assemblymenu, assemblyrefmenu, modulemenu, methodmenu, fieldmenu, propertymenu, eventmenu, resmenu };
                    var membersmenus = new UIContext[]
                    { assemblyrefmenu, typemenu, methodmenu, fieldmenu, propertymenu, eventmenu, resmenu };

                    // Type declaration menu
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner class", (sender, e) => Inject(InjectType.Class),
                                                    browserimages.Images[(int)EBrowserImages.PublicClass]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner interface", (sender, e) => Inject(InjectType.Interface),
                                                    browserimages.Images[(int)EBrowserImages.PublicInterface]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner struct", (sender, e) => Inject(InjectType.Struct),
                                                    browserimages.Images[(int)EBrowserImages.PublicStructure]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner enum", (sender, e) => Inject(InjectType.Enum),
                                                    browserimages.Images[(int)EBrowserImages.PublicEnum]));
                    _items.Add(new SubMenuUIContext(typemenu));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject event", (sender, e) => Inject(InjectType.Event),
                                                    browserimages.Images[(int)EBrowserImages.PublicEvent]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject field", (sender, e) => Inject(InjectType.Field),
                                                    browserimages.Images[(int)EBrowserImages.PublicField]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject method", (sender, e) => Inject(InjectType.Method),
                                                    browserimages.Images[(int)EBrowserImages.PublicMethod]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject constructor", (sender, e) => Inject(InjectType.Constructor),
                                                    browserimages.Images[(int)EBrowserImages.PublicConstructor]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject property", (sender, e) => Inject(InjectType.Property),
                                                    browserimages.Images[(int)EBrowserImages.PublicProperty]));

                    // Shared subitems for Assembly/Module
                    foreach (var menu in new[] { assemblymenu, modulemenu })
                    {
                        _items.Add(new SubMenuUIContext(menu, "Inject class", (sender, e) => Inject(InjectType.Class),
                                                        browserimages.Images[(int)EBrowserImages.PublicClass]));
                        _items.Add(new SubMenuUIContext(menu, "Inject interface", (sender, e) => Inject(InjectType.Interface),
                                                        browserimages.Images[(int)EBrowserImages.PublicInterface]));
                        _items.Add(new SubMenuUIContext(menu, "Inject struct", (sender, e) => Inject(InjectType.Struct),
                                                        browserimages.Images[(int)EBrowserImages.PublicStructure]));
                        _items.Add(new SubMenuUIContext(menu, "Inject enum", (sender, e) => Inject(InjectType.Enum),
                                                        browserimages.Images[(int)EBrowserImages.PublicEnum]));
                        _items.Add(new SubMenuUIContext(menu, "Inject assembly reference",
                                                        (sender, e) => Inject(InjectType.AssemblyReference), browserimages.Images[(int)EBrowserImages.LinkedAssembly]));
                        _items.Add(new SubMenuUIContext(menu, "Inject resource", (sender, e) => Inject(InjectType.Resource),
                                                        browserimages.Images[(int)EBrowserImages.Resources]));
                        _items.Add(new SubMenuUIContext(menu));
                        _items.Add(new SubMenuUIContext(menu, "Save as...", SaveAssembly, barimages.Images[(int)EBarImages.Save]));
                        _items.Add(new SubMenuUIContext(menu, "Obfuscator search...", SearchObfuscator, barimages.Images[(int)EBarImages.Search]));
                        _items.Add(new SubMenuUIContext(menu, "Reload", ReloadAssembly, barimages.Images[(int)EBarImages.Reload]));
                        _items.Add(new SubMenuUIContext(menu, "Rename...", RenameItem, barimages.Images[(int)EBarImages.New]));
                        _items.Add(new SubMenuUIContext(menu, "Verify", VerifyAssembly, barimages.Images[(int)EBarImages.Check]));
                    }

                    // Shared subitems for renaming/deleting
                    foreach (var uiContext in membersmenus)
                    {
                        var menu = (MenuUIContext)uiContext;
                        if (menu == typemenu)
                        {
                            _items.Add(new SubMenuUIContext(menu));
                        }

                        _items.Add(new SubMenuUIContext(menu, "Rename...", RenameItem, barimages.Images[(int)EBarImages.New]));
                        _items.Add(new SubMenuUIContext(menu, "Delete", DeleteItem, barimages.Images[(int)EBarImages.Delete]));
                    }

                    _items.AddRange(allmenus);
                }
            }

            // Main events
            _ab.ActiveItemChanged += ActiveItemChanged;
            _am.AssemblyLoaded    += AssemblyLoaded;
            _am.AssemblyUnloaded  += AssemblyUnloaded;

            ReflexilWindow.HandleItem(_ab.ActiveItem);
        }
示例#22
0
        public void Initialize(IVVVVHost vvvvHost, INodeBrowserHost nodeBrowserHost, IWindowSwitcherHost windowSwitcherHost, IKommunikatorHost kommunikatorHost)
        {
            // Used for Windows Forms message loop
            FIsRunning = true;

            //set blackbox mode?
            this.IsBlackBoxMode = vvvvHost.IsBlackBoxMode;

            // Set VVVV45 to this running vvvv.exe
            Environment.SetEnvironmentVariable(ENV_VVVV, Path.GetFullPath(Shell.CallerPath.ConcatPath("..").ConcatPath("..")));

            FVVVVHost       = vvvvHost;
            NodeInfoFactory = new ProxyNodeInfoFactory(vvvvHost.NodeInfoFactory);

            FVVVVHost.AddMouseClickListener(this);
            FVVVVHost.AddNodeSelectionListener(this);
            FVVVVHost.AddWindowListener(this);
            FVVVVHost.AddWindowSelectionListener(this);
            FVVVVHost.AddComponentModeListener(this);
            FVVVVHost.AddEnumListener(this);

            NodeInfoFactory.NodeInfoUpdated += factory_NodeInfoUpdated;

            // Route log messages to vvvv
            Logger.AddLogger(new VVVVLogger(FVVVVHost));

            DeviceService = new DeviceService(vvvvHost.DeviceService);
            MainLoop      = new MainLoop(vvvvHost.MainLoop);

            ExposedNodeService = new ExposedNodeService(vvvvHost.ExposedNodeService, NodeInfoFactory);

            NodeBrowserHost    = new ProxyNodeBrowserHost(nodeBrowserHost, NodeInfoFactory);
            WindowSwitcherHost = windowSwitcherHost;
            KommunikatorHost   = kommunikatorHost;

            //do not add the entire directory for faster startup
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(HDEHost).Assembly.Location));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(NodeCollection).Assembly.Location));
            //allow plugin writers to add their own factories (deprecated, see below)
            var factoriesPath = ExePath.ConcatPath(@"lib\factories");

            if (Directory.Exists(factoriesPath))
            {
                catalog.Catalogs.Add(new DirectoryCatalog(factoriesPath));
            }

            //register custom assembly resolvers which look also in the PACK_NAME/core and PACK_NAME/core/[x86|x64] folders
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;

            //search for packs, add factories dir to this catalog, add core dir to assembly search path,
            //add nodes to nodes search path
            var packsPath = Path.Combine(ExePath, "packs");

            if (Directory.Exists(packsPath))
            {
                LoadFactoriesFromLegacyPackages(packsPath, catalog);
            }
            //new package loading system
            LoadFactoriesFromPackages(catalog);

            Container = new CompositionContainer(catalog);
            Container.ComposeParts(this);

            PluginFactory.AddFile(ExePath.ConcatPath(@"lib\nodes\plugins\VVVV.Nodes.dll"));

            //Get node infos from core plugins here to avoid looping all node infos
            var windowSwitcherNodeInfo = GetNodeInfo(WINDOW_SWITCHER);
            var kommunikatorNodeInfo   = GetNodeInfo(KOMMUNIKATOR);
            var nodeBrowserNodeInfo    = GetNodeInfo(NODE_BROWSER);

            foreach (var factory in AddonFactories)
            {
                if (factory is PatchFactory)
                {
                    NodeCollection.Add(string.Empty, ExePath.ConcatPath(@"lib\nodes\native\"), factory, true, false);
                }
            }

            //now instantiate a NodeBrowser, a Kommunikator and a WindowSwitcher
            FWindowSwitcher = PluginFactory.CreatePlugin(windowSwitcherNodeInfo, null);
            FKommunikator   = PluginFactory.CreatePlugin(kommunikatorNodeInfo, null);
            FNodeBrowser    = PluginFactory.CreatePlugin(nodeBrowserNodeInfo, null);

            this.IsBoygroupClient = FVVVVHost.IsBoygroupClient;
            if (IsBoygroupClient)
            {
                this.BoygroupServerIP = FVVVVHost.BoygroupServerIP;
            }

            var clockport = 3334;

            try
            {
                if (Environment.CommandLine.Contains("/clockport"))
                {
                    var env = Environment.GetCommandLineArgs();
                    var idx = Array.IndexOf(env, "/clockport") + 1;
                    clockport = int.Parse(env[idx]);
                }
            }
            catch (Exception)
            {
                throw new Exception("Could not parse clockport, make sure you have the right syntax, e.g. '/clockport 3344' ");
            }

            //start time server of client
            FNetTimeSync = IsBoygroupClient ? new UDPTimeClient(BoygroupServerIP, clockport) : new UDPTimeServer(clockport);
            FNetTimeSync.Start();

            //now that all basics are set up, see if there are any node search paths to add
            //from the installed packs
            if (Directory.Exists(packsPath))
            {
                LoadNodesFromLegacyPackages(packsPath);
            }
            LoadNodesFromPackages();
        }
示例#23
0
 /// <summary>
 /// Assembly loaded
 /// </summary>
 /// <param name="sender">Event sender</param>
 /// <param name="e">Event parameters</param>
 protected virtual void AssemblyLoaded(object sender, EventArgs e)
 {
     PluginFactory.GetInstance().ReloadAssemblies(Assemblies);
 }
示例#24
0
 //---
 /// <summary>
 /// Initializes a new instance of the ParallelServer class
 /// </summary>
 /// <param name="highestPriority">the highest priority that is processed by this server</param>
 /// <param name="lowestPriority">the lowest priority that is processed by this server</param>
 /// <param name="workerCount">the number of workers to use</param>
 /// <param name="workerPollInterval">the interval after which a worker will poll the working queue if it has not been triggered</param>
 /// <param name="lowTaskThreshold">the minimum number of tasks that the workerqueue should contain</param>
 /// <param name="highTaskThreshold">the maximum number of tasks that the workerqueue should contain</param>
 /// <param name="useAffineThreads">indicates whether to use affine threads</param>
 /// <param name="eventReTriggerInterval">the timeout in minutes after which an event that has not been commited by a client is re-triggered</param>
 /// <param name="useTasks">indicates whether to use native tasks for the processing</param>
 /// <param name="factory">the factory that is used to initialize further plugins</param>
 protected ParallelServer(int highestPriority, int lowestPriority, int workerCount, int workerPollInterval, int lowTaskThreshold,
                          int highTaskThreshold, bool useAffineThreads, int eventReTriggerInterval, bool runWithoutSchedulers, bool useTasks, PluginFactory factory)
     : this(
         highestPriority, lowestPriority, workerCount, workerPollInterval, lowTaskThreshold, highTaskThreshold, useAffineThreads,
         eventReTriggerInterval, 0, runWithoutSchedulers, useTasks, factory)
 {
 }
示例#25
0
        /// <summary>
        /// Addin load method
        /// </summary>
        /// <param name="serviceProvider">Cecil Studio service provider</param>
        public void Load(IServiceProvider serviceProvider)
        {
            PluginFactory.Register(new CecilStudioPlugin(this));

            _sp  = serviceProvider;
            _wm  = GetService <IWindowManager>();
            _ab  = GetService <IAssemblyBrowser>();
            _cbm = GetService <IBarManager>();
            _am  = GetService <IAssemblyManager>();

            CheckPrerequisites();

            // Main Window
            _items         = new List <UIContext>();
            ReflexilWindow = new Forms.ReflexilWindow();
            var window = _wm.Windows.Add(ReflexilWindowId, ReflexilWindow, ReflexilWindowText);

            window.Image = BasePlugin.ReflexilImage;

            // Main button
            _items.Add(new ButtonUIContext(_cbm.Bars[BarNames.Toolbar]));
            _items.Add(new ButtonUIContext(_cbm.Bars[BarNames.Toolbar], ReflexilButtonText, Button_Click, BasePlugin.ReflexilImage));

            using (var browserimages = new ImageList())
            {
                browserimages.Images.AddStrip(PluginFactory.GetInstance().GetAllBrowserImages());
                browserimages.TransparentColor = Color.Green;

                using (var barimages = new ImageList())
                {
                    barimages.Images.AddStrip(PluginFactory.GetInstance().GetAllBarImages());

                    // Menus
                    var typemenu        = AddMenu(BarNames.TypeDefinitionBrowser.ToString());
                    var assemblymenu    = AddMenu(BarNames.AssemblyDefinitionBrowser.ToString());
                    var assemblyrefmenu = AddMenu(BarNames.AssemblyNameReferenceBrowser.ToString());
                    var modulemenu      = AddMenu(BarNames.ModuleDefinitionBrowser.ToString());
                    var methodmenu      = AddMenu(BarNames.MethodDefinitionBrowser.ToString());
                    var fieldmenu       = AddMenu(BarNames.FieldDefinitionBrowser.ToString());
                    var propertymenu    = AddMenu(BarNames.PropertyDefinitionBrowser.ToString());
                    var eventmenu       = AddMenu(BarNames.EventDefinitionBrowser.ToString());

                    var allmenus     = new UIContext[] { typemenu, assemblymenu, assemblyrefmenu, modulemenu, methodmenu, fieldmenu, propertymenu, eventmenu };
                    var membersmenus = new UIContext[] { assemblyrefmenu, typemenu, methodmenu, fieldmenu, propertymenu, eventmenu };

                    // Type declaration menu
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner class", (sender, e) => Inject(EInjectType.Class), browserimages.Images[(int)EBrowserImages.PublicClass]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner interface", (sender, e) => Inject(EInjectType.Interface), browserimages.Images[(int)EBrowserImages.PublicInterface]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner struct", (sender, e) => Inject(EInjectType.Struct), browserimages.Images[(int)EBrowserImages.PublicStructure]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject inner enum", (sender, e) => Inject(EInjectType.Enum), browserimages.Images[(int)EBrowserImages.PublicEnum]));
                    _items.Add(new SubMenuUIContext(typemenu));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject event", (sender, e) => Inject(EInjectType.Event), browserimages.Images[(int)EBrowserImages.PublicEvent]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject field", (sender, e) => Inject(EInjectType.Field), browserimages.Images[(int)EBrowserImages.PublicField]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject method", (sender, e) => Inject(EInjectType.Method), browserimages.Images[(int)EBrowserImages.PublicMethod]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject constructor", (sender, e) => Inject(EInjectType.Constructor), browserimages.Images[(int)EBrowserImages.PublicConstructor]));
                    _items.Add(new SubMenuUIContext(typemenu, "Inject property", (sender, e) => Inject(EInjectType.Property), browserimages.Images[(int)EBrowserImages.PublicProperty]));

                    // Shared subitems for Assembly/Module
                    foreach (var menu in new[] { assemblymenu, modulemenu })
                    {
                        _items.Add(new SubMenuUIContext(menu, "Inject class", (sender, e) => Inject(EInjectType.Class), browserimages.Images[(int)EBrowserImages.PublicClass]));
                        _items.Add(new SubMenuUIContext(menu, "Inject interface", (sender, e) => Inject(EInjectType.Interface), browserimages.Images[(int)EBrowserImages.PublicInterface]));
                        _items.Add(new SubMenuUIContext(menu, "Inject struct", (sender, e) => Inject(EInjectType.Struct), browserimages.Images[(int)EBrowserImages.PublicStructure]));
                        _items.Add(new SubMenuUIContext(menu, "Inject enum", (sender, e) => Inject(EInjectType.Enum), browserimages.Images[(int)EBrowserImages.PublicEnum]));
                        _items.Add(new SubMenuUIContext(menu, "Inject assembly reference", (sender, e) => Inject(EInjectType.AssemblyReference), browserimages.Images[(int)EBrowserImages.LinkedAssembly]));
                        _items.Add(new SubMenuUIContext(menu));
                        _items.Add(new SubMenuUIContext(menu, "Save as...", (sender, e) => AssemblyHelper.SaveAssembly(GetCurrentAssemblyDefinition(), GetCurrentModuleOriginalLocation()), barimages.Images[(int)EBarImages.Save]));
                        /*_items.Add(new SubMenuUIContext(menu, "Obfuscator search...", (sender, e) => AssemblyHelper.SearchObfuscator(GetCurrentModuleOriginalLocation()), barimages.Images[(int)EBarImages.Search]));*/
                        _items.Add(new SubMenuUIContext(menu, "Reload", ReloadAssembly, barimages.Images[(int)EBarImages.Reload]));
                        _items.Add(new SubMenuUIContext(menu, "Rename...", RenameItem, barimages.Images[(int)EBarImages.New]));
                        _items.Add(new SubMenuUIContext(menu, "Verify", (sender, e) => AssemblyHelper.VerifyAssembly(GetCurrentAssemblyDefinition(), GetCurrentModuleOriginalLocation()), barimages.Images[(int)EBarImages.Check]));
                    }

                    // Shared subitems for renaming/deleting
                    foreach (var uiContext in membersmenus)
                    {
                        var menu = (MenuUIContext)uiContext;
                        if (menu == typemenu)
                        {
                            _items.Add(new SubMenuUIContext(menu));
                        }

                        _items.Add(new SubMenuUIContext(menu, "Rename...", RenameItem, barimages.Images[(int)EBarImages.New]));
                        _items.Add(new SubMenuUIContext(menu, "Delete", DeleteMember, barimages.Images[(int)EBarImages.Delete]));
                    }

                    _items.AddRange(allmenus);
                }
            }

            // Main events
            _ab.ActiveItemChanged += ActiveItemChanged;
            _am.AssemblyLoaded    += AssemblyLoaded;
            _am.AssemblyUnloaded  += AssemblyUnloaded;

            PluginFactory.GetInstance().ReloadAssemblies(_am.Assemblies.ToList());
            ReflexilWindow.HandleItem(_ab.ActiveItem);
        }
示例#26
0
 /// <summary>
 /// Initializes a new instance of the ParallelServer class
 /// </summary>
 /// <param name="highestPriority">the highest priority that is processed by this server</param>
 /// <param name="lowestPriority">the lowest priority that is processed by this server</param>
 /// <param name="workerCount">the number of workers to use</param>
 /// <param name="workerPollInterval">the interval after which a worker will poll the working queue if it has not been triggered</param>
 /// <param name="lowTaskThreshold">the minimum number of tasks that the workerqueue should contain</param>
 /// <param name="highTaskThreshold">the maximum number of tasks that the workerqueue should contain</param>
 /// <param name="useAffineThreads">indicates whether to use affine threads</param>
 /// <param name="eventReTriggerInterval">the timeout in minutes after which an event that has not been commited by a client is re-triggered</param>
 /// <param name="maximumFailsPerItem">defines how many times a task can fail before it is considered a failure</param>
 /// <param name="useTasks">indicates whether to use native tasks for the processing</param>
 /// <param name="factory">the factory that is used to initialize further plugins</param>
 /// <param name="watchDog">a watchdog instance that is used to restart non-responsive processors</param>
 protected ParallelServer(int highestPriority, int lowestPriority, int workerCount, int workerPollInterval, int lowTaskThreshold, int highTaskThreshold, bool useAffineThreads, int eventReTriggerInterval, int maximumFailsPerItem, bool runWithoutSchedulers, bool useTasks, PluginFactory factory, WatchDog watchDog) :
     this(highestPriority, lowestPriority, workerCount, workerPollInterval, lowTaskThreshold, highTaskThreshold, useAffineThreads, eventReTriggerInterval, maximumFailsPerItem, runWithoutSchedulers, useTasks, factory)
 {
     this.watchDog = watchDog;
 }
 bool IHandler.IsItemHandled(object item)
 {
     return(PluginFactory.GetInstance().IsAssemblyDefinitionHandled(item));
 }
示例#28
0
        //---

        /// <summary>
        /// Initializes a new instance of the ParallelServer class
        /// </summary>
        /// <param name="highestPriority">the highest priority that is processed by this server</param>
        /// <param name="lowestPriority">the lowest priority that is processed by this server</param>
        /// <param name="workerCount">the number of workers to use</param>
        /// <param name="workerPollInterval">the interval after which a worker will poll the working queue if it has not been triggered</param>
        /// <param name="lowTaskThreshold">the minimum number of tasks that the workerqueue should contain</param>
        /// <param name="highTaskThreshold">the maximum number of tasks that the workerqueue should contain</param>
        /// <param name="useAffineThreads">indicates whether to use affine threads</param>
        /// <param name="eventReTriggerInterval">the timeout in minutes after which an event that has not been commited by a client is re-triggered</param>
        /// <param name="maximumFailsPerItem">defines how many times a task can fail before it is considered a failure</param>
        /// <param name="useTasks">indicates whether to use native tasks for the processing</param>
        /// <param name="factory">the factory that is used to initialize further plugins</param>
        protected ParallelServer(int highestPriority, int lowestPriority, int workerCount, int workerPollInterval, int lowTaskThreshold, int highTaskThreshold, bool useAffineThreads, int eventReTriggerInterval, int maximumFailsPerItem, bool runWithoutSchedulers, bool useTasks, PluginFactory factory) : this()
        {
            packages = new Dictionary <int, ConcurrentBag <TPackage> >();
            for (int i = highestPriority; i <= lowestPriority; i++)
            {
                packages.Add(i, new ConcurrentBag <TPackage>());
            }

            this.highestPriority        = highestPriority;
            this.lowestPriority         = lowestPriority;
            this.workerCount            = workerCount;
            this.workerPollInterval     = workerPollInterval;
            this.lowTaskThreshold       = lowTaskThreshold;
            this.highTaskThreshold      = highTaskThreshold;
            this.useAffineThreads       = useAffineThreads;
            this.eventReTriggerInterval = eventReTriggerInterval;
            this.maximumFailsPerItem    = maximumFailsPerItem;
            this.factory              = factory;
            this.useTasks             = useTasks;
            this.runWithoutSchedulers = runWithoutSchedulers;
            eventReTriggerer.Change(10000, 10000);
        }
 public bool IsItemHandled(object item)
 {
     return(PluginFactory.GetInstance().IsModuleDefinitionHandled(item));
 }
示例#30
0
        /// <summary>
        /// Retrieve the matching assembly definition reference in the Cecil object model
        /// </summary>
        /// <param name="aloc">Reflector assembly location</param>
        /// <returns>Cecil assembly assembly definition (null if not found)</returns>
        public static AssemblyDefinition ReflectorAssemblyLocationToCecilAssemblyDefinition(IAssemblyLocation aloc)
        {
            var context = PluginFactory.GetInstance().GetAssemblyContext(aloc.Location);

            return(context != null ? context.AssemblyDefinition : null);
        }