Exemplo n.º 1
0
        public ActionResult Login(LoginPageModel model) //TODO: Move all of this to a UserService class
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            //We want to wait a specified amount of time for the response regardless of the results, to avoid
            //Exposing any information to the client
            StaticLogger.Log($"{model.Login}: Login attempt", StaticLogger.LoggingLevel.Call);
            DateTime startLogin = DateTime.Now;

            void WaitForRedirect()
            {
                const double LoginTime = 3000;

                double toWait = LoginTime - (DateTime.Now - startLogin).TotalMilliseconds;

                StaticLogger.Log($"{model.Login}: Waiting for {toWait}", StaticLogger.LoggingLevel.Call);
                if (toWait > 0)
                {
                    System.Threading.Thread.Sleep((int)toWait);
                }
            }

            StaticLogger.Log($"{model.Login}: Calling user service...", StaticLogger.LoggingLevel.Call);
            User?user = this.UserService.Login(model.Login, model.Password);

            if (user != null)
            {
                StaticLogger.Log($"{model.Login}: User not null", StaticLogger.LoggingLevel.Call);
                if (this.ConfigurationService.GetBool(ConfigurationNames.REQUIRE_EMAIL_VALIDATION))
                {
                    if (!this.EmailValidationRepository.IsValidated(user))
                    {
                        return(this.RedirectToAction(nameof(EmailValidationRequired), new { Id = user.Guid.ToString(), area = "" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(model.ReturnUrl) && model.ReturnUrl != this.Request.Path.Value)
                {
                    WaitForRedirect();
                    StaticLogger.Log($"{model.Login}: Returning to {model.ReturnUrl}", StaticLogger.LoggingLevel.Call);
                    return(this.Redirect(model.ReturnUrl));
                }
                else
                {
                    WaitForRedirect();
                    StaticLogger.Log($"{model.Login}: Returning Home", StaticLogger.LoggingLevel.Call);
                    return(this.Redirect("/Home/Index"));
                }
            }
            else
            {
                StaticLogger.Log($"{model.Login}: User is null", StaticLogger.LoggingLevel.Call);
                this.ModelState.AddModelError(string.Empty, "Invalid Login or Password" + System.Environment.NewLine);
                WaitForRedirect();
                return(this.View(model));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Searches All currently loaded assemblies for types with the IMessageHandler interface, and
        /// subscribes all methods beneath them
        /// </summary>
        public static void SubscribeAll()
        {
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (SubscribedAssemblies.Contains(a))
                {
                    continue;
                }
                else
                {
                    SubscribedAssemblies.Add(a);
                }

                try
                {
                    foreach (Type t in a.GetTypes())
                    {
                        if (typeof(IMessageHandler).IsAssignableFrom(t))
                        {
                            MessageBus.Subscribe(t);
                        }
                    }
                }
                catch (Exception ex)
                {
                    StaticLogger.Log(ex.Message, StaticLogger.LoggingLevel.Call);
                    StaticLogger.Log(ex.StackTrace, StaticLogger.LoggingLevel.Call);
                }
            }
        }
Exemplo n.º 3
0
        protected override void OnStart(string[] args)
        {
            Fwk.Logging.Event ev = null;
            //ConfigurationsHelper.HostApplicationName = string.Concat("Fwk remoting ", this.ServiceName);
            try
            {
                RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, false);
                ev              = new Event();
                ev.LogType      = EventType.Information;
                ev.Machine      = Environment.MachineName;
                ev.User         = Environment.UserName;
                ev.Message.Text = "Servicio de host de Remoting iniciado.";
            }
            catch (Exception ex)
            {
                //RemotingHelper.WriteLog("\r\nSe produjo una excepción al iniciar el servicio." +
                //    "\r\n\r\n" + ex.ToString(),
                //    EventLogEntryType.Error);
                ev              = new Event();
                ev.LogType      = EventType.Error;
                ev.Machine      = Environment.MachineName;
                ev.User         = Environment.UserName;
                ev.Message.Text = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex);
            }
            //RemotingHelper.WriteLog("Servicio de host de Remoting iniciado.", EventLogEntryType.Information);

            StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
        }
Exemplo n.º 4
0
        public void StoreOnDisk(IFile df)
        {
            try
            {
                if (df != null && df.Data != null && df.Data.Length > 0)
                {
                    byte[] toStore = df.Data;
                    df.Data = Array.Empty <byte>();

                    FileInfo fileInfo = new FileInfo(df.FullName);

                    if (string.IsNullOrWhiteSpace(df.FullName))
                    {
                        string RawPath = this.GetUserFilesRoot();

                        df.FullName = Path.Combine(RawPath, Guid.NewGuid().ToString().Replace("-", ""));
                    }

                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }

                    File.WriteAllBytes(df.FullName, toStore);
                }
            }
            catch (Exception ex)
            {
                StaticLogger.Log($"Failed to persist file data to disk {df?.FullName}: ", StaticLogger.LoggingLevel.Call);
                StaticLogger.Log(ex.Message, StaticLogger.LoggingLevel.Call);
            }
        }
Exemplo n.º 5
0
        private static IEnumerable <Assembly> GetDependentAssemblies(Assembly a, HashSet <Assembly> checkedAssemblies, string Prefix = "")
        {
            yield return(a);

            if (AssembliesThatReference.TryGetValue(a.GetName().Name, out List <Assembly> referencedBy))
            {
                foreach (Assembly ai in referencedBy)
                {
                    if (checkedAssemblies.Contains(ai))
                    {
                        continue;
                    }

                    checkedAssemblies.Add(ai);

                    foreach (Assembly aii in GetDependentAssemblies(ai, checkedAssemblies, "----" + Prefix))
                    {
                        if (StaticLogger.IsListening)
                        {
                            StaticLogger.Log($"{Prefix} Dependency {aii.GetName().Name}", StaticLogger.LoggingLevel.Call);
                        }

                        yield return(aii);
                    }
                }
            }
        }
Exemplo n.º 6
0
        public static List <Dictionary <string, object> > Execute(this MySqlConnection connection, string sqlCmd, int start, int limit)
        {
            Stack <Dictionary <string, object> > output = new Stack <Dictionary <string, object> >();
            MySqlDataReader reader = null;

            try
            {
                MySqlCommand cmd = new MySqlCommand(sqlCmd, connection);
                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    Dictionary <string, object> entry = new Dictionary <string, object>();
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        entry[reader.GetDataTypeName(i)] = reader.GetValue(i);
                    }
                    output.Push(entry);
                }
            }
            catch (MySqlException ex)
            {
                StaticLogger.Log(LogLevel.Error, "FAILED MySQL READ : " + ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(output.ToList());
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            ConfigurationsHelper.HostApplicationName = string.Concat("Fwk remoting ", Fwk.Bases.ConfigurationsHelper.HostApplicationName);
            RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, false);

            //RemotingHelper.WriteLog("Servicio de host de Remoting iniciado.", EventLogEntryType.Information);
            Fwk.Logging.Event ev = new Event();
            ev.LogType = EventType.Information;
            ev.Machine = Environment.MachineName;
            ev.User    = Environment.UserName;
            WellKnownClientTypeEntry[] myEntries = RemotingConfiguration.GetRegisteredWellKnownClientTypes();

            ev.Message.Text = "Servicio de Remoting consola iniciado.";

            StringBuilder str = new StringBuilder();

            str.AppendLine(Fwk.Bases.ConfigurationsHelper.HostApplicationName);
            str.AppendLine(ev.Message.Text);

            Console.WriteLine(str.ToString());
            try
            {
                StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
            }
            catch
            { }
            Console.ReadLine();
        }
