public MashupInfoRepository(ILogManager logManager, IPluginContext context, ITpBus bus, IMashupScriptStorage scriptStorage)
 {
     _bus = bus;
     _scriptStorage = scriptStorage;
     _log = logManager.GetLogger(GetType());
     _context = context;
 }
        public void Initialize(IPluginContext context)
        {
            try // Try to load the config
            {
                string configPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\config.json"; // Define the config file 's path
                string content = File.ReadAllText(configPath, System.Text.Encoding.UTF8); // Get the content of the config file

                JsonTextReader reader = new JsonTextReader(new StringReader(content)); // Create the JSonTextReader

                /*
                 * Parse the Json here
                 * */
                string lastName = String.Empty;
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        lastName = (string) reader.Value;
                    }
                    else if (reader.TokenType == JsonToken.String)
                    {
                        planning.Add(lastName, (string)reader.Value);
                        lastName = "";
                    }
                }
            }
            catch (Exception) { } // Catch any error and don't notify it
        }
		public static void OptimizeDocumentIndexesIfRunning(this IDocumentIndexProvider documentIndexProvider, IPluginContext context, IActivityLogger logger)
		{
			foreach (IDocumentIndex documentIndex in GetDocumentIndexes(documentIndexProvider, context, runningOnly:true).Where(d => !d.IsOptimized))
			{
				documentIndex.Optimize(DocumentIndexOptimizeSetup.ImmediateOptimize);
			}
		}
        protected override MessageHandlerResult ExecuteCore(Message message, IPluginContext context)
        {
            var match = Matcher.Match(message.Text);
            if (!match.Success)
            {
                return NotHandled();
            }

            var values = new List<string>();
            values.Add(match.Groups[1].Value.Trim());
            values.AddRange(match.Groups[2].Captures.OfType<Capture>().Select(x => x.Value.Trim()));

            var options = (from v in values
                           where v.Length > 0 && !v.Equals("or", StringComparison.InvariantCultureIgnoreCase)
                           select v).ToList();

            if (options.Count == 0)
            {
                return Handled(Message("{0}: confuse BawBag, receive kicking...", context.User.Name), Kick());
            }
            
            var index = context.RandomProvider.Next(0, options.Count);

            return Handled(Message("@{0}: {1}", context.User.Name, options[index]));
        }
        protected override MessageHandlerResult ExecuteCore(Message message, IPluginContext context)
        {
            var match = Matcher.Match(message.Text);
            if (!match.Success)
            {
                return NotHandled();
            }
            
            var index = context.RandomProvider.Next(0, 2);
            string answerText;

            if (index == 0)
            {
                // Negative
                var answerIndex = context.RandomProvider.Next(0, NegativeResponses.Length);
                answerText = NegativeResponses[answerIndex];
            }
            else
            {
                // Positive
                var answerIndex = context.RandomProvider.Next(0, PositiveResponses.Length);
                answerText = PositiveResponses[answerIndex];
            }

            return Handled(Message("@{0}: {1}!", context.User.Name, answerText));
        }
		private MessageHandlerResult GetImage(string query, IPluginContext context)
		{
			try
			{
				var bingContainer = new Bing.BingSearchContainer(new Uri(BingApiUri))
					                    {
						                    Credentials =
							                    new NetworkCredential(BingApi, BingApi)
					                    };

				var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);
				var imageResults = imageQuery.Execute();

				if (imageResults != null)
				{
					var imageList = imageResults.ToList();
					if (imageList.Count > 0)
					{
						var index = context.RandomProvider.Next(imageList.Count);
						var url = imageList[index].MediaUrl;

						return this.Handled(this.Message(url));
					}
				}

				var response = context.TextProcessor.FormatPluginResponse("Really? Do you kiss ${SOMEONE}'s mum with that mouth?", context);
				return this.Handled(this.Message(response));
			}
			catch (Exception ex)
			{
				Log.ErrorException("Unable to search for images on bing.", ex);
				return this.Handled(this.Message("Uh Oh..."));
			}
		}
		protected override MessageHandlerResult ExecuteCore(Message message, IPluginContext context)
		{
			if (context.IsBotAddressed
					|| message.Type != MessageType.Default
					|| context.RandomProvider.Next(2) == 0
					|| !Matcher.IsMatch(message.Text))
			{
				return NotHandled();
			}

			var text = Matcher.Replace(
					message.Text,
					m =>
					{
						var capture = m.Captures[0].Value;
						if (capture[0] == 'e')
						{
							return "s" + capture;
						}

						if (capture[1] == 'X')
						{
							return "SE" + capture.Substring(1);
						}

						return "Se" + capture.Substring(1);
					});

			return Handled(Message(text));
		}
		public BuildSearchIndexesCommand(ITpBus bus, IProfileCollection profileCollection, IPluginContext pluginContext, IPluginMetadata pluginMetadata)
		{
			_bus = bus;
			_profileCollection = profileCollection;
			_pluginContext = pluginContext;
			_pluginMetadata = pluginMetadata;
		}
		private Maybe<IDocumentIndex> DoGetDocumentIndex(IPluginContext context, DocumentIndexTypeToken documentIndexTypeToken)
		{
			Lazy<IDocumentIndex> fetched;
			return _documentIndexes[documentIndexTypeToken].TryGetValue(context.AccountName.Value, out fetched)
				? Maybe.Return(fetched.Value)
				: Maybe.Nothing;
		}
		public SetEnableForTp2(IPluginContext pluginContext, IActivityLogger log, IProfileCollection profileCollection, ITpBus bus)
		{
			_pluginContext = pluginContext;
			_log = log;
			_profileCollection = profileCollection;
			_bus = bus;
		}
		public void ProcessMessage(Message message, IPluginContext context, IJabbRClient client)
		{
			Guard.NullParameter(message, () => message);
			Guard.NullParameter(context, () => context);
			Guard.NullParameter(client, () => client);

			foreach (var messageHandler in _messageHandlers)
			{
				Log.Trace("Applying handler: {0}", messageHandler.Name);

				try
				{
					var result = messageHandler.Execute(message, context);
					result.Execute(client, context.Room);

					var continueProcessing = !result.IsHandled || messageHandler.ContinueProcessing;
					if (!continueProcessing)
					{
						Log.Trace("Terminating message processing after: {0}.", messageHandler.Name);
						break;
					}
				}
				catch (Exception ex)
				{
					Log.ErrorException("Error applying handler: " + messageHandler.Name, ex);
				}
			}
		}
