Пример #1
0
        public virtual void Interprete(ChannelData <Tinput> input)
        {
            List <Message> output = InterpreteProcess(input);

            if (output != null && output.Count > 0)
            {
                Envelop e = new Envelop()
                {
                    OriginalMessage = input.RawData, Messages = output, Address = input.RemoteEndPoint.Address.ToString(), Port = input.RemoteEndPoint.Port, Timestamp = input.Timestamp
                };

                if (_notifyMessageCreated != null)
                {
                    try
                    {
                        _notifyMessageCreated(e);
                    }
                    catch (Exception ex)
                    {
                        _logWriter.Log("Invoke notifyMessageCreated action exception", ex);
                    }
                }
            }
            else
            {
                _logWriter.Log("No Message created");
            }
        }
        /// <summary>
        /// Called when a request comes into the proxy server
        /// </summary>
        /// <param name="requestInfo"></param>
        /// <returns></returns>
        public HttpResponseInfo SendRequest(HttpRequestInfo requestInfo)
        {
            int port;
            HttpResponseInfo respInfo = null;

            requestInfo.ParseVariables();

            if (String.Compare(START_PAGE, requestInfo.Path, true) == 0)
            {
                port = ExtractPort(requestInfo);
                _commandProxy.StartManualExploreProxy(port);
                respInfo = GetSuccessResponse(Resources.RecordingStarted);
            }
            else if (String.Compare(STOP_PAGE, requestInfo.Path, true) == 0)
            {
                port = ExtractPort(requestInfo);
                string fileName = null;
                if (requestInfo.QueryVariables.ContainsKey(FILE_PARAM))
                {
                    fileName = Utils.UrlDecode(requestInfo.QueryVariables[FILE_PARAM]);
                }
                _commandProxy.StopManualExploreProxy(port, fileName);
                respInfo = GetSuccessResponse(Resources.RecordingStopped);
            }
            else
            {
                _logWriter.Log(TraceLevel.Error, "An invalid url was specified: {0}", requestInfo.FullUrl);
                throw new HttpProxyException(HttpStatusCode.NotImplemented, "Not implemented", ServiceCode.CommandProxyNotImplemented);
            }

            return(respInfo);
        }
Пример #3
0
        /// <summary>
        /// Attempts to start a manual explore proxy on the specified port.
        /// </summary>
        /// <param name="port"></param>
        public void StartManualExploreProxy(int port)
        {
            //check if the maximum number of proxies was reached
            if (_manualExploreProxies.Count >= _maxProxies)
            {
                _logWriter.Log(TraceLevel.Error, "Maximum number of proxies ({0}) reached.", _maxProxies);
                throw new HttpProxyException(HttpStatusCode.ServiceUnavailable, "Maximum number of proxies reached", ServiceCode.CommandProxyMaxiumumProxiesReached);
            }

            ManualExploreProxy proxy;
            TrafficViewerFile  file = new TrafficViewerFile();

            file.Profile.SetExclusions(_exclusions);
            proxy = new ManualExploreProxy(Host, port, file, true);
            //set certificate policy
            if (_ignoreCertErrors)
            {
                proxy.NetworkSettings.CertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrs);
            }

            proxy.NetworkSettings.WebProxy = WebRequest.GetSystemWebProxy();

            proxy.Start();

            _manualExploreProxies.Add(port, proxy);
        }
Пример #4
0
        public async Task <IEnumerable <MessageView> > GetMessagesFromTextChannelAsync(ulong guildId, ulong channelId)
        {
            if (guildId == 0)
            {
                return(new MessageView[0]);
            }

            var guild       = _discord.Client.GetGuild(guildId);
            var textChannel = guild.Channels
                              .Where(c => c.Id == channelId && IsViewableTextChannel(c))
                              .Cast <SocketTextChannel>()
                              .FirstOrDefault();

            if (textChannel == null)
            {
                return(new MessageView[0]);
            }

            var result = new List <MessageView>();

            try
            {
                result.AddRange(await GetMessagesFrom(textChannel));
            }
            catch (Exception ex)
            {
                _logger.Log($"Miunie cannot read from the '{textChannel.Name}' channel. {ex.Message}");
            }

            return(result);
        }