Exemplo n.º 8
0
        public async Task Main()
        {
            int entry = Convert.ToInt32(Console.ReadLine());

            while (entry != 0)
            {
                switch (entry)
                {
                case 1:
                    FileNotFoundException ex = new FileNotFoundException("synchrone avec exception", new FileLoadException());
                    StaticLogger.Log(ex);
                    StaticLogger.Log("Synchrone avec message");
                    StaticLogger.Log <FormatException>("synchrone avec typage");
                    break;

                case 2:
                    FileNotFoundException asyncEx = new FileNotFoundException("asynchrone avec exception", new FileLoadException());
                    await StaticLogger.LogAsync(asyncEx);

                    await StaticLogger.LogAsync("aSynchrone avec message");

                    await StaticLogger.LogAsync <FormatException>("asynchrone avec typage");

                    break;
                }

                entry = Convert.ToInt32(Console.ReadLine());
            }
        }
Exemplo n.º 9
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         m_Watch.Stop();
         StaticLogger.Log(m_Level, string.Format("[Timing] {0} in {1}ms", m_Message, m_Watch.ElapsedMilliseconds));
     }
 }
        /// <summary>
        /// Registers the dependencies
        /// </summary>
        public void RegisterDependencies(IServiceRegister serviceRegister)
        {
            if (serviceRegister is null)
            {
                throw new ArgumentNullException(nameof(serviceRegister));
            }

            StaticLogger.Log($"Penguin.Persistence.DependencyInjection: {Assembly.GetExecutingAssembly().GetName().Version}", StaticLogger.LoggingLevel.Call);

            //if (!DependencyEngine.IsRegistered<PersistenceConnectionInfo>())
            //{
            //Wonky ass logic to support old EF connection strings from web.config.
            //Most of this can be removed when CE isn't needed.
            serviceRegister.Register((IServiceProvider ServiceProvider) =>
            {
                if (!(ServiceProvider.GetService(typeof(IProvideConfigurations)) is IProvideConfigurations Configuration))
                {
                    throw new NullReferenceException("IProvideConfigurations must be registered before building database connection");
                }

                string ConnectionString = Configuration.GetConnectionString("DefaultConnectionString");

                if (ConnectionString is null)
                {
                    string error = $"Can not find connection string {Strings.CONNECTION_STRING_NAME} in registered configuration provider";

                    try
                    {
                        throw new DatabaseNotConfiguredException(error,
                                                                 new MissingConfigurationException(Strings.CONNECTION_STRING_NAME, error
                                                                                                   ));
                    }     //Notify dev if possible
                    catch (Exception)
                    {
                        return(new PersistenceConnectionInfo("", ""));
                    }
                }

                string Provider = "System.Data.SqlClient";

                if (ConnectionString.StartsWith("name="))
                {
                    ConnectionString = ConnectionString.Replace("name=", "");
                    ConnectionString = Configuration.GetConnectionString(ConnectionString);
                }

                PersistenceConnectionInfo connectionInfo = new PersistenceConnectionInfo(ConnectionString, Provider);

                if (connectionInfo.ProviderType == ProviderType.SQLCE)
                {
                    connectionInfo.ProviderName = "System.Data.SqlServerCe.4.0";
                }

                return(connectionInfo);
            }, ServiceLifetime.Singleton);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Gets a list of all types derived from the current type
        /// </summary>
        /// <param name="t">The root type to check for</param>
        /// <returns>All of the derived types</returns>
        public static IEnumerable <Type> GetDerivedTypes(Type t)
        {
            if (t is null)
            {
                throw new ArgumentNullException(nameof(t));
            }

            if (t.IsInterface)
            {
                throw new ArgumentException($"Type to check for can not be interface as this method uses 'IsSubclassOf'. To search for interfaces use {nameof(GetAllImplementations)}");
            }

            if (DerivedTypes.ContainsKey(t))
            {
                StaticLogger.Log($"RE: Using cached derived types for {FriendlyTypeName(t)}", StaticLogger.LoggingLevel.Method);
                foreach (Type toReturn in DerivedTypes[t])
                {
                    yield return(toReturn);
                }
            }
            else
            {
                StaticLogger.Log($"RE: Searching for derived types for {FriendlyTypeName(t)}", StaticLogger.LoggingLevel.Call);

                List <Type> typesToReturn = new List <Type>();

                foreach (Type type in GetDependentAssemblies(t).GetAllTypes())
                {
                    if (type.IsSubclassOf(t) && type.Module.ScopeName != "EntityProxyModule")
                    {
                        if (StaticLogger.Level != StaticLogger.LoggingLevel.None)
                        {
                            StaticLogger.Log($"RE: --{t.Name} :: {FriendlyTypeName(type)}", StaticLogger.LoggingLevel.Call);
                        }

                        typesToReturn.Add(type);
                    }
                    else
                    {
                        if (StaticLogger.Level != StaticLogger.LoggingLevel.None)
                        {
                            StaticLogger.Log($"RE: --{t.Name} !: {FriendlyTypeName(type)}", StaticLogger.LoggingLevel.Call);
                        }
                    }
                }

                DerivedTypes.TryAdd(t, typesToReturn.ToList());

                StaticLogger.Log("RE: Finished type search", StaticLogger.LoggingLevel.Method);

                foreach (Type toReturn in typesToReturn)
                {
                    yield return(toReturn);
                }
            }
        }
Exemplo n.º 12
0
        protected override void OnStop()
        {
            fwkServiceHost.Faulted -= new EventHandler(fwkServiceHost_Faulted);
            fwkServiceHost.Close();

            Fwk.Logging.Event ev = new Event();
            ev.LogType      = EventType.Information;
            ev.Machine      = Environment.MachineName;
            ev.User         = Environment.UserName;
            ev.Message.Text = string.Concat("Servicio de host (", base.ServiceName, ")  detenido");
            StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
        }
Exemplo n.º 13
0
        public void Should_log()
        {
            StaticLogger logger = new StaticLogger();
            Log          log    = new Log(LogLevel.Debug, "log example");

            logger.Log(log);

            var logged = logger.GetLogs()[0];

            Assert.AreSame(log, logged);
            Assert.AreEqual(LogLevel.Debug, logged.Level);
        }
        private static void RegisterInterfaces(IServiceRegister serviceRegister, Type RepositoryType)
        {
            foreach (Type i in RepositoryType.GetInterfaces())
            {
                if (i.IsGenericType && i.IsAssignableFrom(RepositoryType))
                {
                    StaticLogger.Log($"PPDI: Registering repository for {i} => {RepositoryType}", StaticLogger.LoggingLevel.Call);

                    serviceRegister.Register(i, RepositoryType, ServiceLifetime.Transient);
                }
            }
        }
Exemplo n.º 15
0
        protected override void OnStop()
        {
            fwkServiceHost.Faulted -= new EventHandler(fwkServiceHost_Faulted);
            fwkServiceHost.Close();

            Fwk.Logging.Event ev = new Event();
            ev.LogType      = EventType.Information;
            ev.Machine      = Environment.MachineName;
            ev.User         = Environment.UserName;
            ev.Message.Text = string.Concat("Servicio de host de WCF ", Fwk.Bases.ConfigurationsHelper.HostApplicationName, " iniciado");
            StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
        }
Exemplo n.º 16
0
        protected override void OnStart(string[] args)
        {
            fwkServiceHost          = new ServiceHost(typeof(FwkService));
            fwkServiceHost.Faulted += new EventHandler(fwkServiceHost_Faulted);
            fwkServiceHost.Open();

            Fwk.Logging.Event ev = new Event();
            ev.LogType      = EventType.Information;
            ev.Machine      = Environment.MachineName;
            ev.User         = Environment.UserName;
            ev.Message.Text = string.Concat("Servicio de host (", base.ServiceName, ") iniciado");
            StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
        }
Exemplo n.º 17
0
 protected override void OnStop()
 {
     foreach (IChannel wChannel in ChannelServices.RegisteredChannels)
     {
         ChannelServices.UnregisterChannel(wChannel);
     }
     Fwk.Logging.Event ev = new Event();
     ev.LogType      = EventType.Information;
     ev.Machine      = Environment.MachineName;
     ev.User         = Environment.UserName;
     ev.Message.Text = "Servicio de host de Remoting detenido.";
     StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
 }
Exemplo n.º 18
0
        protected override void OnStart(string[] args)
        {
            ConfigurationsHelper.HostApplicationNname = string.Concat("Fwk remoting ", this.ServiceName);
            RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, false);

            //RemotingHelper.WriteLog("Servicio de host de Remoting iniciado.", EventLogEntryType.Information);
            Fwk.Logging.Event ev = new Event();
            ev.LogType      = EventType.Information;
            ev.Machine      = Environment.MachineName;
            ev.User         = Environment.UserName;
            ev.Message.Text = "Servicio de host de Remoting iniciado.";
            StaticLogger.Log(TargetType.WindowsEvent, ev, null, null);
        }
 private static bool TestDomainCredentials(string UserName, string Password)
 {
     try
     {
         using PrincipalContext context = new PrincipalContext(ContextType.Domain);
         return(context.ValidateCredentials(UserName, Password));
     }
     catch (Exception ex)
     {
         StaticLogger.Log(ex.Message, StaticLogger.LoggingLevel.Call);
         StaticLogger.Log(ex.StackTrace, StaticLogger.LoggingLevel.Call);
         return(false);
     }
 }