Example #12
0
        public static PluginRunContext Parse(PluginConfigItem configItem, IPluginContext context)
        {
            string runContext = configItem.RunContext;
            if (string.IsNullOrEmpty(runContext))
                runContext = MainThread;
            // on the same current thread
            if (runContext == MainThread)
            {
                if (!Contexts.ContainsKey(runContext))
                    Contexts[runContext] = new PluginRunContext(configItem, context);
            }
            else if (runContext == NewThread)
            {
                if (!Contexts.ContainsKey(runContext))
                    // get a new thread
                    Contexts[runContext] = new MultiThreadPluginRunContext(configItem, context);
            }
            else if (runContext == NewProcess)
            {
                if (!Contexts.ContainsKey(runContext))
                    // get a new process
                    Contexts[runContext] = new MultiProcessPluginRunContext(configItem, context);
            }
            else if (runContext == NewAppDomain)
            {
                if (!Contexts.ContainsKey(runContext))
                    // get a new AppDomain
                    Contexts[runContext] = new MultiAppDomainPuginRunContext(configItem, context);
            }
            Contexts[runContext].ConfigItem = configItem;
            Contexts[runContext].Context = context;
            configItem.PluginRunContext = Contexts[runContext];

            return Contexts[runContext];
        }
		public MashupScriptStorage(IPluginContext context, IMashupLocalFolder folder, ILogManager logManager, IMashupLoader mashupLoader)
		{
			_folder = folder;
			_mashupLoader = mashupLoader;
			_log = logManager.GetLogger(GetType());
			_accountName = context.AccountName;
		}
		public static void ShutdownDocumentIndexes(this IDocumentIndexProvider documentIndexProvider, IPluginContext context, DocumentIndexShutdownSetup setup, IActivityLogger logger)
		{
			foreach (IDocumentIndex documentIndex in GetDocumentIndexes(documentIndexProvider, context, runningOnly:false))
			{
				var success = documentIndex.Shutdown(setup);
				logger.DebugFormat("{0} was {1} shutted down", documentIndex.Type.TypeToken, success ? string.Empty : "not");
			}
		}
		private static IEnumerable<IDocumentIndex> GetDocumentIndexes(IDocumentIndexProvider documentIndexProvider, IPluginContext context, bool runningOnly)
		{
			IEnumerable<IDocumentIndex> documentIndexes = documentIndexProvider.DocumentIndexTypes.Select(t => t.TypeToken)
				.Distinct()
				.Select(t => runningOnly ? documentIndexProvider.GetDocumentIndex(context, t) : Maybe.Return(documentIndexProvider.GetOrCreateDocumentIndex(context,t)))
				.Choose();
			return documentIndexes;
		}
Example #16
0
 public static void PreLoadMainPlugins(IPluginContext mainPluginContext)
 {
     if (null != mainPluginContext)
     {
         PluginConfig pluginConfig = new PluginConfig(mainPluginContext);
         pluginConfig.PreLoadPlugins();
     }
 }
		public RunAtStartStopInitializer()
		{
			_documentIndexProvider = ObjectFactory.GetInstance<IDocumentIndexProvider>();
			_log = ObjectFactory.GetInstance <IActivityLogger>();
			_isOnSite = ObjectFactory.GetInstance<IMsmqTransport>().RoutableTransportMode == RoutableTransportMode.OnSite;
			_documentIndexRebuilder = ObjectFactory.GetInstance<DocumentIndexRebuilder>();
			_pluginContext = ObjectFactory.GetInstance<IPluginContext>();
		}
        private MessageHandlerResult GetKarma(string nick, IPluginContext context)
        {
            var result = context.RavenSession.Query<KarmaTotal, KarmaTotals>().SingleOrDefault(x => x.Name == nick);

            var quantity = (result == null) ? 0 : result.Quantity;

            return Handled(Message("@{0}: {1} = {2}", context.User.Name, nick, quantity));
        }
		public QueryPlanBuilder(IPluginContext pluginContext, IProfileReadonly profile, IDocumentIndexProvider documentIndexProvider, IEntityTypeProvider entityTypeProvider, IDocumentIdFactory documentIdFactory)
		{
			_accountName = pluginContext.AccountName;
			_profile = profile;
			_documentIndexProvider = documentIndexProvider;
			_entityTypeProvider = entityTypeProvider;
			_documentIdFactory = documentIdFactory;
			_contextQueryPlanBuilder = new ContextQueryPlanBuilder(_documentIndexProvider, _documentIdFactory, pluginContext.AccountName, _profile, _entityTypeProvider);
		}