Пример #5
0
        private void Write(string message, string configTraceLevel, BaseException exception = null)
        {
            var contxt = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("appContext");

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            }))
            {
                LogEntity entity = new LogEntity();
                try
                {
                    entity.ActivityId = "abc";
                    entity.Message    = message;
                    entity.StackTrace = exception.StackTrace;
                    entity.TraceLevel = configTraceLevel;
                    entity.UserName   = WindowsIdentity.GetCurrent().Name;
                    if (_logWriter != null)
                    {
                        _logWriter.Log(entity);
                    }
                }
                catch (Exception ex) {
                    _eventWriter.WriteToEventLog(entity, ex);
                }
            }
        }
Пример #6
0
        public async Task GiveReputationAsync(MiunieUser invoker, MiunieUser target, MiunieChannel c)
        {
            if (invoker.UserId == target.UserId)
            {
                await _discordMessages.SendMessageAsync(c, PhraseKey.CANNOT_SELF_REP, invoker.Name);

                return;
            }

            if (_reputationProvider.CanAddReputation(invoker, target))
            {
                _logger.Log($"User '{invoker.Name}' has a reputation timeout for User '{target.Name}', ignoring...");
                return;
            }

            _reputationProvider.AddReputation(invoker, target);

            if (_miunieDiscord.UserIsMiunie(target))
            {
                await _discordMessages.SendMessageAsync(c, PhraseKey.REPUTATION_GIVEN_BOT, invoker.Name);

                return;
            }

            await _discordMessages.SendMessageAsync(c, PhraseKey.REPUTATION_GIVEN, target.Name, invoker.Name);
        }
Пример #7
0
        public async Task <IEnumerable <TextChannelView> > GetAvailableTextChannelsAsync(ulong guildId)
        {
            var guild = await _discord.Client.GetGuildAsync(guildId);

            var textChannels = guild.Channels.Where(c => c.Type == ChannelType.Text);
            var result       = new List <TextChannelView>();

            foreach (var channel in textChannels)
            {
                try
                {
                    result.Add(new TextChannelView
                    {
                        Id       = channel.Id,
                        Name     = $"# {channel.Name}",
                        Messages = await GetMessagesFrom(channel)
                    });
                }
                catch (Exception)
                {
                    _logger.Log($"Miunie cannot read from the '{channel.Name}' channel.");
                }
            }

            return(result);
        }
Пример #8
0
 public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage request,
                                       ILogger log,
                                       [Inject] ILogWriter writer)
 {
     log.LogInformation("C# HTTP trigger function processed a request.");
     writer.Log();
     return(request.CreateResponse(HttpStatusCode.OK, "Autofac managed to inject a ILogger<>"));
 }
Пример #9
0
        private async Task TryRunAsBotCommand(SocketCommandContext context, int argPos)
        {
            var result = await _commandService.ExecuteAsync(context, argPos, _services);

            if (!result.IsSuccess)
            {
                _logger.Log($"Command execution failed. Reason: {result.ErrorReason}.");
            }
        }
Пример #10
0
 /// <summary>
 /// sync
 /// </summary>
 /// <param name="message"></param>
 public void InvokeMessageHandler(Envelop envelop)
 {
     if (_messageHandler != null)
     {
         _messageHandler(envelop);
     }
     else
     {
         _logWriter.Log("Envelop created, but there is no MessageHandler");
     }
 }
Пример #11
0
 internal void Log(object sender, DebugLogMessageEventArgs e)
 {
     if (e.Level == LogLevel.Critical)
     {
         _logger.LogError(e.Message);
     }
     else
     {
         _logger.Log(e.Message);
     }
 }
Пример #12
0
 public void Execute(IPEndPoint endPoint)
 {
     try
     {
         ChannelData <T> channelData = new ChannelData <T>(GetData(), endPoint, DateTime.Now);
         _channel.SendData(channelData);
     }
     catch (Exception ex)
     {
         _logWriter.Log(this.GetType().Name + " Execute function exception.", ex);
     }
 }