Exemplo n.º 20
0
        private void CreateTaskbarIcon()
        {
            StaticLogger.Log("Creating taskbar icon...");

            var tbi = new TaskbarIcon();

            using (var iconStream = GetResourceStream(new Uri("pack://application:,,,/TrayIcon.ico")).Stream)
            {
                tbi.Icon = new Icon(iconStream);
            }
            tbi.ToolTipText = "Sync.Net";

            tbi.DoubleClickCommand = new RelayCommand(p => true, p => ShowMainWindow());
        }
Exemplo n.º 21
0
        public SavegameFeatureModel(
            Savegame <SavegameContent> savegame,
            ISavegameService savegameService)
        {
            var savegameJson = JsonConvert.SerializeObject(savegame, Formatting.Indented);

            var sb = new StringBuilder()
                     .AppendLine("CURRENT SAVEGAME:")
                     .AppendLine($"{savegameJson}");

            StaticLogger.Log(sb.ToString());

            savegameService.Save();
        }
Exemplo n.º 22
0
        internal static void LogError(Exception ex)
        {
            if (Convert.ToBoolean(Poisoned.WcfService.Properties.Settings.Default.PerformLog))
            {
                Event ev = new Event();
                ev.AppId        = Poisoned.WcfService.Properties.Resource.Title;
                ev.LogType      = EventType.Error;
                ev.Message.Text = ExceptionHelper.GetAllMessageException(ex);
                ev.Source       = Poisoned.WcfService.Properties.Resource.Title;


                StaticLogger.Log(Fwk.Logging.Targets.TargetType.File, ev, "Error.xml", string.Empty);
            }
        }
        private static bool TestOWACredentials(string UserName, string Password)
        {
            try
            {
                OWAValidator auth = new OWAValidator();

                return(auth.Validate(UserName, Password));
            }
            catch (Exception ex)
            {
                StaticLogger.Log(ex.Message, StaticLogger.LoggingLevel.Call);
                StaticLogger.Log(ex.StackTrace, StaticLogger.LoggingLevel.Call);
                return(false);
            }
        }