Example #20
0
 public static PluginConfigItem GetPluginConfigItem(IPluginContext context, string url)
 {
     PluginConfigItem theItem = PluginConfigParser.GetPluginByUrl(
        PluginConfigParser.GetCachePluginList()[context.PluginContainer.Name], url
        );
     if (theItem != null)
         return theItem;
     throw new ArgumentOutOfRangeException();
 }
		public MashupInfoRepository(ILogManager logManager, IPluginContext context, ITpBus bus, IMashupScriptStorage scriptStorage)
		{
			_bus = bus;
			_scriptStorage = scriptStorage;
			_context = context;
			_lazyMashupManagerProfile =
				Lazy.Create(() => ObjectFactory.GetInstance<ISingleProfile>().Profile.GetProfile<MashupManagerProfile>());
			_log = logManager.GetLogger(GetType());
		}
Example #22
0
 public void Initialize(IPluginContext context)
 {
     try // Try to load the config
     {
         string content = File.ReadAllText(configPath, System.Text.Encoding.UTF8); // Read the content of the config file
         whoisUsers = JsonConvert.DeserializeObject<Dictionary<string, string>>(content); // Deserialize the config
     }
     catch (Exception) { }
 }
 public QueryPlanBuilder(IPluginContext pluginContext, IProfileReadonly profile, IDocumentIndexProvider documentIndexProvider, IEntityTypeProvider entityTypeProvider, IIndexDataFactory indexDataFactory, ContextQueryPlanBuilder contextQueryPlanBuilder)
 {
     _pluginContext = pluginContext;
     _profile = profile;
     _documentIndexProvider = documentIndexProvider;
     _entityTypeProvider = entityTypeProvider;
     _indexDataFactory = indexDataFactory;
     _contextQueryPlanBuilder = contextQueryPlanBuilder;
 }
		public ContextQueryPlanBuilder(IDocumentIndexProvider documentIndexProvider, IIndexDataFactory indexDataFactory, IPluginContext pluginContext, IProfileReadonly profile, IEntityTypeProvider entityTypeProvider, IEnumerable<IContextQueryPlanBuilder> planBuilders)
		{
			_documentIndexProvider = documentIndexProvider;
			_indexDataFactory = indexDataFactory;
			_pluginContext = pluginContext;
			_profile = profile;
			_entityTypeProvider = entityTypeProvider;
			_planBuilders = planBuilders;
		}
 protected PluginInfoSender()
 {
     _context = ObjectFactory.GetInstance<IPluginContext>();
     _bus = ObjectFactory.GetInstance<ITpBus>();
     PluginMetadata = ObjectFactory.GetInstance<IPluginMetadata>();
     _accountCollection = ObjectFactory.GetInstance<IAccountCollection>();
     _pluginQueueFactory = ObjectFactory.GetInstance<IPluginQueueFactory>();
     _pluginSettings = ObjectFactory.GetInstance<IPluginSettings>();
     _pluginIcon = ObjectFactory.GetInstance<PluginIcon>();
 }
Example #26
0
        public static void ExecutePlugin(IPluginContext parentProgram, string url)
        {
            if (!configs.ContainsKey(parentProgram))
            {
                //ShellUtils.ShowWarn("Please call LoadPlugin at first.");
                return;
            }

            configs[parentProgram].ExecutePlugin(url);
        }
Example #27
0
 /// <summary>
 /// Starts the plugin.
 /// </summary>
 /// <param name="config">The configuration object for this plugin</param>
 /// <param name="context">The context for this plugin</param>
 /// <returns>Always true</returns>
 public bool StartPlugin(Config config, IPluginContext context)
 {
     var path = Path.Combine(new FileInfo(this.GetType().Assembly.Location).DirectoryName, @"lib\Bass.Net");
     Bass.LoadMe(path);
     BassMix.LoadMe(path);
     Bass.BASS_PluginLoadDirectory(Path.Combine(path, "plugins"));
     _player = new Player();
     PluginManager.Register(_player);
     return true;
 }
		public static void ShutdownDocumentIndexesIfRunning(this IDocumentIndexProvider documentIndexProvider, IPluginContext context, DocumentIndexShutdownSetup setup, IActivityLogger logger)
		{
			foreach (IDocumentIndex documentIndex in GetDocumentIndexes(documentIndexProvider, context, runningOnly:true))
			{
				if (documentIndex.Shutdown(setup))
				{
					logger.DebugFormat("{0} was shutted down", documentIndex.Type.TypeToken);
				}
			}
		}
		public RunAtStartStopInitializer()
		{
			_documentIndexProvider = ObjectFactory.GetInstance<IDocumentIndexProvider>();
			_log = ObjectFactory.GetInstance <IActivityLogger>();
			_profileCollection = ObjectFactory.GetInstance<IProfileCollection>();
			_isOnSite = ObjectFactory.GetInstance<IMsmqTransport>().RoutableTransportMode == RoutableTransportMode.OnSite;
			_bus = ObjectFactory.GetInstance<ITpBus>();
			_pluginContext = ObjectFactory.GetInstance<IPluginContext>();
			_pluginMetadata = ObjectFactory.GetInstance<IPluginMetadata>();
		}
        protected override MessageHandlerResult ExecuteCore(Message message, IPluginContext context)
        {
            var getKaramMatch = GetKarmaExpression.Match(message.Text);
            if (getKaramMatch.Success)
            {
                return GetKarma(getKaramMatch.Groups["nick"].Value, context);
            }

            return NotHandled();
        }
        /// <summary>
        /// Create an adapter for a remote (out-of-process) plugin.
        /// </summary>
        /// <param name="router"></param>
        /// <param name="pluginContext"></param>
        /// <param name="descriptor"></param>
        /// <returns></returns>
        public static V8PluginAdapter CreateRemote(IV8PluginRouter router, IPluginContext pluginContext, PluginDescriptor descriptor)
        {
            V8PluginAdapter adapter;

            if (!RemotePluginAdapterCache.TryGetValue(descriptor.PluginId, out adapter))
            {
                lock (RemotePluginAdapterCache)
                {
                    if (!RemotePluginAdapterCache.TryGetValue(descriptor.PluginId, out adapter))
                    {
                        var plugin = new RemoteV8Plugin(router, pluginContext, descriptor);
                        adapter = new V8PluginAdapter(plugin);
                        RemotePluginAdapterCache.Add(descriptor.PluginId, adapter);
                    }
                }
            }

            return(adapter);
        }