Пример #13
0
        private static IODataClient GetNewODataClient(Uri targetInstance, CodeActivityContext context, IWorkflowContext workflowContext, ILogWriter logWriter)
        {
            var passwordGrantRequest = GetPasswordGrantRequest(workflowContext, logWriter);

            passwordGrantRequest.Resource = targetInstance;

            logWriter.Log(Severity.Info, Tag, $"Making password grant OAuth request for {passwordGrantRequest.Resource} as {passwordGrantRequest.Username}");

            var token = (context.GetExtension <IOAuthTokenRepository>() ?? new OAuthTokenRepository()).GetAccessToken(passwordGrantRequest).Result;

            return(new ODataClient(targetInstance, token));
        }
        private static IODataClient GetNewODataClient(Uri targetInstance, CodeActivityContext context, IWorkflowContext workflowContext, ILogWriter logWriter)
        {
            var oAuthGrantRequest = GetOAuthGrantRequest(workflowContext, logWriter);

            oAuthGrantRequest.Resource = targetInstance;

            logWriter.Log(Severity.Info, Tag, $"Making client credentials grant OAuth request for {oAuthGrantRequest.Resource}.");

            var token = (context.GetExtension <IOAuthTokenRepository>() ?? new OAuthTokenRepository()).GetAccessToken(oAuthGrantRequest).Result;

            return(new ODataClient(targetInstance, token));
        }
Пример #15
0
        protected override void WriteLog(
            Severity severity,
            string message,
            IDictionary <string, object> data,
            Exception ex)
        {
            var mute = _muteFilter(severity, message, data, ex);

            if (!mute)
            {
                _logWriter.Log(severity, message, data, ex);
            }
        }
Пример #16
0
        /// <inheritdoc/>
        protected override void ExecuteWorkflowActivity(CodeActivityContext context, IWorkflowContext workflowContext, IODataClient oDataClient, ILogWriter logWriter, IRepositoryFactory repoFactory)
        {
            var solutionUniqueName   = this.SolutionUniqueName.GetRequired(context, nameof(this.SolutionUniqueName));
            var isManaged            = this.IsManaged.Get(context);
            var oDataSolutionService = context.GetExtension <IODataSolutionService>() ?? new ODataSolutionService(new ODataRepositoryFactory(oDataClient), logWriter);

            var solutionZip = oDataSolutionService.GetSolutionZipAsync(solutionUniqueName, isManaged).Result;

            logWriter.Log(Severity.Info, nameof(GetSolutionZipFromInstance), solutionZip);

            this.SolutionZip.Set(context, solutionZip);
            this.IsSuccessful.Set(context, true);
        }
Пример #17
0
        internal Task Log(LogMessage evt)
        {
            if (evt.Severity == LogSeverity.Critical)
            {
                _logger.LogError(evt.Message);
            }
            else
            {
                _logger.Log(evt.Message);
            }

            return(Task.CompletedTask);
        }
Пример #18
0
 public virtual void ExecuteCommand(IPEndPoint endPoint)
 {
     foreach (ICommand command in _commandList)
     {
         try
         {
             command.Execute(endPoint);
         }
         catch (Exception ex)
         {
             _logWriter.Log(this.GetType().Name + " ExecuteCommand function exception.", ex);
         }
     }
 }
Пример #19
0
        /// <inheritdoc/>
        protected override void ExecuteWorkflowActivity(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService orgSvc, ILogWriter logWriter, IRepositoryFactory repoFactory)
        {
            var documentBody = this.Attachment.GetRequired(context, nameof(this.Attachment));

            logWriter.Log(Severity.Info, nameof(AttachFileToNote), $"{documentBody}");
            repoFactory.GetRepository <DevelopContext, Annotation>().Update(new Annotation
            {
                FileName     = this.FileName.GetRequired(context, nameof(this.FileName)),
                DocumentBody = this.Attachment.GetRequired(context, nameof(this.Attachment)),
                IsDocument   = true,
                MimeType     = this.MimeType.Get(context),
                Id           = this.Note.GetRequired(context, nameof(this.Note)).Id,
            });
        }
Пример #20
0
        public override Task ProcessAsync(CommandProcessorInput input)
        {
            var commands = _serviceCollection.GetAvailableCommands();

            if (commands is null || !commands.Any())
            {
                _logWriter.Log("Service Location did not get any available commands.");
                return(Task.CompletedTask);
            }

            var prompt = input.Message.Substring((int)input.PrefixOffset).Trim();

            input.TargetedCommands = commands.Where(c => prompt.StartsWith(c.Prompt));
            return(NextStep.ProcessAsync(input));
        }