Exemplo n.º 24
0
        public static MySqlConnection CreateConnection(string connectionString)
        {
            MySqlConnection connection = null;

            try
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();
            }
            catch (MySqlException ex)
            {
                StaticLogger.Log(LogLevel.Error, "FAILED MySQL CONNECTION : " + ex.Message);
            }

            return(connection);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Muestra el mensage
        /// </summary>
        /// <param name="pMessage">Mensage a mostrar</param>
        /// <returns>DialogResult</returns>
        public DialogResult Show(String pSource, String pMessage, String pDetail, bool pLogError)
        {
            _FwkMessageView.Source  = pSource;
            _FwkMessageView.Message = pMessage;
            _FwkMessageView.Detail  = pDetail;
            _FwkMessageView.ShowDialog();


            if (pLogError)
            {
                Event wEvent = new Event(EventType.Error, Fwk.Bases.ConfigurationsHelper.HostApplicationName, _FwkMessageView.Detail);
                wEvent.AppId  = Fwk.Bases.ConfigurationsHelper.HostApplicationName;
                wEvent.Source = Fwk.Bases.ConfigurationsHelper.HostApplicationName;
                StaticLogger.Log(wEvent);
            }
            return(_FwkMessageView.DialogResult);
        }
Exemplo n.º 26
0
        public void PostConfigure(string name, StaticFileOptions options)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            // Basic initialization in case the options weren't initialized by any other component
            options.ContentTypeProvider ??= new FileExtensionContentTypeProvider();

            if (options.FileProvider == null && this._environment.WebRootFileProvider == null)
            {
                throw new InvalidOperationException("Missing FileProvider.");
            }

            options.FileProvider ??= this._environment.WebRootFileProvider;

            List <IFileProvider> providers = new List <IFileProvider>()
            {
                options.FileProvider
            };

            List <Assembly> allAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

            foreach (Assembly a in allAssemblies)
            {
                Type t = typeof(Microsoft.Extensions.FileProviders.Embedded.EmbeddedResourceFileInfo);
                StaticLogger.Log(t.FullName);

                try
                {
                    if (!a.IsDynamic)
                    {
                        if (a.GetManifestResourceStream("Microsoft.Extensions.FileProviders.Embedded.Manifest.xml") != null)
                        {
                            providers.Add(new ManifestEmbeddedFileProvider(a, "wwwroot"));
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            FileProvider         = new CompositeFileProvider(providers);
            options.FileProvider = FileProvider;
        }
    private static void FillTree()
    {
        DateTime start   = DateTime.Now;
        var      results = new List <Process>();
        // query the management system objects for any process that has the current
        // process listed as it's parentprocessid
        string queryText = string.Format("select processid, parentprocessid from win32_process");

        using (var searcher = new ManagementObjectSearcher(queryText))
        {
            foreach (var obj in searcher.Get())
            {
                object pidObj       = obj.Properties["processid"].Value;
                object parentPidObj = obj.Properties["parentprocessid"].Value;
                if (pidObj != null)
                {
                    int pid = Convert.ToInt32(pidObj);
                    if (!processes.ContainsKey(pid))
                    {
                        processes.Add(pid, new ProcessTreeNode(pid));
                    }
                    ProcessTreeNode currentNode = processes[pid];
                    if (parentPidObj != null)
                    {
                        currentNode.Parent = Convert.ToInt32(parentPidObj);
                    }
                }
            }
        }
        DateTime num1 = DateTime.Now;

        foreach (ProcessTreeNode node in processes.Values)
        {
            if (node.Parent != 0 && processes.ContainsKey(node.Parent))
            {
                processes[node.Parent].Children.Add(node.Pid);
            }
        }
        timeFilled = DateTime.Now;
        StaticLogger.Log(string.Format("ProcessTree.FillTree() completed in {0} seconds. 1={1}  2={2}",
                                       (timeFilled - start).TotalSeconds,
                                       (num1 - start).TotalSeconds,
                                       (timeFilled - num1).TotalSeconds));
    }
Exemplo n.º 28
0
        internal static void AddRegistration(Registration dr)
        {
            if (StaticLogger.Level != StaticLogger.LoggingLevel.None)
            {
                StaticLogger.Log($"DI: Registering {dr.RegisteredType.FullName} => { dr.ToInstantiate.FullName} ({dr.ServiceProvider.Name})", StaticLogger.LoggingLevel.Call);
            }

            if (!Registrations.TryGetValue(dr.RegisteredType, out ConcurrentList <Registration> registrations))
            {
                registrations = new ConcurrentList <Registration>();
                Registrations.TryAdd(dr.RegisteredType, registrations);
            }

            ResolvableTypes.TryRemove(dr.RegisteredType, out _);

            registrations.Insert(0, dr);

            return;
        }
Exemplo n.º 29
0
        private void StartProcessing(ProcessorConfiguration configuration)
        {
            _asyncTaskQueue.TaskError += _asyncTaskQueue_TaskError;
            _asyncTaskQueue.StartProcessing();

            var processorFactory = new ProcessorFactory();

            _processor = processorFactory.Create(configuration, _asyncTaskQueue);

            _processor.ProcessSourceDirectory();

            _watcher = new EventWatcher(_processor,
                                        AppContainer.Container.Resolve <IConfigurationProvider>(),
                                        AppContainer.Container.Resolve <IFileWatcher>());
            StaticLogger.Log("Starting file watcher...");
            _watcher.Start();

            StaticLogger.Log("Ready.");
        }
Exemplo n.º 30
0
        /// <summary>
        /// Crea una entrada en el visor de eventos
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="eventType"></param>
        public static void Log(string source, string msg, EventType eventType, bool sendWindowsEvent)
        {
            Event ev = new Event();

            ev.LogType      = eventType;
            ev.Source       = source;
            ev.Message.Text = msg;
            ev.LogDate      = System.DateTime.Now;

            try
            {
                if (sendWindowsEvent && sendWindowsEvent_ok)
                {
                    StaticLogger.Log(TargetType.WindowsEvent, ev, string.Empty, string.Empty);
                }
            }
            catch (System.Security.SecurityException se)
            {
                sendWindowsEvent_ok = false;
                Event ev1 = new Event();
                ev1.LogType      = EventType.Warning;
                ev1.Source       = ServiceName;
                ev1.Message.Text = string.Concat("problemas de seguridad no se permite loguear mas en el visor de eventos\r\n", ExceptionHelper.GetAllMessageException(se));
                ev1.LogDate      = System.DateTime.Now;

                Audit(ev1);
            }
            catch (System.ComponentModel.Win32Exception we)//Puede q se llene el log de windows
            {
                sendWindowsEvent_ok = false;
                Event ev1 = new Event();
                ev1.LogType      = EventType.Warning;
                ev1.Source       = ServiceName;
                ev1.Message.Text = string.Concat("Problemas para crear logs en el visor de eventos, puede que este lleno\r\n", ExceptionHelper.GetAllMessageException(we));
                ev1.LogDate      = System.DateTime.Now;

                Audit(ev1);
            }

            Audit(ev);
            //SendMail(source, msg);
        }