Example #32
0
        /// <summary>
        /// Starts this plugin
        /// </summary>
        /// <param name="config">The configuration section for this plugin</param>
        /// <param name="context">The context for this plugin</param>
        /// <returns>False if no valid URL, key or secret was given in the config, otherwise true</returns>
        public bool StartPlugin(dynamic config, IPluginContext context)
        {
            // No config, no dice...
            if (config == null || config.GetType() != typeof(ConfigObject))
            {
                Log("This plugin requires a LastFMService config section with a url, key and secret setting");
                return(false);
            }

            // Get the values from the config
            config.TryGetString("url", out _url);
            config.TryGetString("key", out _key);
            config.TryGetString("secret", out _secret);

            // Collect errors
            var errors = new List <string>();

            if (String.IsNullOrWhiteSpace(_url))
            {
                errors.Add("No url given");
            }
            if (String.IsNullOrWhiteSpace(_key))
            {
                errors.Add("No key given");
            }
            if (String.IsNullOrWhiteSpace(_secret))
            {
                errors.Add("No secret given");
            }

            // Return
            if (errors.Count() > 0)
            {
                Log("Wrong LastFMService config: " + String.Join(", ", errors));
                return(false);
            }
            else
            {
                PluginManager.Register((IArtworkService)this);
                return(true);
            }
        }
        public void PerformAction(IPluginContext context, IReporter reporter)
        {
            var preferSpaces       = new PreferSpaces(context, reporter);
            var trailingWhiteSpace = new TrailingWhiteSpace(context, reporter);
            var indentation        = new Indentation(context, reporter);
            var lineLength         = new LineLength(context, reporter);

            string line;
            var    lineNumber = 0;

            while ((line = context.FileContents.ReadLine()) != null)
            {
                lineNumber++;

                preferSpaces.ParseLine(line, lineNumber);
                trailingWhiteSpace.ParseLine(line, lineNumber);
                indentation.ParseLine(line, lineNumber);
                lineLength.ParseLine(line, lineNumber);
            }
        }
Example #34
0
        public void PerformAction(IPluginContext context, IReporter reporter)
        {
            string line;
            var    lineNumber = 0;

            var reader = new StreamReader(File.OpenRead(context.FilePath));

            while ((line = reader.ReadLine()) != null)
            {
                lineNumber++;
                var column = line.IndexOf("\t", StringComparison.Ordinal);
                reporter.ReportViolation(new SampleRuleViolation(
                                             context.FilePath,
                                             "prefer-tabs",
                                             "Should use spaces rather than tabs",
                                             lineNumber,
                                             column,
                                             RuleViolationSeverity.Warning));
            }
        }
Example #35
0
 public IndexExistingEntitiesSaga(IEntityIndexer entityIndexer, IEntityTypeProvider entityTypesProvider, IDocumentIndexProvider documentIndexProvider, IPluginContext pluginContext, IActivityLogger logger, SagaServices sagaServices)
 {
     _entityIndexer         = entityIndexer;
     _entityTypesProvider   = entityTypesProvider;
     _documentIndexProvider = documentIndexProvider;
     _pluginContext         = pluginContext;
     _logger              = logger;
     _sagaServices        = sagaServices;
     _generalsIndexing    = new GeneralsIndexing(_entityIndexer, () => Data, _entityTypesProvider, d => _assignablesIndexing.Start(), q => Send(q), _logger);
     _assignablesIndexing = new AssignablesIndexing(_entityIndexer, () => Data, _entityTypesProvider, d => _testCasesIndexing.Start(), q => Send(q), _logger);
     _testCasesIndexing   = new TestCasesIndexing(_entityIndexer, () => Data, _entityTypesProvider, d => _impedimentsIndexing.Start(), q => Send(q), _logger);
     _impedimentsIndexing = new ImpedimentsIndexing(_entityIndexer, () => Data, _entityTypesProvider, d => _commentsIndexing.Start(), q => Send(q), _logger);
     _commentsIndexing    = new CommentsIndexing(_entityIndexer, () => Data, _entityTypesProvider, d =>
     {
         SendLocal(new IndexExistingEntitiesDoneLocalMessage {
             SagaId = Data.OuterSagaId
         });
         MarkAsComplete();
     }, q => Send(q), _logger, (dto, indexer) => indexer.AddCommentIndex(dto, DocumentIndexOptimizeSetup.NoOptimize));
 }
        protected override void Execute(IPluginContext context)
        {
            this.EnsureNotNull(context, nameof(context));

            context.EnsureTargetLogicalName(GlobalSettingEntity.TypeName(_prefix));

            var target = context
                         .GetTargetEntity();
            var image = context
                        .GetEntityImage(EntityImageType.PreImage, throwIfNull: context.IsUpdateMessage());

            var type = target
                       .GetAttributeValue <OptionSetValue>(GlobalSettingEntity.TypeFieldName(_prefix), image)?
                       .ToEnum <GlobalSettingType>() ?? GlobalSettingType.String;
            var value = target
                        .GetAttributeValue <String>(GlobalSettingEntity.ValueFieldName(_prefix), image);

            ValidateValue(type, value);
            SanitizeValue(target, type, value);
        }