Пример #21
0
        private static OAuthPasswordGrantRequest GetPasswordGrantRequest(IWorkflowContext workflowContext, ILogWriter logWriter)
        {
            if (!workflowContext.SharedVariables.ContainsKey(SharedVariablesSecureConfigKey))
            {
                throw new InvalidPluginExecutionException($"Secure configuration not found. Please inject an {nameof(OAuthPasswordGrantRequest)} object with shared variables key '{SharedVariablesSecureConfigKey}'.");
            }

            var secureConfig = (string)workflowContext.SharedVariables[SharedVariablesSecureConfigKey];

            logWriter.Log(Severity.Info, Tag, $"Deserializing password grant request from secure configuration.");

            OAuthPasswordGrantRequest passwordGrantRequest;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(secureConfig)))
            {
                passwordGrantRequest = (OAuthPasswordGrantRequest) new DataContractJsonSerializer(typeof(OAuthPasswordGrantRequest)).ReadObject(ms);
            }

            return(passwordGrantRequest);
        }
Пример #22
0
        /// <summary>
        ///  Allows users to start Manual Explore proxies remotely
        /// </summary>
        /// <param name="host">The host to listen to</param>
        /// <param name="port">The port to listen to</param>
        /// <param name="filesDirectory">This is the directory where Manual Explore files will be saved</param>
        /// <param name="maxProxies">The maximum number of manual explore proxies</param>
        /// <param name="ignoreCertErrors">Whether to ignore invalid certificates</param>
        /// <param name="recordingType">The type of the recording output</param>
        /// <param name="exclusions">The default file exclusions to use for the recorders</param>
        public CommandProxy(string host, int port, string filesDirectory, int maxProxies, bool ignoreCertErrors, string recordingType, params string [] exclusions) : base(host, port, 0)
        {
            _filesDirectory       = Path.GetFullPath(filesDirectory);
            _maxProxies           = maxProxies;
            _manualExploreProxies = new Dictionary <int, ManualExploreProxy>();
            _logWriter            = TrafficViewerSDK.SdkSettings.Instance.Logger;
            _ignoreCertErrors     = ignoreCertErrors;
            _exclusions           = exclusions;
            _recordingType        = recordingType;
            StringBuilder exclusionsString = new StringBuilder();

            foreach (string exclusion in exclusions)
            {
                exclusionsString.Append("\r\n\t");
                exclusionsString.Append(exclusion);
            }
            string message = String.Format(Resources.ManualExploreServerStarting, host, port, filesDirectory, maxProxies, ignoreCertErrors, exclusionsString);

            _logWriter.Log(TraceLevel.Info, message);
            HttpServerConsole.Instance.WriteLine(LogMessageType.Information, message);
        }
Пример #23
0
        public virtual bool Process(IFormatter <T> formatter, T input)
        {
            bool result = false;

            try
            {
                if (!IsMatch(formatter, input))
                {
                    if (!IsBreak)
                    {
                        if (_filters.Count > 0)
                        {
                            foreach (IFormatterFilter <T> filter in _filters)
                            {
                                bool subResult = filter.Process(formatter, input);
                                if (subResult)
                                {
                                    result = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                _logWriter.Log("", ex);
            }

            return(result);
        }
Пример #24
0
        public void LogWarning(string message)
        {
            ILogWriter writer = LogWriterfactory.GetLogWriter(LoggerType.EnterpriseLogWriter);

            writer.Log(message);
        }
Пример #25
0
 public static void Log(this ILogWriter logWriter, string message, string appName, LoggingEventType eventType)
 {
     logWriter.Log(new LogEntry(eventType, message, appName));
 }
Пример #26
0
 public static void LogInformation(this ILogWriter logWriter, string message, string appName)
 {
     logWriter.Log(new LogEntry(LoggingEventType.Information, message, appName));
 }
Пример #27
0
 public static void LogError(this ILogWriter logWriter, string appName, Exception exception)
 {
     logWriter.Log(new LogEntry(LoggingEventType.Error, exception.Message, appName, exception));
 }