Example #37
0
        //TimedCommandThread : Thread for printing the timed message
        public void TimedCommandThread(object o)
        {
            // Get the arguments
            object[]       arguments = (object[])o;
            IPluginContext context   = (IPluginContext)arguments[0];
            string         name      = (string)arguments[1];

            while (context.Bot.IsRunning) // While the bot is running
            {
                Command command = new Command {
                    Name = "FCKOFF2000"
                };                              // Create an empty command with a weird name
                foreach (Command c in commands) // Foreach name
                {
                    if (c.Name == name)         // Is it the name we are looking for ?
                    {
                        command = c;            // Store the command
                        break;
                    }
                }

                if (command.Name == "FCKOFF2000") // If no command found, command has been removed, then stop thread
                {
                    break;
                }

                if (command.Interval == 0) // If interval is 0, sleep and continue
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    Thread.Sleep(command.Interval * 60000); // Else wait for the desired time
                    if (!commands.Contains(command))
                    {
                        return;                                   // If command has been removed stop thread
                    }
                    context.Bot.SendChannelMessage(command.Text); // Then print the message
                }
            }
        }
Example #38
0
        /// <summary>
        /// Gets the context in use for the plugin's context type.
        /// </summary>
        public static IPluginContext GetContext(Plugin plugin, ContextType context)
        {
            IPluginContext pluginContext = null;

            if (plugin.HasPluginFile)
            {
                pluginContext = (from c in plugin.PluginFile.ContextItems
                                 where (c.UseForType != null && c.UseForType.Contains(context))
                                 select c).FirstOrDefault();

                if (pluginContext == null)
                {
                    //no context for this type so resort to standard context
                    pluginContext = (from c in plugin.PluginFile.ContextItems
                                     where (c.UseForType != null && c.UseForType.Contains(ContextType.Standard))
                                     select c).FirstOrDefault();
                }
            }

            return(pluginContext);
        }
Example #39
0
    public void Run(IPluginContext context)
    {
        _services = context.Services;
        var optionService = context.Services.Get <IPluginService>();

        options = new();
        if (!optionService.RequestOptions(options))
        {
            return;
        }

        var dialogService = context.Services.Get <IDialogService>();

        dialogService.ProgressDialog(progress =>
        {
            progress.Report(new ProgressInfo(isIndeterminate: true));
            if (options.Target == ConstOptions.MaxLink)
            {
                progress.Report(new ProgressInfo("Setting max link values..."));
                HandleMaxLink();
            }
            else if (options.Target == ConstOptions.IVs)
            {
                progress.Report(new ProgressInfo("Setting IV values..."));
                HandleIVs();
            }
            else if (options.Target == ConstOptions.Capacity)
            {
                progress.Report(new ProgressInfo("Setting capacity values..."));
                HandleCapacity();
            }
            else if (options.Target == ConstOptions.InitLink)
            {
                progress.Report(new ProgressInfo("Setting initial link values..."));
                HandleInitLink();
            }

            progress.Report(new ProgressInfo(progress: 100, isIndeterminate: false, statusText: "Done!"));
        });
    }
Example #40
0
        private Item[] GetSeriesListRequest(IPluginContext context, string url)
        {
            List <Item> items = new List <Item>();

            var header = new Dictionary <string, string>()
            {
                { "Accept-Encoding", "gzip, deflate, lzma" },
                { "Content-Type", "text/html; charset=UTF-8" }
            };

            context.ConsoleLog("url=" + string.Format(SITE_URL,
                                                      url.Replace("transСтандартный", "trans")));
            string response =
                context.GetHttpClient().GetRequest(string.Format(SITE_URL,
                                                                 url.Replace("transСтандартный", "trans")), header);

            var matches = Regex.Matches(response,
                                        "({)([\\s\\S]*?)(\"comment\"\\s*:\\s*\")(.+?)(\",)([\\s\\S]*?)(\"streamsend\"\\s*:\\s*\")(.+?)(\",)([\\s\\S]*?)(\"galabel\"\\s*:\\s*\")(.+?)(\",)([\\s\\S]*?)(\"file\"\\s*:\\s*\")(.+?)(\")([\\s\\S]*?)(})",
                                        RegexOptions.Multiline);

            var match = Regex.Match(url, "(\\/)(\\d+)(\\/list.xml)");

            Item Item = GetSerialInfoRequest(match.Groups[2].Value);

            for (int i = 0; i < matches.Count; i++)
            {
                var item = new Item()
                {
                    Name        = matches[i].Groups[4].Value.Replace("<br>", " "),
                    Link        = matches[i].Groups[16].Value,
                    Type        = ItemType.FILE,
                    ImageLink   = Item.ImageLink,
                    Description = Item.Description
                };

                items.Add(item);
            }

            return(items.ToArray());
        }
Example #41
0
        /// <summary>
        /// Assign the account to the parent Contact's owner
        /// </summary>
        /// <param name="context"></param>
        /// <param name="accountService"></param>
        /// <param name="systemUserService"></param>
        public void AssignContactOwnerToAccount(IPluginContext context, IAccountService accountService, ISystemuserService systemUserService)
        {
            #region Parameters check

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (accountService == null)
            {
                throw new ArgumentNullException(nameof(accountService));
            }
            if (systemUserService == null)
            {
                throw new ArgumentNullException(nameof(systemUserService));
            }

            #endregion

            var account = context.GetInputParameter <Entity>(InputParameters.Target);

            var primaryContactRef = account.GetAttributeValue <EntityReference>(AccountDefinition.Columns.PrimaryContactId);

            if (primaryContactRef != null)
            {
                var contact = accountService.Retrieve(primaryContactRef, ContactDefinition.Columns.OwnerId);

                var ownerRef = contact.GetAttributeValue <EntityReference>(ContactDefinition.Columns.OwnerId);

                // Check if the user is active
                if (systemUserService.IsActiveUser(ownerRef))
                {
                    account[AccountDefinition.Columns.OwnerId] = ownerRef;
                }
                else
                {
                    throw new InvalidPluginExecutionException("The owner in disabled.");
                }
            }
        }
Example #42
0
        public Playlist GetList(IPluginContext context)
        {
            IPAdress = context.GetRequestParams()["host"].Split(':')[0];



            var path = context.GetRequestParams().Get(PLUGIN_PATH);

            path = ((((path == null)) ? "plugin" : "plugin;" + path));

            if (context.GetRequestParams()["search"] != null)
            {
                switch (path)
                {
                //case "plugin;Search_NNM":
                case "plugin;Search_rutracker":
                    return(SearchListRuTr(context, context.GetRequestParams()["search"]));
                }
            }


            switch (path)
            {
            case "plugin":
                return(GetTopListRuTr(context));
            }

            string[] PathSpliter = path.Split(';');

            switch (PathSpliter[PathSpliter.Length - 1])
            {
            //Case "PAGERUTR"
            //    Return GetPAGERUTR(context, PathSpliter(PathSpliter.Length - 2))
            case "PAGEFILMRUTR":
                return(GetTorrentPageRuTr(context, PathSpliter[PathSpliter.Length - 2]));
            }

            return(GetTopListRuTr(context));
        }
Example #43
0
        /** <inheritdoc /> */
        public void Start(IPluginContext <TestIgnitePluginConfiguration> context)
        {
            context.RegisterExceptionMapping("org.apache.ignite.platform.plugin.PlatformTestPluginException",
                                             (className, message, inner, ignite) =>
                                             new TestIgnitePluginException(className, message, ignite, inner));

            context.RegisterCallback(1, (input, output) =>
            {
                CallbackResult = input.ReadString();
                output.WriteString(CallbackResult.ToUpper());

                return(CallbackResult.Length);
            });

            var ex = Assert.Throws <IgniteException>(() => context.RegisterCallback(1, (input, output) => 0));

            Assert.AreEqual("Plugin callback with id 1 is already registered", ex.Message);

            Context = context;

            EnsureIgniteWorks(false);
        }
Example #44
0
        public Task ExecuteAsync(IPluginContext context)
        {
            var task = Task.CompletedTask;

            try {
                win = CreateWindow();
                // w.Owner = context.Window;
                var vm = CreateViewModel(context);
                win.DataContext = vm;
                win.Closed     += (o, e) => vm.Closed();

                win.Show();

                task = win.Dispatcher.InvokeAsync(() => {
                    vm.Init();
                }).Task;
            } catch (Exception ex) {
                throw ex;
            }

            return(task);
        }
Example #45
0
        public void Initialize(ViDi2.Training.UI.IPluginContext context)
        {
            this.context = context;

            var pluginContainerMenuItem =
                context.MainWindow.MainMenu.Items.OfType <System.Windows.Controls.MenuItem>().
                First(i => (string)i.Header == "Plugins");

            pluginMenuItem = new MenuItem()
            {
                Header    = ((IPlugin)this).Name,
                IsEnabled = true,
                ToolTip   = ((IPlugin)this).Description
            };
            pluginMenuItem.Click += (o, a) =>
            {
                Task.Run(() =>
                {
                    Run();
                });
            };
            pluginContainerMenuItem.Items.Add(pluginMenuItem);
        }
Example #46
0
        public void Register(IPluginContext context)
        {
            context.Plugin.DisplayName = "Oxite Messages";

            context.Plugin.Settings["ExecuteOnAll"]     = true.ToString();
            context.Plugin.Settings["Interval"]         = TimeSpan.FromMinutes(2).Ticks.ToString();
            context.Plugin.Settings["FromEmailAddress"] = "";
            context.Plugin.Settings["SmtpClient.Host"]  = "";
            context.Plugin.Settings["SmtpClient.Port"]  = "";
            context.Plugin.Settings["SmtpClient.UseDefaultCredentials"] = "";
            context.Plugin.Settings["SmtpClient.Credentials.Username"]  = "";
            context.Plugin.Settings["SmtpClient.Credentials.Password"]  = "";
            context.Plugin.Settings["SmtpClient.Credentials.Domain"]    = "";
            context.Plugin.Settings["SmtpClient.EnableSsl"]             = "";

            context.Container.RegisterType <OxiteDataContext>(new InjectionConstructor(new ResolvedParameter <string>("ApplicationServices")));
            context.Container.RegisterType <IMessageOutboundRepository, MessageOutboundRepository>();
            context.Container.RegisterType <IMessageOutboundService, MessageOutboundService>();

            context.Plugin.BackgroundServices.Add(typeof(BackgroundServices.SendMessagesBackgroundService));

            context.EventAdd("CommentAdded", s => CommentAdded(context, s));
        }
Example #47
0
        /// <summary>
        /// Starts this plugin
        /// </summary>
        /// <param name="config">The configuration section for this plugin</param>
        /// <param name="context">The context for this plugin</param>
        /// <returns>False if no valid URL was given in the config, otherwise true</returns>
        public bool StartPlugin(dynamic config, IPluginContext context)
        {
            // No config, no dice...
            if (config == null || config.GetType() != typeof(ConfigObject))
            {
                Log("This plugin requires a ImdbAPIService config section with a url");
                return(false);
            }

            // Get the value from the config
            config.TryGetString("url", out _url);

            // OK if we now have a url
            var ok = _url != null;

            // Register components if ok
            if (ok)
            {
                PluginManager.Register((IComponent)this);
            }

            return(ok);
        }
        protected override void ExecuteCrmPlugin(IPluginContext <ins_salesorderline> context)
        {
            var messageName = context.PluginExecutionContext.MessageName;

            if (messageName == "Create" || messageName == "Update")
            {
                var target = context.Target;
                if (target.ContainsAny(e => e.ins_productid))
                {
                    new LoadProductData(context).Execute();
                }

                if (target.ContainsAny(e => e.ins_priceamount, e => e.ins_qty))
                {
                    new CalculateTotalPrice(context).Execute();
                }
            }

            if (messageName == "Delete")
            {
                new UpdateSalesOrder(context).Execute();
            }
        }
Example #49
0
        public string GetMarkup(Plugin plugin, ContextType context)
        {
            string markup = String.Empty;

            if (!plugin.IsNull)
            {
                //retrieve the appropriate plugin context
                IPluginContext pluginContext = GetContext(plugin, context);

                if (pluginContext != null)
                {
                    if (!String.IsNullOrEmpty(pluginContext.Markup.src))
                    {
                        //check to see if source can be found
                        string srcPath = Path.Combine(plugin.PluginPath, pluginContext.Markup.src);

                        if (File.Exists(srcPath))
                        {
                            markup = FileUtils.ReadFileToString(srcPath);
                        }
                    }

                    if (String.IsNullOrEmpty(markup))
                    {
                        //markup not found using the src attribute
                        //so use the Value instead
                        markup = pluginContext.Markup.Value;
                    }
                }
            }
            else
            {
                m_Logger.Error(string.Format("The plugin {0} ({1}) does not contain markup for a standard context", plugin.Name, plugin.RegistrationKey));
            }

            return(markup ?? string.Empty);
        }
        private Entity GetParentEntity(IPluginContext context, Entity entity, AutoNumberingRule rule)
        {
            if (!rule.IsParented())
            {
                return(null);
            }

            if (rule.ParentAttributeName.IsNullOrEmpty())
            {
                throw new InvalidPluginExecutionException("Invalid auto-numbering configuration. Missing parent attribute name.");
            }

            if (rule.LastNumberAttributeName.IsNullOrEmpty())
            {
                throw new InvalidPluginExecutionException("Invalid auto-numbering configuration. Missing last number attribute name.");
            }

            var parentReference = entity.GetAttributeValue <EntityReference>(rule.ParentAttributeName);

            if (parentReference == null)
            {
                throw new InvalidPluginExecutionException($"You must provide a value for '{rule.ParentAttributeName}'.");
            }

            var parentAttributes = rule.ParentAttributes
                                   .Union(new[] { rule.LastNumberAttributeName, rule.LastYearAttributeName, rule.LastDayAttributeName })
                                   .Where(o => !o.IsNullOrEmpty())
                                   .Distinct()
                                   .ToArray();

            var parent = context.OrganizationService.Retrieve(
                parentReference.LogicalName,
                parentReference.Id,
                parentAttributes);

            return(parent);
        }
Example #51
0
        private void PostSaved(IPluginContext context, object state)
        {
            //TODO: (erikpo) Move this decision out of the plugin itself and back into the plumbing
            if (context.Plugin.Enabled)
            {
                ITrackbackOutboundService trackbackOutboundService = context.Container.Resolve <ITrackbackOutboundService>();
                Post post = (Post)state;

                if (post.Published.HasValue)
                {
                    string postUrl = context.Container.Resolve <AbsolutePathHelper>().GetAbsolutePath(post);
                    IEnumerable <TrackbackOutbound> trackbacksToAdd    = extractTrackbacks(context, post, postUrl, post.Area.DisplayName);
                    IEnumerable <TrackbackOutbound> unsentTrackbacks   = trackbackOutboundService.GetUnsent(post.ID);
                    IEnumerable <TrackbackOutbound> trackbacksToRemove = trackbacksToAdd.Where(tb => !unsentTrackbacks.Contains(tb) && !tb.Sent.HasValue);

                    trackbackOutboundService.Remove(trackbacksToRemove);
                    trackbackOutboundService.Save(trackbacksToAdd);
                }
                else
                {
                    //TODO: (erikpo) Remove all outbound trackbacks
                }
            }
        }
Example #52
0
        private static IEnumerable <TrackbackOutbound> extractTrackbacks(IPluginContext context, Post post, string postUrl, string postAreaTitle)
        {
            //INFO: (erikpo) Trackback spec: http://www.sixapart.com/pronet/docs/trackback_spec
            Regex r =
                new Regex(
                    @"(?<HTML><a[^>]*href\s*=\s*[\""\']?(?<HRef>[^""'>\s]*)[\""\']?[^>]*>(?<Title>[^<]+|.*?)?</a>)",
                    RegexOptions.IgnoreCase | RegexOptions.Compiled
                    );
            MatchCollection          m          = r.Matches(post.Body);
            List <TrackbackOutbound> trackbacks = Enumerable.Empty <TrackbackOutbound>().ToList();

            if (m.Count > 0)
            {
                int retryCount = int.Parse(context.Plugin.Settings["RetryCount"]);

                trackbacks = new List <TrackbackOutbound>(m.Count);

                foreach (Match match in m)
                {
                    trackbacks.Add(
                        new TrackbackOutbound
                    {
                        TargetUrl           = match.Groups["HRef"].Value,
                        PostID              = post.ID,
                        PostTitle           = post.Title,
                        PostBody            = post.GetBodyShort(),
                        PostAreaTitle       = postAreaTitle,
                        PostUrl             = postUrl,
                        RemainingRetryCount = retryCount
                    }
                        );
                }
            }

            return(trackbacks);
        }
Example #53
0
        protected virtual void Validate(IPluginContext context, Type pluginType)
        {
            var attributes = new PluginAttributesCollection(pluginType);

            if (attributes.ExecutionModes.Any())
            {
                context.EnsureSupportedExecutionMode(attributes.ExecutionModes.ToArray());
            }

            if (attributes.PipelineStages.Any())
            {
                context.EnsureSupportedPipelineStage(attributes.PipelineStages.ToArray());
            }

            if (attributes.PipelineMessages.Any())
            {
                context.EnsureSupportedMessage(attributes.PipelineMessages.ToArray());
            }

            if (!String.IsNullOrWhiteSpace(attributes.PrimaryEntityLogicalName))
            {
                context.EnsureTargetLogicalName(attributes.PrimaryEntityLogicalName);
            }
        }
Example #54
0
        public void PerformAction(IPluginContext context, IReporter reporter)
        {
            string line;
            var    lineNumber = 0;

            var reader = new System.IO.StreamReader(System.IO.File.OpenRead(context.FilePath));

            while ((line = reader.ReadLine()) != null)
            {
                lineNumber++;
                var column = line.IndexOf("Identity", StringComparison.OrdinalIgnoreCase);

                if (column > -1)
                {
                    reporter.ReportViolation(new SampleRuleViolation(
                                                 context.FilePath,
                                                 "use-scope-identity",
                                                 line,
                                                 lineNumber,
                                                 column,
                                                 RuleViolationSeverity.Error));
                }
            }
        }
        public void Initialize(IPluginContext context)
        {
            if (initialized)
            {
                return;
            }

            initialized = true;

            AppDomain.CurrentDomain.AssemblyResolve += (s, args) =>
            {
                String resourceName = new AssemblyName(args.Name).Name + ".dll";
                var    test         = Assembly.GetExecutingAssembly().GetManifestResourceNames();
                string fullname     = Array.Find(Assembly.GetExecutingAssembly().GetManifestResourceNames(), (str) => { return(str.EndsWith(resourceName)); });
                if (fullname == null)
                {
                    return(null);
                }

                using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(test[0]))
                {
                    if (stream != null)
                    {
                        Byte[] assemblyData = new Byte[stream.Length];
                        stream.Read(assemblyData, 0, assemblyData.Length);
                        return(Assembly.Load(assemblyData));
                    }
                    else
                    {
                        return(null);
                    }
                }
            };

            this.context = context;
        }
        public AccountHandler([NotNull] IAccountCollection collection, [NotNull] ITpBus bus, [NotNull] IPluginContext context,
                              [NotNull] ILogManager logManager, [NotNull] IMsmqTransport msmqTransport)
        {
            if (collection == null)
            {
                throw new NullReferenceException("collection");
            }

            if (bus == null)
            {
                throw new ArgumentNullException("bus");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            _collection    = collection;
            _bus           = bus;
            _context       = context;
            _msmqTransport = msmqTransport;
            _log           = logManager.GetLogger(this.GetType());
        }
Example #57
0
        protected virtual void CreateLogEntryFromException(
            IPluginContext context,
            Exception exception,
            LogEntryType type = LogEntryType.Error)
        {
            var action = (Action)(() =>
            {
                var name = GetType().FullName;
                var trace = context.TracingService.ToString();

                var entry = LogEntry.CreateFromException(
                    exception,
                    name,
                    trace,
                    type: type,
                    prefix: _prefix);

                var repository = new LogEntryRepository(_prefix, context);

                repository.Create(entry);
            });

            action.Catch(ex => context.TracingService.Trace(ex.ToString()));
        }
Example #58
0
        public LinksIntegrationTests()
        {
            FileService   = Substitute.For <IFileService>();
            PluginContext = Substitute.For <IPluginContext>();
            PluginContext.Directory.Returns(PluginDirectory);

            FileService.Exists(ConfigurationPath).Returns(true);
            var configuration = JsonConvert.SerializeObject(new Configuration {
                LinksFilePath = LinksPath
            });

            FileService.ReadAllText(ConfigurationPath)
            .Returns(configuration);

            var builder = new ContainerBuilder();

            var pluginContext = Substitute.For <IPluginContext>();

            pluginContext.Directory.Returns(PluginDirectory);

            builder.RegisterModule(new AutofacModule(pluginContext));
            builder.RegisterInstance(FileService);
            _container = builder.Build();
        }
Example #59
0
 public void Start(IPluginContext <NormalConfig> context)
 {
     PluginLog.Add(Name + ".Start");
 }
Example #60
0
 public void Start(IPluginContext <ExceptionConfig> context)
 {
     PluginLog.Add(Name + ".Start");
     throw new IOException("Failure in plugin provider");
 }