Debug() public method

public Debug ( string message ) : void
message string
return void
 static void Main(string[] args)
 {
     try
     {
         log = LogManager.GetCurrentClassLogger();
         BookListService bls = new BookListService();
         log.Debug("Старт записи в двоичный файл");
             WriteDefaultValues(fileName);
         log.Debug("Окончание записи в двоичный файл");
         log.Debug("Старт чтения данных из двоичног файла");
         bls = ReadDefaultValues(fileName);
         log.Debug("Окончание чтения данных из двоичног файла");
         Book[] find = bls.FindByTag("1999", EnumTag.Year); //Поиск
         foreach (Book b in find)
         Console.WriteLine(b);
         Console.WriteLine("-------------------------");
         Book[] sort = bls.SortBooksByTag(EnumTag.Page);//Сортировка
         foreach (Book b in sort)
             Console.WriteLine(b);
         //log.Warn("Попытка добавить уже существующую книгу");
         //bls.AddBook(sort[0]); 
         bls.RemoveBook(sort[0]);//Удаление книги
         log.Warn("Попытка удаления книги отсутствующей в каталоге");
         bls.RemoveBook(sort[0]);
     }
     catch (Exception e)
     {
         log.Error(e.Message);
     }
     
 }
        //Constructor: Initializes the V1 instance connection.
        public VersionOneClient(IntegrationConfiguration Config, Logger Logger)
        {
            _logger = Logger;
            _config = Config;
            _V1_META_URL = Config.V1Connection.Url + "/meta.v1/";
            _V1_DATA_URL = Config.V1Connection.Url + "/rest-1.v1/";
            V1APIConnector metaConnector = new V1APIConnector(_V1_META_URL);
            V1APIConnector dataConnector;

            //Set V1 connection based on authentication type.
            if (_config.V1Connection.UseWindowsAuthentication == true)
            {
                _logger.Debug("-> Connecting with Windows Authentication.");

                //If username is not specified, try to connect using domain credentials.
                if (String.IsNullOrEmpty(_config.V1Connection.Username))
                {
                    _logger.Debug("-> Connecting with default Windows domain account: {0}\\{1}", Environment.UserDomainName, Environment.UserName);
                    dataConnector = new V1APIConnector(_V1_DATA_URL);
                }
                else
                {
                    _logger.Debug("-> Connecting with specified Windows domain account: {0}", _config.V1Connection.Username);
                    dataConnector = new V1APIConnector(_V1_DATA_URL, _config.V1Connection.Username, _config.V1Connection.Password, true);
                }
            }
            else
            {
                _logger.Debug("-> Connecting with V1 account credentials: {0}", _config.V1Connection.Username);
                dataConnector = new V1APIConnector(_V1_DATA_URL, _config.V1Connection.Username, _config.V1Connection.Password);
            }

            _v1Meta = new MetaModel(metaConnector);
            _v1Data = new Services(_v1Meta, dataConnector);
        }
示例#3
0
        public DirectoryEntry GetADDirectoryEntry(string FQDomainName, string LDAPPath, Logger Logger)
        {
            Logger.Debug(string.Format(@"Getting Directory Entry for LDAP Path {0}", LDAPPath));

            //DirectoryEntry LDAPConnection = new DirectoryEntry(FQDomainName);
            DirectoryEntry LDAPConnection = new DirectoryEntry("LDAP://"+FQDomainName);

            LDAPConnection.Path = "LDAP://"+LDAPPath;
            LDAPConnection.AuthenticationType = AuthenticationTypes.Secure;

               try
               {
               //Try fetch to Native ADSI Object  - if this passes Then we know that we
               //are authenticated. If an exception is thrown then we know we are using an Invalid Account.

               object DirEntryNativeObject = LDAPConnection.NativeObject;

               }
               catch (Exception ex)
               {
               Logger.Error(String.Format("Error authenticating to Active Directory with current running user. {0} {1}.",
                   ex.Message, ex.InnerException != null ? ex.InnerException.Message : ""));

               throw new Exception(String.Format("Error authenticating to Active Directory with current running user. {0} {1}.",
                   ex.Message, ex.InnerException != null ? ex.InnerException.Message : "" ));
               }

               return LDAPConnection;
        }
        public static ABIExitCode Compile(ABIFileSystemOptions options, LogFactory factory)
        {
            #region Argument exceptions

            if (options == null)
                throw new ArgumentNullException("options");

            if (factory == null)
                throw new ArgumentNullException("factory");

            #endregion

            _logger = factory.GetCurrentClassLogger();
            _logger.Debug(options);
            try
            {
                if (!Validate(options))
                    return ABIExitCode.ErrorDuringValidation;

                var engine = new CompilerEngine(options, factory);

                var result = engine.Compile();
                Debug.Assert(result != ABIExitCode.ErrorExitCodeUnassigned);
                return result;
            }
            catch (Exception ex) // avoid external unhandled exceptions
            {
                _logger.Error(ex);
            }

            return ABIExitCode.ErrorUnhandledException;
        }
示例#5
0
 /// <summary>
 /// Create a new NLog logger instance.
 /// </summary>
 /// <param name="name">Name of type to log as.</param>
 public NLogLog([NotNull] NLog.Logger log, [NotNull] string name)
 {
     if (name == null)
         throw new ArgumentNullException("name");
     _log = log;
     _log.Debug(() => "");
 }
示例#6
0
        private void TraceMessageInternal(LogLvl level, string message)
        {
            if (level > desiredLogLevel)
            {
                return;
            }

            switch (level)
            {
            case LogLvl.Debug:
                variableLogger?.Debug(message);
                break;

            case LogLvl.Info:
                variableLogger?.Info(message);
                break;

            case LogLvl.Warning:
                variableLogger?.Warn(message);
                break;

            case LogLvl.Error:
                variableErrorLogger?.Error(message);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }
示例#7
0
        public Group GetADGroup(ActiveDirectoryClient ADClient, string GroupNameSearchString, Logger Logger)
        {
            List<IGroup> foundGroups = null;

            try
            {
                Logger.Debug(string.Format("Searching/Fetching AD Group {0}", GroupNameSearchString));
                foundGroups = ADClient.Groups
                    .Where(group => group.DisplayName.StartsWith(GroupNameSearchString))
                    .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error when fetching group from Azure Active Directory {0} {1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : "");
                Logger.Error(String.Format("Error when fetching group from Azure Active Directory {0} {1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : ""));
            }
            if (foundGroups != null && foundGroups.Count > 0)
            {
                return foundGroups.First() as Group;
            }
            else
            {
                return null;
            }
        }
示例#8
0
        public ActiveDirectoryClient ADClient(IConfiguration Configuration, IAuthenticationProvidor authProvidor, Logger Logger)
        {
            ActiveDirectoryClient activeDirectoryClient;
            try
            {
                Logger.Debug(@"Connecting to Azure Active Directory GraphAPI to get ClientSession");
                activeDirectoryClient = authProvidor.GetActiveDirectoryClientAsApplication(Configuration);

                if (activeDirectoryClient != null)
                {
                    return activeDirectoryClient;
                }
                else
                {
                    return null;
                }
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                Logger.Error(String.Format(@"Could not aquire Azure active Directory Authentication Token {0}", ex.Message));

                if (ex.InnerException != null)
                {
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                    Logger.Error(String.Format(@"Error detail {0}", ex.InnerException));

                }
                Console.ResetColor();
                return null;
            }
        }
示例#9
0
        public void Execute()
        {
            _logger = LogManager.GetLogger("log");

            try
            {

                InitializeLoggingConfiguration();

                Application.AddMessageFilter(KeyboardTracking.Instance);
                SdlTradosStudio.Application.Closing += Application_Closing;

                _service = new KeyboardTrackingService(_logger);
                _editorController = SdlTradosStudio.Application.GetController<EditorController>();
                _editorController.Opened += _editorController_Opened;
                _editorController.ActiveDocumentChanged += _editorController_ActiveDocumentChanged;
                _editorController.Closing += _editorController_Closing;

                var twitterPersistenceService = new TwitterPersistenceService(_logger);
                if (twitterPersistenceService.HasAccountConfigured) return;
                using (var tForm = new TwitterAccountSetup(twitterPersistenceService))
                {
                    tForm.ShowDialog();
                }
            }
            catch (Exception ex)
            {

                _logger.Debug(ex,"Unexpected exception when intializing the app");
                throw;
            }
        }
示例#10
0
 /// <summary>
 /// Constructeur permettant de définir les arguments à passer en ligne de commande à memcached.
 /// </summary>
 /// <param name="defaultArguments">Arguments par défaut à passer à la commande de memcached (peut être <c>null</c>).</param>
 public Memcached(string[] defaultArguments)
 {
     _logger = LogManager.GetLogger(this.GetType().Name);
     _defaultArgs = defaultArguments;
     _memCachedPath = Resources.Resources.ExtractMemcachedToTemporaryDirectory();
     _tempDir = Path.GetDirectoryName(_memCachedPath);
     _logger.Debug("Exécutable memcached extrait dans le dossier temporaire {0}.", _tempDir);
 }
示例#11
0
        public void DisposeADDirectoryEntry(DirectoryEntry DirEntry, Logger Logger)
        {
            if (DirEntry != null)
            {
                DirEntry.Close();
            }

            Logger.Debug(@"Directory Entry Closed");
        }
示例#12
0
        protected void Application_Start()
        {
            logger = LogManager.GetCurrentClassLogger();
            logger.Debug("Application Started.");
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
示例#13
0
        public ProdutosController()
        {
            var factory = new LogFactory();

            _logger = factory.GetLogger("Default");

            _logger.Debug("Criando Controller");

            // var produtoRepository = new ProdutoADORepository();
            var produtoRepository = new ProdutoEFRepository();
            var departamentoRepository = new DepartamentoEFRepository();

            _catalogoService = new CatalogoService(produtoRepository, departamentoRepository);
        }
        public MemcachedService()
        {
            _logger = LogManager.GetLogger(this.GetType().Name);
            _logger.Debug(string.Format("Instanciation du service {0} ({1})...\r\nExécution 64 bits: {2}\r\nPf: {3}", _serviceName, _applicationPath, IntPtr.Size == 8, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)));
            this.ServiceName = _serviceName;
            EventLog.Source = _serviceName;
            this.EventLog.Log = "Application";
            this.AutoLog = true;

            this.CanHandlePowerEvent = false;
            this.CanHandleSessionChangeEvent = false;
            this.CanPauseAndContinue = false;
            this.CanStop = true;

            _memCached = new Memcached();
        }
示例#15
0
 private void DoWrite(Logger logger, LogLevel level, string message)
 {
     switch (level)
     {
         case LogLevel.Debug:
             logger.Debug(message);
             break;
         case LogLevel.Info:
             logger.Info(message);
             break;
         case LogLevel.Trace:
             logger.Trace(message);
             break;
         case LogLevel.Error:
         default:
             logger.Error(message);
             break;
     }
 }
示例#16
0
        public void Execute()
        {
            _logger = LogManager.GetLogger("log");
            #if DEBUG
            {
                _emailService = new EmailService(true);
            }
            #else
            {
                _emailService = new EmailService(false);
            }
            #endif

            try
            {

                InitializeLoggingConfiguration();

                Application.AddMessageFilter(KeyboardTracking.Instance);
                SdlTradosStudio.Application.Closing += Application_Closing;

                _service = new KeyboardTrackingService(_logger,_emailService);
                _editorController = SdlTradosStudio.Application.GetController<EditorController>();
                _editorController.Opened += _editorController_Opened;
                _editorController.ActiveDocumentChanged += _editorController_ActiveDocumentChanged;
                _editorController.Closing += _editorController_Closing;

                var twitterPersistenceService = new TwitterPersistenceService(_logger);
                if (twitterPersistenceService.HasAccountConfigured) return;
                using (var tForm = new TwitterAccountSetup(twitterPersistenceService))
                {
                    tForm.ShowDialog();
                }
                _logger.Info(string.Format("Started productivity plugin version {0}",VersioningService.GetPluginVersion()));
            }
            catch (Exception ex)
            {
                _logger.Debug(ex,"Unexpected exception when intializing the app");
                _emailService.SendLogFile();
            }
        }
        static void Main(string[] args)
        {            
            ConfigurationItemFactory.Default.Targets.RegisterDefinition("SignalTarget", typeof(SignalTarget));
            Logger = LogManager.GetCurrentClassLogger(typeof(SignalTarget));
            var rnd = new Random((int)DateTime.Now.Ticks);

            for (int i = 0; i < 100; i++) {
                Logger.Trace("Sample trace message from NLog");
                Logger.Debug("Sample debug message from NLog");
                Logger.Info("Sample informational message from NLog");
                Logger.Warn("Sample warning message from NLog");
                Logger.Error("Sample error message from NLog", new Exception("Something bad happened!"));
                Logger.Fatal("Sample fatal error message from NLog");

                var sleep = rnd.Next(20, 250);
                Console.WriteLine(string.Concat("Sleeping...:", sleep, "ms"));
                Thread.Sleep(sleep);
            }

            Console.WriteLine("Logging Complete. Press enter to continue...");
            Console.ReadLine();
        }
示例#18
0
        public static void CreateProductivityForm(Logger logger)
        {
            try
            {

                var productivityService = new ProductivityService(logger);
                var twitterPersistanceService = new TwitterPersistenceService(logger);
                var leaderboardApi = new LeaderboardApi(twitterPersistanceService);
                var versioningService = new VersioningService(leaderboardApi);
                var tweetMessageService = new TweetMessageService(versioningService);
                var twitterShareService = new TwitterShareService(twitterPersistanceService, tweetMessageService);
                using (var pForm = new ProductivityForm(productivityService, twitterShareService))
                {
                    pForm.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                logger.Debug(ex, "Unexpected exception when opening the productivity score");
                throw;
            }
        }
示例#19
0
 public void Debug(string msg)
 {
     _log?.Debug(msg);
     System.Diagnostics.Trace.TraceInformation($"{ProjectName} : {msg}");
 }
示例#20
0
        static void Main(string[] args)
        {
            logger = LogManager.GetCurrentClassLogger();

            links = new Hashtable();

            string courseId = "compinvesting1-003";

            logger.Info("Starting logger for CourseId: {0}", courseId);

            string outputRoot = @"C:\Coursera";
            outputDirectory = Path.Combine(outputRoot, courseId);

            logger.Info("Output root:\t{0}", outputRoot);
            logger.Debug("Output path:\t{0}", outputDirectory);

            if (!CleanOutputDirectory(outputDirectory))
            {

                logger.Error("Error cleaning output directory. Exiting.");
                Environment.Exit(1);

            }

            cookies = new CookieContainer();

            cookies.Add(new Cookie("CAUTH", "CAUTH=rOW2CeRiLNyXtRL4YCVynx8HmQFF5iuqo0QW34FpCv3-CNDUgOLSUsiL49wTZ0hQB0DrnacH4XGuoSDXVw1xNg.4icwuSn2_eIWxA8ZzTdLqA.LLIbVkqYGUDSFDpVFXV26_8VRyWsUPw6KvfrhNcRpsDEg7ybal7tRvwVN_pamKdUOgDl5Jht9-bLRNZqmX7peZ7enxlXQ4FQDb6liosj0gr_lC6v63W4HZid6rnWwK0aQL7b_Ru4RLp_XBSfKwhMyLH7eaa0a2SzQz7VvJ0gaVU", "/", "class.coursera.org"));

            string rootPage = String.Format("https://class.coursera.org/{0}/class/index", courseId);

            HtmlDocument document = GetPage(rootPage);

            links.Add(GetUrlWithoutAnchor(rootPage), "index.html");

            if (!DownloadStaticContent(ref document, Path.Combine(outputDirectory, "static")))
            {

                logger.Error("Error downloading static content. Exiting.");
                Environment.Exit(1);

            }

            foreach (HtmlNode node in document.DocumentNode.SelectNodes("//ul[@class='course-navbar-list']/li[@class='course-navbar-item']/a"))
            {

                Console.WriteLine("{0}: {1}", node.InnerText.Trim(), node.Attributes["href"].Value);

            }

            RemoveTopBar(ref document);
            StripJavaScript(ref document);
            ReplaceLinks(ref document);

            //Console.WriteLine(document.DocumentNode.OuterHtml);

            document.Save(Path.Combine(outputDirectory, "index.html"));

            Console.ReadKey();
        }
示例#21
0
        public MainClass(string [] args)
        {
            Ticker.Tick();

            // required for the MS .NET runtime that doesn't initialize glib automatically
            if (!GLib.Thread.Supported)
                GLib.Thread.Init();

            // Connect to dbus
            DBusInstance DBusInstance = ServiceManager.Get <DBusInstance> ();
            DBusInstance.Initialise ();

            if (DBusInstance.AlreadyRunning)
            {
                Console.WriteLine("Already running");
                DBusInstance.CommandParser.ParseCommands (args);
                return;
            }

            DBusInstance.CommandParser.RunCommand += HandleCommand;

            Ticker.Tick();
            CheckDataFolders();
            Ticker.Tock ("Checking folders");

            foreach (string arg in args)
                HandleCommand (arg);

            Ticker.Tick ();
            if (DebugEnabled) {
                BuildNlogConfig();
            }
            logger = DebugEnabled ? NLog.LogManager.GetCurrentClassLogger () : new EmptyLogger ();
            Ticker.Tock("NLog");

            logger.Info("Starting Monsoon");

            Ticker.Tick ();
            SetProcessName("monsoon");
            Ticker.Tock("Setting process name");

            string localeDir = Path.Combine(Defines.ApplicationDirectory, "locale");
            if (!Directory.Exists(localeDir)) {
                localeDir = Path.Combine(Defines.InstallPrefix, "share");
                localeDir = Path.Combine(localeDir, "locale");
            }

            Ticker.Tick ();
            Mono.Unix.Catalog.Init("monsoon", localeDir);
            logger.Debug("Using locale data from: {0}", localeDir);

            Application.Init("monsoon", ref args);
            Ticker.Tock("Locale");

            try {
                SettingsManager.Restore <EngineSettings> (SettingsManager.EngineSettings);
                SettingsManager.Restore <PreferencesSettings> (SettingsManager.Preferences);
                SettingsManager.Restore <TorrentSettings> (SettingsManager.DefaultTorrentSettings);
            }
            catch (Exception ex) {
                logger.Error("Couldn't restore old settings: {0}", ex.Message);
            }

            try
            {
                Ticker.Tick();
                mainWindow = new MainWindow ();
                Ticker.Tock ("Instantiating window");

            }
            catch(Exception e)
            {
                logger.ErrorException(e.Message, e);
                Environment.Exit (0);
            }

            LoadAddins ();

            GLib.ExceptionManager.UnhandledException += new GLib.UnhandledExceptionHandler(OnUnhandledException);

            Ticker.Tock ("Total time:");
            Application.Run();

            try {
                SettingsManager.Store <EngineSettings> (SettingsManager.EngineSettings);
                SettingsManager.Store <PreferencesSettings> (SettingsManager.Preferences);
                SettingsManager.Store <TorrentSettings> (SettingsManager.DefaultTorrentSettings);
            }
            catch (Exception ex) {
                logger.Error("Could save engine settings: {0}", ex.Message);
            }
            ServiceManager.Get <ListenPortController> ().Stop ();
            mainWindow.Destroy ();
        }
示例#22
0
 public static void Debug(string msg)
 {
     _logger.Debug(msg);
 }
示例#23
0
 /// <summary>
 /// Запись в лог
 /// </summary>
 /// <param name="message">Сообщение лога</param>
 /// <param name="pars">Дополнительный данные лога</param>
 public static void Write(string message, params object[] pars)
 {
     _logger.Debug(message, pars);
 }
示例#24
0
 /// <summary>
 /// <inheritdoc cref="ILogger"/>
 /// </summary>
 public void Debug(string message)
 => logger.Debug(message);
示例#25
0
        static int Main(string[] args)
        {
            ConfigureNlog();
            _logger = LogManager.GetCurrentClassLogger();
            Snapx.EnableNLogLogProvider();

            if (Environment.GetEnvironmentVariable("SNAPX_WAIT_DEBUGGER") == "1")
            {
                var process = Process.GetCurrentProcess();

                while (!Debugger.IsAttached)
                {
                    _logger.Debug($"Waiting for debugger to attach... Process id: {process.Id}");
                    Thread.Sleep(1000);
                }

                _logger.Debug("Debugger attached.");
            }


            _logger.Info($"Process started! Arguments({args.Length}): {string.Join(" ", args)}");

            if (Snapx.ProcessEvents(args))
            {
                return(0);
            }

            var snapApp = Snapx.Current;

            if (snapApp != null)
            {
                // Supervisor automatically restarts your application if it crashes.
                // If you need to exit your application the you must invoke Snapx.StopSupervisor() before exiting.
                Snapx.StartSupervisor();
            }

            var mainWindowViewModel = new MainWindowViewModel
            {
                ViewIsDefault = true,
                Environment   = new AppEnvironment
                {
                    SnapApp       = snapApp,
                    UpdateManager = snapApp == null ? null : new SnapUpdateManager
                    {
                        ApplicationId = Guid.NewGuid().ToString("N")
                    }
                }
            };

            AppBuilder
            .Configure <App>()
            .UsePlatformDetect()
            .UseReactiveUI()
            .AfterSetup(x =>
            {
                MainWindow.ViewModel = mainWindowViewModel;
            })
            .StartWithClassicDesktopLifetime(args);

            return(0);
        }
示例#26
0
        public OperationResult Disassociate(string connectionString, Guid processId)
        {
            OperationResult operationResult = new OperationResult();

            try
            {
                try
                {
                    using (HttpClient client = ConnectionHelper.GetHttpClient(connectionString, ConnectionHelper.clientId, ConnectionHelper.redirectUrl))
                    {
                        client.DefaultRequestHeaders.Add("Accept", "application/json");
                        client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                        client.DefaultRequestHeaders.Add("OData-Version", "4.0");
                        //client.DefaultRequestHeaders.Add("Prefer", "return=representation");


                        //HttpContent c = new StringContent(jsonObject.ToString(Formatting.None), Encoding.UTF8, "application/json");
                        string targetQuery  = "";
                        string relatedQuery = "";

                        if (String.IsNullOrEmpty(this.TargetIdKeyToUse))
                        {
                            targetQuery = $"{this.TargetEntityName}({this.TargetEntityId})";
                        }
                        else
                        {
                            if (WrapTargetEntityIdWithQuotes)
                            {
                                targetQuery = $"{this.TargetEntityName}({this.TargetIdKeyToUse}='{this.TargetEntityId}')";
                            }
                            else
                            {
                                targetQuery = $"{this.TargetEntityName}({this.TargetIdKeyToUse}={this.TargetEntityId})";
                            }
                        }

                        if (String.IsNullOrEmpty(this.RelatedEntityIdKeyToUse))
                        {
                            relatedQuery = $"{this.RelationshipDefinitionName}({this.RelatedEntityId})";
                        }
                        else
                        {
                            if (WrapRelatedEntityIdWithQuotes)
                            {
                                relatedQuery = $"{this.RelationshipDefinitionName}({this.RelatedEntityIdKeyToUse}='{this.RelatedEntityId}')";
                            }
                            else
                            {
                                relatedQuery = $"{this.RelationshipDefinitionName}({this.RelatedEntityIdKeyToUse}={this.RelatedEntityId})";
                            }
                        }


                        string url = $"{targetQuery}/{relatedQuery}/$ref";

                        MethodBase m = MethodBase.GetCurrentMethod();
                        Logger.Debug("ProcessID: {processId} Action: {actionName} ", processId, m.Name);

                        var response = client.DeleteAsync(url).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            //Get the response content and parse it.
                            //JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                            //string userId = (string)body[this.Fields.EntityId];
                            operationResult.Code         = "";
                            operationResult.Message      = "Desasociación realizada correctamente";
                            operationResult.IsSuccessful = true;
                            operationResult.Data         = null;
                        }
                        else
                        {
                            //Get the response content and parse it.
                            JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                            //CrmWebAPIError userId = (CrmWebAPIError)body["error"];
                            JObject        result = JObject.Parse(body.ToString());
                            CrmWebAPIError err    = result.ToObject <CrmWebAPIError>();

                            if (err != null)
                            {
                                LogEventInfo log = new LogEventInfo(LogLevel.Error, Logger.Name, $"Url:{url} ErrorCode:{err.error.code} ErrorMessage:{err.error.message} ResponseReasonPhrase:{response.ReasonPhrase}");
                                log.Properties["ProcessID"]  = processId;
                                log.Properties["AppID"]      = AboxDynamicsBase.Classes.Constants.ApplicationIdWebAPI;
                                log.Properties["MethodName"] = System.Reflection.MethodBase.GetCurrentMethod().Name;
                                Logger.Log(log);
                            }

                            operationResult.Code          = "Ocurrió un error desasociando las entidades";
                            operationResult.Message       = response.ReasonPhrase;
                            operationResult.IsSuccessful  = false;
                            operationResult.Data          = null;
                            operationResult.InternalError = err;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogEventInfo log = new LogEventInfo(LogLevel.Error, Logger.Name, null, "", null, ex);
                    log.Properties["ProcessID"]  = processId;
                    log.Properties["AppID"]      = AboxDynamicsBase.Classes.Constants.ApplicationIdWebAPI;
                    log.Properties["MethodName"] = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    Logger.Log(log);
                    operationResult.Code         = "";
                    operationResult.Message      = ex.ToString();
                    operationResult.IsSuccessful = false;
                    operationResult.Data         = null;
                }

                return(operationResult);
            }
            catch (Exception ex)
            {
                LogEventInfo log = new LogEventInfo(LogLevel.Error, Logger.Name, null, "", null, ex);
                log.Properties["ProcessID"]  = processId;
                log.Properties["AppID"]      = AboxDynamicsBase.Classes.Constants.ApplicationIdWebAPI;
                log.Properties["MethodName"] = System.Reflection.MethodBase.GetCurrentMethod().Name;
                Logger.Log(log);

                operationResult.Code         = "";
                operationResult.Message      = ex.ToString();
                operationResult.IsSuccessful = false;
                operationResult.Data         = null;
                return(operationResult);
            }
        }
示例#27
0
        public DicomCStoreResponse OnCStoreRequest(DicomCStoreRequest request)
        {
            logger.Debug($"Recived StoreRequest ");
            lock (this)
            {
                try
                {
                    string guid = Guid.NewGuid().ToString();

                    string storePath  = ConfigurationManager.AppSettings["DicomStorePath"];
                    var    actualPath = Path.GetFullPath(storePath);

                    logger.Debug($"Store path = {actualPath}");

                    string tempPath = Path.GetDirectoryName(actualPath).ToString() + "\\dicomfiles\\temp\\" + guid + ".dcm";
                    logger.Debug($"Temp files store  path = {tempPath}");

                    if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
                    {
                        logger.Debug("Temp folder does not exist - creating temp folder");
                        Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
                    }
                    actualPath = Path.Combine(actualPath, guid);
                    actualPath = Path.Combine(actualPath) + ".dcm";

                    request.File.Save(actualPath);
                    logger.Debug($"Saving file {actualPath}");
                    request.File.Save(tempPath);
                    logger.Debug($"Saving file {tempPath}");

                    return(new DicomCStoreResponse(request, DicomStatus.Success));
                }
                catch (Exception ex)
                {
                    do
                    {
                        logger.Error(ex.Message);
                        ex = ex.InnerException;
                    } while (ex.InnerException != null);

                    return(new DicomCStoreResponse(request, DicomStatus.Cancel));
                }
            }
        }
示例#28
0
        protected override Variant OnCall(string method, List <Dom.ActionParameter> args)
        {
            object [] parameters = new object[args.Count];
            int       count      = 0;

            foreach (var arg in args)
            {
                try
                {
                    parameters[count] = GetVariantValue(arg.dataModel[0].InternalValue);
                }
                catch (Exception ex)
                {
                    logger.Debug("OnCall: Warning, unable to get value for parameter #" + count + ".  Setting parameter to null.  Exception: " + ex.ToString());
                    parameters[count] = null;
                }

                count++;
            }

            try
            {
                WebServiceInvoker invoker = new WebServiceInvoker(new Uri(this.Url));
                object            ret     = invoker.InvokeMethod <object>(this.Service, method, parameters);

                StatusCode = HttpStatusCode.OK.ToString();

                if (ret == null)
                {
                    return(null);
                }

                return(new Variant(ret.ToString()));
            }
            catch (Exception ex)
            {
                if (ex.InnerException is ArgumentException &&
                    ex.InnerException.Message.IndexOf("surrogate") != -1)
                {
                    throw new SoftException(ex.InnerException);
                }
                if (ex.InnerException is InvalidOperationException &&
                    ex.InnerException.Message.IndexOf("XML") != -1)
                {
                    throw new SoftException(ex.InnerException);
                }

                if (!(ex.InnerException is WebException))
                {
                    throw;
                }

                var webEx    = ex.InnerException as WebException;
                var response = webEx.Response as HttpWebResponse;
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    StatusCode = response.StatusCode.ToString();
                    logger.Debug("OnCall: Warning: Status code was: " + StatusCode);

                    if (ErrorOnStatusCode)
                    {
                        var sex = new SoftException(ex);                         // Soft or ignore?
                        throw sex;
                    }
                    else
                    {
                        return(null);
                    }
                }

                throw;
            }
        }
示例#29
0
 public void Debug(string message)
 {
     Logger.Debug(message);
     WriteToConsole(message);
     EventLogger.WriteToEventLog(message);
 }
示例#30
0
        /// <summary>
        /// Gets the files of given type, use postfixFilesName in search pattern.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="type">The type of files.</param>
        /// <param name="postfixFilesName">Postfix name of files for search pattern.</param>
        /// <returns>
        /// Collection of files.
        /// </returns>
        /// <example>How to use it: <code>
        /// var files = GetFilesOfGivenType(folder, FileType.Txt, "live");
        /// </code></example>
        public static ICollection <FileInfo> GetFilesOfGivenType(string folder, FileType type, string postfixFilesName)
        {
            Logger.Debug("Get Files '{0}' from '{1}', postfixFilesName '{2}'", type, folder, postfixFilesName);
            ICollection <FileInfo> files =
                new DirectoryInfo(folder)
                .GetFiles("*" + postfixFilesName + ReturnFileExtension(type)).OrderBy(f => f.Name).ToList();

            return(files);
        }
示例#31
0
 public override void Debug(string message, params object[] args) => _log.Debug(message, args);
示例#32
0
 private void Cancel_Click(object sender, EventArgs e)
 {
     logger = LogManager.GetCurrentClassLogger();
     logger.Debug("User Clicked Cancel Button");
     this.Close();
 }
示例#33
0
文件: Logger.cs 项目: Exmaru/Techdas
 public void Debug(string msg)
 {
     logger.Debug(msg);
 }
示例#34
0
 public void Debug(string msg, params object[] args)
 {
     _logger.Debug(msg, args);
 }
        /// <summary>
        /// Constructs a graph containing raw and parsed information of the insight API result
        /// </summary>
        /// <param name="root"> the element list API result</param>
        /// <param name="service">the service get API result</param>
        /// <param name="_debug"> indicated whether the program should run in debug mode</param>
        /// <param name="uuid"> the name of the service to build a graph for</param>
        public ServiceGraph(IqlApiResult root, IqlApiResult service, bool _debug, string uuid)
        {
            debug        = _debug;
            logger       = NLog.LogManager.GetCurrentClassLogger();
            this.Service = new Service(service, logger, uuid);
            if (root == null || service.objectEntries == null || service.objectTypeAttributes == null)
            {
                return;
            }
            if (root.objectEntries == null || root.objectTypeAttributes == null)
            {
                ElementMemberIsNull = true;
                return;
            }
            this.RouteElements                 = root.objectEntries;
            this.RouteTypeAttributes           = root.objectTypeAttributes;
            this.ElementIncomingElementIndexes = new HashSet <int> [root.objectEntries.Count];
            this.ServiceElementNameList        = new Dictionary <string, int>();
            this.ObjectAttributeTypesById      = new Dictionary <int, string>();
            this.IqlApiResult = root;
            bool initSuccess           = true;
            bool incominElementSuccess = true;
            bool soureSetSuccess       = true;
            bool buildGraphSuccess     = true;

            try
            {
                logger.Debug("Starting the data initialization......");
                InitData();
                logger.Debug("Data initialization completed");
            }
            catch (Exception e)
            {
                logger.Error("initialization failed " + Service.Name + "\n" + e.Message);
                initSuccess = false;
            }
            try
            {
                logger.Debug("Setting Incoming elements......");
                FindIncomingElements();
                logger.Debug("Incoming elements setting completed");
            }
            catch (Exception e)
            {
                logger.Error("Setting Incoming elements failed " + Service.Name + "\n" + e.Message);
                incominElementSuccess = false;
            }
            try
            {
                logger.Debug("Setting sources......");
                this.Sources = FindSources();
                logger.Debug("source setting completed");
            }
            catch (Exception e)
            {
                logger.Error("Setting sources failed" + "\n" + e.Message);
                soureSetSuccess = false;
            }
            try
            {
                logger.Debug("Starting the graph build......");
                BuildServiceGraph();
                logger.Debug("graph build completed");
            }
            catch (Exception e)
            {
                logger.Error("graph build failed" + "\n" + e.Message);
                buildGraphSuccess = false;
            }

            this.constructorSuceeded = initSuccess && incominElementSuccess && soureSetSuccess && buildGraphSuccess;
        }
        public NippsSiteResponse ListSite()
        {
            NLog.Logger       logger   = NLog.LogManager.GetCurrentClassLogger();
            NippsSiteResponse response = new NippsSiteResponse();

            response.ResultMessages = new List <string>();

            try
            {
                using (ServerManager serverManager = ServerManager.OpenRemote("localhost"))
                {
                    List <NippsSite> sites = new List <NippsSite>();

                    foreach (Site site in serverManager.Sites)
                    {
                        NippsSite nippsSite = new NippsSite();
                        nippsSite.Name = site.Name;
                        nippsSite.NippsApplications = new List <NippsApplication>();

                        foreach (Application application in site.Applications)
                        {
                            try
                            {
                                nippsSite.NippsApplications.Add(new NippsApplication
                                {
                                    ApplicationPoolName = application.ApplicationPoolName,
                                    Path                 = application.Path,
                                    PhysicalPath         = ServerManagerHelper.PutEnvVarValue(application.VirtualDirectories[0].PhysicalPath),
                                    ApplicationPoolState = serverManager.ApplicationPools[application.ApplicationPoolName].State,
                                    Version              = GetVersion(application)
                                });
                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex.ToString());
                                response.ResultMessages.Add(ex.ToString());
                            }
                        }

                        try
                        {
                            nippsSite.State    = site.State;
                            nippsSite.Protocol = site.Bindings[0].Protocol;
                            nippsSite.Port     = site.Bindings[0].EndPoint.Port.ToString();
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.ToString());
                            response.ResultMessages.Add(ex.ToString());
                        }

                        sites.Add(nippsSite);
                    }

                    response.NippsSites = sites;
                    response.Result     = Result.OK;
                    logger.Debug(sites);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                response.Result = Result.FAIL;
                response.ResultMessages.Add(ex.ToString());
            }

            return(response);
        }
示例#37
0
 public void Debug(LogOutputProvider messageProvider)
 {
     _log.Debug(ToGenerator(messageProvider));
 }
        private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey)
        {
            aiLogger.Trace("Sample trace message");
            aiLogger.Debug("Sample debug message");
            aiLogger.Info("Sample informational message");
            aiLogger.Warn("Sample warning message");
            aiLogger.Error("Sample error message");
            aiLogger.Fatal("Sample fatal error message");

            AdapterHelper.ValidateChannel(this.adapterHelper, instrumentationKey, 6);
        }
示例#39
0
 public static void Debug([Localizable(false)] string message, params object[] args)
 {
     Log.Debug(message, args);
 }
 public SyncCommandRunner()
 {
     _logger = LogManager.GetCurrentClassLogger();
     _logger.Debug("Try to Get Communicator");
     _communicatorInstance = (ICommunicator) Communicator.Instance;
 }
示例#41
0
 public void Debug(string msg)
 {
     loger.Debug(msg);
     CommitLogInfo("DEBUG", msg);
 }
示例#42
0
        /// <summary>
        /// Called to crack a DataElement based on an input stream.  This method
        /// will hand cracking off to a more specific method after performing
        /// some common tasks.
        /// </summary>
        /// <param name="elem">DataElement to crack</param>
        /// <param name="data">Input stream to use for data</param>
        void handleNode(DataElement elem, BitStream data)
        {
            List <BitStream> oldStack = null;

            try
            {
                if (elem == null)
                {
                    throw new ArgumentNullException("elem");
                }
                if (data == null)
                {
                    throw new ArgumentNullException("data");
                }

                logger.Debug("------------------------------------");
                logger.Debug("{0} {1}", elem.debugName, data.Progress);

                var pos = handleNodeBegin(elem, data);

                if (elem.transformer != null)
                {
                    long startPos    = data.TellBits();
                    var  sizedData   = elem.ReadSizedData(data, pos.size);
                    var  decodedData = elem.transformer.decode(sizedData);

                    // Make a new stack of data for the decoded data
                    oldStack   = _dataStack;
                    _dataStack = new List <BitStream>();
                    _dataStack.Add(decodedData);

                    // Use the size of the transformed data as the new size of the element
                    handleCrack(elem, decodedData, decodedData.LengthBits);

                    // Make sure the non-decoded data is at the right place
                    if (data == decodedData)
                    {
                        data.SeekBits(startPos + decodedData.LengthBits, System.IO.SeekOrigin.Begin);
                    }
                }
                else
                {
                    handleCrack(elem, data, pos.size);
                }

                if (elem.constraint != null)
                {
                    handleConstraint(elem, data);
                }

                if (elem.analyzer != null)
                {
                    _elementsWithAnalyzer.Add(elem);
                }

                handleNodeEnd(elem, data, pos);
            }
            catch (Exception e)
            {
                handleException(elem, data, e);
                throw;
            }
            finally
            {
                if (oldStack != null)
                {
                    _dataStack = oldStack;
                }
            }
        }
 public static void LogErrors(Exception ex)
 {
     Logger.Debug(ex.Message);
     Logger.Debug(ex.StackTrace);
     Logger.Debug(ex.InnerException);
 }
 //Ctor
 protected DefaultComponentModel()
 {
     logger = LogManager.GetLogger (this.GetType ().ToString ());
     logger.Debug ("Executing ctor for: " + this.GetType ().FullName);
     viewHandlerCollection = new IViewHandlerCollection ();
 }
示例#45
0
        void Startup()
        {
            #region INISetup
            try
            {
                if (!File.Exists(iniPath))
                {
                    //INI File is not present in application directory
                    //Create one by hand and set default settings;
                    Console.WriteLine("[STARTUP] INI File not found, Generating one with default values");
                    ini = new INI.IniFile();
                    ini.Section("General").Set("LogToFile", "True");
                    ini.Section("General").Set("LogLevel", "Debug");
                    ini.Section("General").Set("LogToConsole", "False");
                    ini.Section("General").Set("ConsoleLogLevel", "Warn");
                    ini.Section("General").Set("LogDir", Environment.CurrentDirectory + "\\Logs");
                    ini.Section("General").Set("AppDir", Environment.CurrentDirectory + "\\Applications");
                    ini.Section("General").Set("SourceDir", Environment.CurrentDirectory + "\\Source");
                    ini.Section("General").Set("ToolDir", Environment.CurrentDirectory + "\\Tools");
                    ini.Section("Optional").Set("ClearBeforeMain", "True", "This will clear the console before displaying main menu");
                    ini.Save(iniPath);
                }

                //Reading INI File and setting variables;
                ini = new INI.IniFile(iniPath);

                Console.WriteLine("[STARTUP] Reading INI values...");
                logLevel = ini.Section("General").Get("LogLevel");
                wtc.WriteWhite("[STARTUP] LogLevel: ");
                wtc.WriteGreen(logLevel + "\n");
                bLogToConsole = Boolean.Parse(ini.Section("General").Get("LogToConsole"));
                wtc.WriteWhite("[STARTUP] LogToConsole: ");
                wtc.WriteGreen(bLogToConsole.ToString() + "\n");
                consoleLogLevel = ini.Section("General").Get("ConsoleLogLevel");
                wtc.WriteWhite("[STARTUP] ConsoleLogLevel: ");
                wtc.WriteGreen(consoleLogLevel + "\n");
                logDir = ini.Section("General").Get("LogDir");
                wtc.WriteWhite("[STARTUP] Log Directory: ");
                wtc.WriteGreen(logDir + "\n");
                appDir = ini.Section("General").Get("AppDir");
                wtc.WriteWhite("[STARTUP] Application Directory: ");
                wtc.WriteGreen(appDir + "\n");
                sourceDir = ini.Section("General").Get("SourceDir");
                wtc.WriteWhite("[STARTUP] Source Directory: ");
                wtc.WriteGreen(sourceDir + "\n");
                toolDir = ini.Section("General").Get("ToolDir");
                wtc.WriteWhite("[STARTUP] Tool Directory: ");
                wtc.WriteGreen(toolDir + "\n");

                //Optional INI settings
                //WE don't care if their missing, just to tailor the experience to each user;
                wtc.WriteWhiteLine("[STARTUP] Checking for optional INI settings");
                try
                {
                    wtc.WriteWhite("[OPTIONAL] Checking for ClearBeforeMain");
                    bClearBeforeMenu = Boolean.Parse(ini.Section("Optional").Get("ClearBeforeMain"));
                }
                catch
                {

                }

                //Checking for Logging directory first so we can log missing folder structure later.
                if (!Directory.Exists(logDir))
                {
                    wtc.WriteWhiteLine("[STARTUP] No logDirectory found, attempting to create");
                    //Try to create the logDir, Fail out and throw error if not
                    try
                    {
                        Directory.CreateDirectory(logDir);
                        wtc.WriteWhite("[STARTUP] Creating LogDir at ");
                        wtc.WriteGreenLine(logDir);
                    }
                    catch (Exception ex)
                    {
                        //Unable to create the directory, throw fatal error and exit
                        wtc.WriteRedLine("Fatal Error: " + ex.Message);
                        Console.ReadKey();
                        Environment.Exit(5);
                    }
                }
                #endregion

            #region Logging

                var config = new LoggingConfiguration();
                var fileTarget = new FileTarget();

                config.AddTarget("file", fileTarget);

                fileTarget.Layout = "[${longdate}] - [${level}]: ${message}";
                fileTarget.FileName = logDir + "\\Main.log";

                LoggingRule rule_LTF;

                switch (logLevel.ToUpper())
                {
                    case "TRACE":
                        rule_LTF = new LoggingRule("*", LogLevel.Trace, fileTarget);
                        wtc.WriteWhite("[STARTUP] LogToFileLevel set to: ");
                        wtc.WriteGreen(logLevel + "\n");
                        break;
                    case "DEBUG":
                        rule_LTF = new LoggingRule("*", LogLevel.Debug, fileTarget);
                        wtc.WriteWhite("[STARTUP] LogToFileLevel set to: ");
                        wtc.WriteGreen(logLevel + "\n");
                        break;
                    case "WARN":
                        rule_LTF = new LoggingRule("*", LogLevel.Warn, fileTarget);
                        wtc.WriteWhite("[STARTUP] LogToFileLevel set to: ");
                        wtc.WriteGreen(logLevel + "\n");
                        break;
                    case "INFO":
                        rule_LTF = new LoggingRule("*", LogLevel.Info, fileTarget);
                        wtc.WriteWhite("[STARTUP] LogToFileLevel set to: ");
                        wtc.WriteGreen(logLevel + "\n");
                        break;
                    case "ERROR":
                        rule_LTF = new LoggingRule("*", LogLevel.Error, fileTarget);
                        wtc.WriteWhite("[STARTUP] LogToFileLevel set to: ");
                        wtc.WriteGreen(logLevel + "\n");
                        break;
                    default:
                        wtc.WriteRedLine("[STARTUP] Uknown type " + logLevel + " defaulting to WARN");
                        rule_LTF = new LoggingRule("*", LogLevel.Warn, fileTarget);
                        break;
                }

                config.LoggingRules.Add(rule_LTF);

                if (bLogToConsole)
                {
                    var consoleTarget = new ColoredConsoleTarget();
                    config.AddTarget("console", consoleTarget);

                    consoleTarget.Layout = "[${longdate}] - [${level}]: ${message}";
                    LoggingRule rule_LTC;

                    switch (consoleLogLevel.ToUpper())
                    {
                        case "TRACE":
                            rule_LTC = new LoggingRule("*", LogLevel.Trace, consoleTarget);
                            wtc.WriteWhite("[STARTUP] ConsoleLogLevel set to: ");
                            wtc.WriteGreen(consoleLogLevel + "\n");
                            break;
                        case "DEBUG":
                            rule_LTC = new LoggingRule("*", LogLevel.Debug, consoleTarget);
                            wtc.WriteWhite("[STARTUP] ConsoleLogLevel set to: ");
                            wtc.WriteGreen(consoleLogLevel + "\n");
                            break;
                        case "WARN":
                            rule_LTC = new LoggingRule("*", LogLevel.Warn, consoleTarget);
                            wtc.WriteWhite("[STARTUP] ConsoleLogLevel set to: ");
                            wtc.WriteGreen(consoleLogLevel + "\n");
                            break;
                        case "INFO":
                            rule_LTC = new LoggingRule("*", LogLevel.Info, consoleTarget);
                            wtc.WriteWhite("[STARTUP] ConsoleLogLevel set to: ");
                            wtc.WriteGreen(consoleLogLevel + "\n");
                            break;
                        case "ERROR":
                            rule_LTC = new LoggingRule("*", LogLevel.Error, consoleTarget);
                            wtc.WriteWhite("[STARTUP] ConsoleLogLevel set to: ");
                            wtc.WriteGreen(consoleLogLevel + "\n");
                            break;
                        default:
                            wtc.WriteRedLine("[STARTUP] Uknown type " + consoleLogLevel + " defaulting to WARN");
                            rule_LTC = new LoggingRule("*", LogLevel.Warn, fileTarget);
                            break;
                    }

                    config.LoggingRules.Add(rule_LTC);
                }
                else
                {
                    wtc.WriteWhite("[STARTUP] LogToConsole set to: ");
                    wtc.WriteRed(bLogToConsole.ToString());
                    wtc.WriteWhiteLine(" - Skipping level check");
                }

                LogManager.Configuration = config;
                logger = LogManager.GetCurrentClassLogger();

                logger.Debug("============================");
                logger.Debug("Application Started");
                logger.Debug("============================");

                logger.Debug("Exporting settings to log");
                logger.Debug("LogLevel: " + logLevel);
                logger.Debug("LogToConsole " + bLogToConsole.ToString());
                logger.Debug("ConsoleLogLevel: " + consoleLogLevel);
                logger.Debug("LogDir: " + logDir);
                logger.Debug("AppDir: " + appDir);
                logger.Debug("SourceDir: " + sourceDir);
                logger.Debug("ToolDir: " + toolDir);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Critical  Error: ");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Application will now close");
                Console.ReadKey();
                Environment.Exit(1605);
            }

            #endregion

            #region DirectoryCheck

            //Broke up the Try Catch so we can get the error and parse it to the log versus the console before logging exists.

            try
            {

                //Check through each directory to make sure they exist
                logger.Debug("Checking through each directory to make sure they exist");

                wtc.WriteWhiteLine("[STARTUP] Checking for AppDirectory");
                logger.Debug("Checking for AppDirectory at " + appDir);

                if (!Directory.Exists(appDir))
                {
                    logger.Debug("No Directory found at " + appDir);

                    //Try to create the appDir, Fail out and throw error if not
                    try
                    {
                        logger.Debug("Attempting to create directory at " + appDir);
                        Directory.CreateDirectory(appDir);
                        wtc.WriteWhite("[STARTUP] Creating AppDir at ");
                        wtc.WriteGreenLine(appDir);
                    }
                    catch (Exception ex)
                    {
                        //Unable to create the directory, throw fatal error and exit
                        logger.Error("Unable to create directory at " + appDir);
                        logger.Error("Failed with error: " + ex.Message);
                        wtc.WriteRedLine("Fatal Error: " + ex.Message);
                        Console.ReadKey();
                        Environment.Exit(6);
                    }
                }
                else
                {
                    logger.Debug("AppDirectory exists at " + appDir);
                    wtc.WriteGreenLine("[STARTUP] Application Directory exists!");
                }

                wtc.WriteWhiteLine("[STARTUP] Checking for SourceDirectory");
                logger.Debug("Checking for SourceDirectory at " + sourceDir);

                if (!Directory.Exists(sourceDir))
                {
                    logger.Debug("No Directory found at " + sourceDir);

                    //Try to create the appDir, Fail out and throw error if not
                    try
                    {
                        logger.Debug("Attempting to create directory at " + sourceDir);
                        Directory.CreateDirectory(sourceDir);
                        wtc.WriteWhite("[STARTUP] Creating SourceDir at ");
                        wtc.WriteGreenLine(sourceDir);

                    }
                    catch (Exception ex)
                    {
                        //Unable to create the directory, throw fatal error and exit
                        logger.Error("Unable to create directory at " + sourceDir);
                        logger.Error("Failed with error: " + ex.Message);
                        wtc.WriteRedLine("Fatal Error: " + ex.Message);
                        Console.ReadKey();
                        Environment.Exit(7);
                    }
                }
                else
                {
                    logger.Debug("SourceDirectory exists at " + sourceDir);
                    wtc.WriteGreenLine("[STARTUP] Source Directory exists!");
                }

                wtc.WriteWhiteLine("[STARTUP] Checking for ToolDirectory");
                logger.Debug("Checking for ToolDirectory at " + sourceDir);

                if (!Directory.Exists(toolDir))
                {
                    logger.Debug("No Directory found at " + toolDir);

                    //Try to create the appDir, Fail out and throw error if not
                    try
                    {
                        logger.Debug("Attempting to create directory at " + sourceDir);
                        Directory.CreateDirectory(toolDir);
                        wtc.WriteWhite("[STARTUP] Creating ToolDir at ");
                        wtc.WriteGreenLine(toolDir);

                    }
                    catch (Exception ex)
                    {
                        //Unable to create the directory, throw fatal error and exit
                        logger.Error("Unable to create directory at " + sourceDir);
                        logger.Error("Failed with error: " + ex.Message);
                        wtc.WriteRedLine("Fatal Error: " + ex.Message);
                        Console.ReadKey();
                        Environment.Exit(7);
                    }
                }
                else
                {
                    logger.Debug("ToolDirectory exists at " + toolDir);
                    wtc.WriteGreenLine("[STARTUP] Tool Directory exists!");
                }

                //Check for Write/Read/Delete Permissions in directories;

                logger.Debug("Checking for Write/Read/Delete Permissions in directories");
                try
                {
                    //APPDIR
                    logger.Debug("Creating file TEST in " + appDir);
                    File.WriteAllText(appDir + "\\test.test", "");
                    logger.Debug(appDir + "\\test.test" + " - File Created!");
                    logger.Debug("Deleting File " + appDir + "\\test.test");
                    File.Delete(appDir + "\\test.test");
                    logger.Debug(appDir + "\\test.test" + " - File Deleted!");
                    //SOURCEDIR
                    logger.Debug("Creating file TEST in " + sourceDir);
                    File.WriteAllText(sourceDir + "\\test.test", "");
                    logger.Debug(sourceDir + "\\test.test" + " - File Created!");
                    logger.Debug("Deleting File " + sourceDir + "\\test.test");
                    File.Delete(sourceDir + "\\test.test");
                    logger.Debug(sourceDir + "\\test.test" + " - File Deleted!");
                    //TOOLDIR
                    logger.Debug("Creating file TEST in " + toolDir);
                    File.WriteAllText(toolDir + "\\test.test", "");
                    logger.Debug(toolDir + "\\test.test" + " - File Created!");
                    logger.Debug("Deleting File " + toolDir + "\\test.test");
                    File.Delete(toolDir + "\\test.test");
                    logger.Debug(toolDir + "\\test.test" + " - File Deleted!");
                }
                catch (Exception ex)
                {
                    logger.Fatal(ex.Message);
                    wtc.WriteRedLine("[FATAL ERROR] " + ex.Message);
                    Console.ReadKey();
                    Environment.Exit(8);
                }
                #endregion

                #region ToolSupport
                //This seciton needs to get improved as we add more tool support;
                //Currently going to check for PSEXEC, will need to validate more as we use more.

                //IDEA MIRROR SUPPORT;
                //DOWNLOAD TOOLS NEEDED VIA A MIRROR AND VERIFY MD5

                //DEFINE TOOLS IN INI?
                if (!File.Exists(toolDir + "\\psexec.exe"))
                {
                    //PSEXEC is missing;
                    logger.Warn("Unable to find psexec in the following location [" + toolDir + "\\psexec.exe]");
                    logger.Warn("Any applications that use PSEXEC will not function!");
                    bPsexecMissing = true;
                    wtc.WriteYellowLine("[STARTUP] PSEXEC is missing from the Tools directory. Please make sure the exe is in the given path, or change the \"ToolDir\" path in your ini to where PSEXEC exists");
                    wtc.WriteYellowLine("[WARNING] Program will continue, any application that uses PSEXEC as the install driver will not function till this is resolved");
                }
            }
            catch (Exception ex)
            {
                wtc.WriteRedLine("[FATAL ERROR] " + ex.Message);
                logger.Fatal(ex.Message);
                Console.ReadKey();
                Environment.Exit(2);
            }
            #endregion
        }
示例#46
0
 /// <summary>
 /// Logs a debug message.
 /// This is an informational message, that is useful when debugging.
 /// </summary>
 /// <param name="message">The message to be logged.</param>
 public static void Debug(string message)
 {
     Configure();
     log.Debug(message);
 }
示例#47
0
文件: App.xaml.cs 项目: jameshy/else
        private void OnStart(object sender, StartupEventArgs startupEventArgs)
        {
            // create logger
            _logger = LogManager.GetLogger("app");

            // handle unhandled exceptions
            SetupUnhandledExceptionHandlers();

            // setup dependency injection
            SetupAutoFac();

            using (var scope = Container.BeginLifetimeScope()) {
                // handle installer events
                var updater = scope.Resolve<Updater>();
                updater.HandleEvents();

                // just in case we brutally terminate our process, cleanup trayicon and updater
                AppDomain.CurrentDomain.ProcessExit += (o, args) =>
                {
                    _trayIcon?.Dispose();
                    updater.Dispose();
                };

                // quit the app if we could not create the mutex, another instance is already running
                if (!CreateMutex()) {
                    _logger.Debug("Refusing to start, another instance is already running");
                    Current.Shutdown();
                    return;
                }

                // ensure data directories exist
                var paths = scope.Resolve<Paths>();
                try {
                    paths.Setup();
                }
                catch (FileNotFoundException notFound) {
                    // paths not found (e.g. %appdata%\Else could not be found)
                    // fatal error
                    Debug.Fail(notFound.Message);
                    Current.Shutdown();
                }

                var settings = scope.Resolve<Settings>();
                try {
                    settings.Setup();
                }
                catch (FileNotFoundException notFound) {
                    Debug.Fail(notFound.Message);
                    Current.Shutdown();
                }

                // initialize themes and scan the disk for themes
                var themeManager = scope.Resolve<ThemeManager>();
                try {
                    themeManager.InitializeDefaultTheme();
                }
                catch {
                    Debug.Fail("bad base theme");
                    Current.Shutdown();
                }
                themeManager.ScanForThemes(paths.GetAppPath("Themes"), false);
                themeManager.ScanForThemes(paths.GetUserPath("Themes"), true);
                themeManager.ApplyThemeFromSettings();

                // create LauncherWindow (we create it now because we need its window handle to register hotkeys and create the tray icon)
                var launcherWindow = scope.Resolve<LauncherWindow>();

                // setup message pump
                var messagePump = scope.Resolve<Win32MessagePump>();
                messagePump.Setup(launcherWindow);

                // only do the following if the app is running directly (not launched from simulator)
                if (!RunningFromSimulator) {
                    // only initialize plugins and trayicon if we are directly running the app (e.g. not running inside the theme editor)

                    var pluginManager = scope.Resolve<PluginManager>();
                    pluginManager.DiscoverPlugins();
                    _trayIcon = scope.Resolve<TrayIcon>();
                    _trayIcon.Setup();

                    // show splash screen on the first run
                    if (settings.User.FirstLaunch) {
                        var splashScreen = scope.Resolve<SplashScreenWindow>();
                        splashScreen.ShowWindow();
                        settings.User.FirstLaunch = false;
                        settings.Save();
                    }
                    scope.Resolve<Updater>().BeginAutoUpdates();
                }
            }
            // trigger custom OnStartupComplete event, this is used by the theme editor.
            OnStartupComplete?.Invoke(this, EventArgs.Empty);
        }
示例#48
0
        private void Submit_ClickAsync(object sender, EventArgs e)
        {
            logger = LogManager.GetCurrentClassLogger();
            logger.Debug("Click Submit");


            this.CurrentTask.Show();
            this.TaskStep.Show();
            this.progressBar1.Show();

            for (int i = 0; i < TheJobTaskTable.Rows.Count; i++)
            {
                TaskStep.Text = TheJobTaskTable.Rows[i][1].ToString() + ".   " + TheJobTaskTable.Rows[i][5].ToString();


                //---------------------------------- External Task ------------------------------------------
                if (TheJobTaskTable.Rows[i][3].ToString().Equals("False"))
                {
                    if (TheJobTaskTable.Rows[i][2].Equals("External_Command"))
                    {
                        String fileString = TheJobTaskTable.Rows[i][4].ToString();
                        JSON   fileJSON   = JsonConvert.DeserializeObject <JSON>(fileString);

                        //----------------------Default = YES-------------------


                        if (fileJSON.Default.Equals("Yes"))
                        {
                            logger = LogManager.GetCurrentClassLogger();
                            logger.Debug("User Verify File");
                            if (MessageBox.Show("Do you want to verify if your file has the correct data?", "Verify Data", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                TaskStep.Text = "Waiting for Resume...";
                                logger        = LogManager.GetCurrentClassLogger();
                                logger.Debug("User Chose Verify File");
                                // user clicked yes
                                if (!Open.OpenAppVerify(FilePath.Text))
                                {
                                    MessageBox.Show("Please reselect your file", "MESSAGE");
                                    return;
                                }
                            }
                            else
                            {
                                logger = LogManager.GetCurrentClassLogger();
                                logger.Debug("User Chose Not To Verify");
                            }
                        }

                        //----------------------Default = YES END-------------------

                        //----------------------Default = NO--------------------
                        else
                        {
                            if (fileJSON.Default.Equals("No"))
                            {
                                logger = LogManager.GetCurrentClassLogger();
                                logger.Debug("Oppening External App");
                                if (!Open.OpenJson(fileJSON.App))
                                {
                                    MessageBox.Show("unable to call external command", "ERROR");
                                    return;
                                }
                                Task.Delay(10000).Wait();
                            }

                            ThreadStart progressBarThreadStart = () =>
                            {
                                progressBar1.Invoke(new Action(() =>
                                {
                                    progressBar1.Value = 0;
                                }));
                                while (progressBar1.Value < 100)
                                {
                                    progressBar1.Invoke((MethodInvoker) delegate()
                                    {
                                        if (!Open.complete)
                                        {
                                            progressBar1.Value += 1;
                                        }
                                        else
                                        {
                                            progressBar1.Value = progressBar1.Maximum;
                                        }
                                    });

                                    Thread.Sleep(80);
                                }

                                Thread.Sleep(1000);
                                progressBar1.Invoke(new Action(() =>
                                {
                                    progressBar1.Value = 0;
                                }));
                            };

                            Thread progressBarThread = new Thread(progressBarThreadStart);
                            progressBarThread.Start();
                            //await Task.Run(() =>
                            //{
                            //    progressBar1.Invoke(new Action(() =>
                            //    {
                            //        progressBar1.Value = 0;
                            //    }));
                            //    while (progressBar1.Value < 100)
                            //    {

                            //        progressBar1.Invoke((MethodInvoker)delegate ()
                            //        {

                            //            if (!Open.complete)
                            //            {
                            //                progressBar1.Value += 1;

                            //            }
                            //            else
                            //            {
                            //                progressBar1.Value = progressBar1.Maximum;
                            //            }
                            //        });

                            //        Thread.Sleep(80);

                            //    }

                            //    Thread.Sleep(1000);
                            //    progressBar1.Invoke(new Action(() =>
                            //    {
                            //        progressBar1.Value = 0;
                            //    }));


                            //});
                        }

                        //----------------------Default = NO END--------------------

                        //-----------------30 SEC AUTOMATED MESSAGE--------------------

                        var result = AutoClosingMessageBox.Show(
                            text: "Do you want to continue?",
                            caption: "Continue",
                            timeout: 30000,
                            buttons: MessageBoxButtons.YesNo,
                            defaultResult: DialogResult.Yes);
                        if (result == DialogResult.Yes)
                        {
                        }
                        else
                        {
                            return;
                        }

                        //-----------------30 SEC AUTOMATED MESSAGE END--------------------
                    }
                    //----------------EXTRERNAL COMMAND END-----------------------------
                }



                //----------------Internal Task---------------------------
                else if (TheJobTaskTable.Rows[i][3].ToString().Equals("True"))
                {
                    //---------------- Excel Format Validation --------------------

                    if (TheJobTaskTable.Rows[i][2].Equals("Excel_Validation"))
                    {
                        string filePath     = FilePath.Text;
                        string templatePath = TheJobTaskTable.Rows[i][4].ToString();


                        Boolean ErrorFound = false; //true when found an error

                        ThreadStart progressBarThreadStart = () =>
                        {
                            progressBar1.Invoke(new Action(() =>
                            {
                                progressBar1.Value = 0;
                            }));
                            while (progressBar1.Value < 100)
                            {
                                progressBar1.Invoke((MethodInvoker) delegate()
                                {
                                    if (!Compare.complete & ErrorFound == false)
                                    {
                                        progressBar1.Value += 1;
                                    }
                                    else
                                    {
                                        progressBar1.Value = progressBar1.Maximum;
                                    }
                                });

                                Thread.Sleep(80);
                            }

                            Thread.Sleep(1500);

                            progressBar1.Invoke(new Action(() =>
                            {
                                progressBar1.Value = 0;
                            }));
                        };


                        Thread progressBarThread = new Thread(progressBarThreadStart);
                        progressBarThread.Start();


                        try
                        {
                            logger = LogManager.GetCurrentClassLogger();
                            logger.Debug("Validating user's file with template");

                            CheckExcellProcesses();
                            Compare.compare(GetExcelRange(filePath), GetExcelRange(templatePath), templatePath);

                            KillExcel();
                        }

                        catch (Exception ce)
                        { KillExcel();
                          ErrorFound = true;
                          MessageBox.Show("File can not be found", "ERROR");
                          logger = LogManager.GetCurrentClassLogger();
                          logger.Error(ce, "File can not be found"); }



                        if (Error == true)
                        {
                            logger = LogManager.GetCurrentClassLogger();
                            logger.Debug("program exit with a validation error.");
                            return;
                        }
                    }

                    //-----------------EXCEL VALIDATION END--------------------------------



                    //---------------- SQL_SP_ImportData ------------------------------

                    if (TheJobTaskTable.Rows[i][2].Equals("SQL_SP_ImportData") & Error == false)
                    {
                        logger = LogManager.GetCurrentClassLogger();
                        logger.Debug("Calling SQL_SP_ImportData");
                        ThreadStart progressBarThreadStart = () =>
                        {
                            progressBar1.Invoke(new Action(() =>
                            {
                                progressBar1.Value = 0;
                            }));
                            while (progressBar1.Value < 100)
                            {
                                progressBar1.Invoke((MethodInvoker) delegate()
                                {
                                    if (!Compare.complete)
                                    {
                                        progressBar1.Value += 1;
                                    }
                                    else
                                    {
                                        progressBar1.Value = progressBar1.Maximum;
                                    }
                                });

                                Thread.Sleep(80);
                                Application.DoEvents();
                            }

                            Thread.Sleep(1500);
                            progressBar1.Invoke(new Action(() =>
                            {
                                progressBar1.Value = 0;
                            }));
                        };

                        Thread progressBarThread = new Thread(progressBarThreadStart);
                        progressBarThread.Start();

                        String SQL_SP_ImportDataString = TheJobTaskTable.Rows[i][4].ToString();
                        JSON   SQL_SP_ImportDataJSON   = JsonConvert.DeserializeObject <JSON>(SQL_SP_ImportDataString);
                        try {
                            CheckExcellProcesses();
                            Compare.SQL_SP_ImportData(GetExcelRange(FilePath.Text), SQL_SP_ImportDataJSON);
                            KillExcel();
                            if (Error == true)
                            {
                                KillExcel();
                                return;
                            }
                        }
                        catch (Exception ce)
                        {
                            KillExcel();
                            logger = LogManager.GetCurrentClassLogger();
                            logger.Error(ce, "File Not Found in SQL_SP_ImportData");
                            MessageBox.Show("File cannot be found", "ERROR");
                            return;
                        }
                    }

                    //------------------SQL_SP_ImportData END------------------------------


                    //-------------------- SQL_SP ------------------------------------

                    if (TheJobTaskTable.Rows[i][2].Equals("SQL_SP") & Error == false)
                    {
                        logger = LogManager.GetCurrentClassLogger();
                        logger.Debug("Calling SQL_SP");
                        ThreadStart progressBarThreadStart = () =>
                        {
                            progressBar1.Invoke(new Action(() =>
                            {
                                progressBar1.Value = 0;
                            }));
                            while (progressBar1.Value < 100)
                            {
                                progressBar1.Invoke((MethodInvoker) delegate()
                                {
                                    if (!Compare.complete)
                                    {
                                        progressBar1.Value += 1;
                                    }
                                    else
                                    {
                                        progressBar1.Value = progressBar1.Maximum;
                                    }
                                });

                                Thread.Sleep(80);
                            }

                            Thread.Sleep(1000);
                            progressBar1.Invoke(new Action(() =>
                            {
                                progressBar1.Value = 0;
                            }));
                        };

                        Thread progressBarThread = new Thread(progressBarThreadStart);
                        progressBarThread.Start();

                        String SQL_SPString = TheJobTaskTable.Rows[i][4].ToString();
                        JSON   SQL_SPJSON   = JsonConvert.DeserializeObject <JSON>(SQL_SPString);

                        try
                        {
                            Compare.SQL_SP(SQL_SPJSON);
                            if (Error == true)
                            {
                                return;
                            }
                        }
                        catch (Exception se)
                        {
                            logger = LogManager.GetCurrentClassLogger();
                            logger.Error(se, "Calling SQL_SP failed");
                            MessageBox.Show("Failed to call SQL_SP.", "ERROR");
                            return;
                        }
                        //-------------------- SQL_SP END ------------------------------------
                    }

                    //-------------------------INTERNAL TASK END----------------------------
                }
                //--------------------------END-----------------------------------------
            }
            Thread.Sleep(1500);

            MessageBox.Show("Your file has been successfully submitted!", "Success");
            TaskStep.Text = "All Tasks Finished";
            //this.Close();
        }
示例#49
0
        // GET: Movies/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }

#if DEBUG
            logger = NLog.LogManager.GetLogger("rule1");
            logger.Debug("\nDebug Log\n" + movie);
#endif
            return View(movie);
        }
示例#50
0
        public static void Log(object message, Type type, ErrorLevel logType = ErrorLevel.Info)
        {
            switch (logType)
            {
            case ErrorLevel.Info:
            {
                _logger.Info(message);

                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Write($"[{logType.ToString()}] ");
                Console.ResetColor();
                Console.WriteLine(message);
                break;
            }

            case ErrorLevel.Warning:
            {
                _logger.Warn(message);
#if DEBUG
                lock (ConsoleSync)
                {
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.Write($"[{logType.ToString()}] ");
                    Console.ResetColor();
                    Console.WriteLine(message);
                }
#endif
                break;
            }

            case ErrorLevel.Error:
            {
                _logger.Error(message);
#if DEBUG
                lock (ConsoleSync)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write($"[{logType.ToString()}] ");
                    Console.ResetColor();
                    Console.WriteLine(message);
                }
#endif
                break;
            }

            case ErrorLevel.Debug:
            {
#if DEBUG
                _logger.Debug(message);

                lock (ConsoleSync)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write($"[{logType.ToString()}] ");
                    Console.ResetColor();
                    Console.WriteLine(message);
                }
#endif
                break;
            }
            }
        }
示例#51
0
        public void OnFault(RunContext context, uint currentIteration, StateModel stateModel, Fault[] faultData)
        {
            logger.Debug(">> OnFault");

            if (Fault != null)
            {
                Fault(context, currentIteration, stateModel, faultData);
            }

            logger.Debug("<< OnFault");
        }
		protected async Task<SynchronizationReport> ApplyConflictOnDestinationAsync(ConflictItem conflict, string destination,
		                                                                            string localServerUrl, Logger log)
		{
			log.Debug("File '{0}' is in conflict with destination version from {1}. Applying conflict on destination", FileName,
			          destination);

			var destinationRavenFileSystemClient = new RavenFileSystemClient(destination);
			try
			{
				var version = conflict.RemoteHistory.Last().Version;
				var serverId = conflict.RemoteHistory.Last().ServerId;
				var history = new List<HistoryItem>(conflict.RemoteHistory);
				history.RemoveAt(conflict.RemoteHistory.Count - 1);

				await
					destinationRavenFileSystemClient.Synchronization.ApplyConflictAsync(FileName, version, serverId, history,
					                                                                    localServerUrl);
			}
			catch (Exception ex)
			{
				log.WarnException(string.Format("Failed to apply conflict on {0} for file '{1}'", destination, FileName), ex);
			}

			return new SynchronizationReport(FileName, FileETag, SynchronizationType)
				       {
					       Exception = new SynchronizationException(string.Format("File {0} is conflicted", FileName)),
				       };
		}
 public void Initialize(LogFactory log)
 {
     _logger = log.GetCurrentClassLogger();
     _logger.Debug("Initialize");
 }
示例#54
0
        // PERFORM_MUTATION
        //
        private void performMutation(DataElement obj, long curr)
        {
            logger.Debug("performMutation(curr=" + curr + ")");

            var sizeRelation = obj.relations.getFromSizeRelation();

            if (sizeRelation == null)
            {
                logger.Error("Error, sizeRelation == null, unable to perform mutation.");
                return;
            }

            var objOf = sizeRelation.Of;

            if (objOf == null)
            {
                logger.Error("Error, sizeRelation.Of == null, unable to perform mutation.");
                return;
            }

            n = (int)curr;

            obj.MutatedValue   = null;
            objOf.MutatedValue = null;

            // make sure the data hasn't changed somewhere along the line
            //if (originalDataLength != size)
            //PopulateValues(obj);

            // Set all mutation flags up front
            obj.mutationFlags   |= DataElement.MUTATE_OVERRIDE_RELATIONS;
            obj.mutationFlags   |= DataElement.MUTATE_OVERRIDE_TYPE_TRANSFORM;
            objOf.mutationFlags |= DataElement.MUTATE_OVERRIDE_RELATIONS;
            objOf.mutationFlags |= DataElement.MUTATE_OVERRIDE_TYPE_TRANSFORM;

            // keep size indicator the same
            obj.MutatedValue = new Variant(obj.Value);

            byte[]    data    = objOf.Value.Value;
            BitStream newData = new BitStream();

            if (n <= 0)
            {
                objOf.MutatedValue = new Variant(new byte[0]);
                return;
            }
            else if (n < data.Length)
            {
                // shorten the size
                for (int i = 0; i < n; ++i)
                {
                    newData.WriteByte(data[i]);
                }
            }
            else if (data.Length == 0)
            {
                // fill in with A's
                for (int i = 0; i < n; ++i)
                {
                    newData.WriteByte((byte)('A'));
                }
            }
            else
            {
                // wrap the data to fill size
                logger.Debug("Expanding data from " + data.Length + " to " + n + " bytes");
                while (newData.LengthBytes < n)
                {
                    if ((newData.LengthBytes + data.Length) < n)
                    {
                        newData.WriteBytes(data);
                    }
                    else
                    {
                        for (int i = 0; i < data.Length && newData.LengthBytes < n; ++i)
                        {
                            newData.WriteByte(data[i]);
                        }
                    }
                }
            }

            logger.Debug("Setting MutatedValue");
            objOf.MutatedValue = new Variant(newData);
        }
示例#55
0
        public static void CreateTweetForm(Logger logger)
        {
            try
            {
                var twitterPersistenceService = new TwitterPersistenceService(logger);

                if (!ProductivityUiHelper.IsTwitterAccountConfigured(twitterPersistenceService, logger))
                {
                    MessageBox.Show(
                        PluginResources
                            .ProductivityShareViewPartAction_Execute_In_order_to_share_the_result_you_need_to_configure_your_twitter_account);
                    return;
                }
                var productivityService = new ProductivityService(logger);

                if (productivityService.TotalNumberOfCharacters < Constants.MinimumNumberOfCharacters)
                {
                    MessageBox.Show(
                        string.Format(
                            PluginResources
                                .ProductivityShareViewPartAction_Execute_In_order_to_share_your_score_you_need_to_translate_at_least__0__characters,
                            Constants.MinimumNumberOfCharacters.ToString("N0")));
                    return;
                }

                var leaderboardApi = new LeaderboardApi(twitterPersistenceService);
                var versioningService = new VersioningService(leaderboardApi);
                var tweetMessageService = new TweetMessageService(versioningService);
                var leaderBoardShareService = new LeaderboardShareService(leaderboardApi, twitterPersistenceService);
                var twitterShareService = new TwitterShareService(twitterPersistenceService, tweetMessageService);
                var shareService = new ShareService(productivityService, twitterShareService, leaderBoardShareService,
                    versioningService);

                if (!leaderboardApi.IsAlive())
                {
                    MessageBox.Show(PluginResources.TweetFactory_CreateTweet_SDL_Leaderboard_could_not_be_reached__Please_check_your_internet_connectivity_and_try_again);
                    return;
                }

                if (!twitterShareService.IsAlive())
                {
                    MessageBox.Show(PluginResources.TweetFactory_CreateTweet_Twitter_could_not_be_reached__Please_check_your_internet_connectivity_and_try_again_);
                    return;
                }

                if (!versioningService.IsPluginVersionCompatibleWithLeaderboardVersion())
                {
                    MessageBox.Show(
                        string.Format(
                            "In order to share you score you need to update the plugin to the version {0}. Please download the latest version from Open Exchange.",
                            shareService.LeaderboardVersion));
                    return;
                }

                using (var tf = new TweetForm(shareService,tweetMessageService, productivityService))
                {
                    tf.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                logger.Debug(ex, "Unexpected exception when opening the share score");
                throw;
            }
        }
示例#56
0
        private async Task _PlayAsync(string deviceUniqueId, CancellationTokenSource cancellationTokenSource, int attempts = 0)
        {
            Device device = await FindDeviceAsync(deviceUniqueId);

            if (device == null)
            {
                await Task.FromException(new NullReferenceException("Couldn't get device with uniqueId " + deviceUniqueId)).ConfigureAwait(false);
            }
            else
            {
                int            deviceInstanceId = SnapSettings.DetermineInstanceId(deviceUniqueId, device.Index);
                DeviceSettings deviceSettings   = SnapSettings.GetDeviceSettings(deviceUniqueId);
                if (deviceInstanceId != -1)
                {
                    // update device's last seen:
                    deviceSettings.LastSeen = DateTime.Now;
                    SnapSettings.SaveDeviceSettings(deviceUniqueId, deviceSettings);

                    StringBuilder   stdError = new StringBuilder();
                    string          lastLine = "";
                    Action <string> stdOut   = (line) =>
                    {
                        lastLine = line; // we only care about the last line from the output - in case there's an error (snapclient should probably be sending these to stderr though)
                    };
                    string resampleArg = "";
                    if (string.IsNullOrEmpty(deviceSettings.ResampleFormat) == false)
                    {
                        resampleArg = string.Format("--sampleformat {0}:0", deviceSettings.ResampleFormat);
                    }
                    string command = string.Format("-h {0} -p {1} -s {2} -i {3} --sharingmode={4} {5}", SnapSettings.Server, SnapSettings.PlayerPort, device.Index, deviceInstanceId, deviceSettings.ShareMode.ToString().ToLower(), resampleArg);
                    Logger.Debug("Snapclient command: {0}", command);
                    CommandTask <CommandResult> task = Cli.Wrap(_SnapClient())
                                                       .WithArguments(command)
                                                       .WithStandardOutputPipe(PipeTarget.ToDelegate(stdOut))
                                                       .ExecuteAsync(cancellationTokenSource.Token);

                    Logger.Debug("Snapclient PID: {0}", task.ProcessId);
                    ChildProcessTracker.AddProcess(Process.GetProcessById(task.ProcessId)); // this utility helps us make sure the player process doesn't keep going if our process is killed / crashes
                    try
                    {
                        await task;
                    }
                    catch (CliWrap.Exceptions.CommandExecutionException e)
                    {
                        OnSnapClientErrored?.Invoke();
                        // add type to ShowNotification (level?), show notification with type and print log at type level
                        Snapcast.Instance.ShowNotification("Snapclient error", _BuildErrorMessage(device, lastLine));
                        // todo: parse WASAPI error code here and provide human friendly output
                        Logger.Error("Snapclient exited with non-zero exit code. Exception:");
                        Logger.Error(e.Message);
                        DevicePlayStateChanged?.Invoke(deviceUniqueId, EState.Stopped);
                        m_ActivePlayers.Remove(deviceUniqueId);

                        // settings might have changed while we were playing - refetch them
                        DeviceSettings nDeviceSettings = SnapSettings.GetDeviceSettings(deviceUniqueId);
                        if (nDeviceSettings.AutoRestartOnFailure == true && (attempts <= nDeviceSettings.RestartAttempts || nDeviceSettings.RestartAttempts == 0))
                        {
                            m_ActivePlayers.Add(deviceUniqueId, cancellationTokenSource);
                            DevicePlayStateChanged?.Invoke(deviceUniqueId, EState.Playing);
                            await _PlayAsync(deviceUniqueId, cancellationTokenSource, attempts + 1).ConfigureAwait(false);
                        }
                    }
                }
            }
            DevicePlayStateChanged?.Invoke(deviceUniqueId, EState.Stopped);
            m_ActivePlayers.Remove(deviceUniqueId);
        }
示例#57
0
        public void ContactSync(Logger Logger, IConfiguration config, IAuthenticationProvidor authProvidor, IAzureADFunctions azureAdFunctions, IOnPremADHelper onPremAdHelper, IOnPremAdFunctions onPremAdFunctions, ActiveDirectoryClient AzureClientSession)
        {
            //Get Entry into On-prem Active Directory Contacts OU.
            DirectoryEntry _OnPremContactsDirectoryEntry = onPremAdHelper.GetADDirectoryEntry(config.FQDomainName, config.ContactsDestinationOUDN, Logger);

            //Gather User Objects for the Work we intend to do later:
            Group _AzureUsersgroup = azureAdFunctions.GetADGroup(AzureClientSession, config.AzureADUserGroup, Logger);
            if (_AzureUsersgroup != null)
            {
                List<Tuple<string, IDirectoryObject>> _AzureGroupMembers = azureAdFunctions.GetAdGroupMembers(_AzureUsersgroup, config, Logger);

                if (_AzureGroupMembers.Any(members => members.Item1 == "user"))
                {
                    List<IUser> _AzureGroupUsers = _AzureGroupMembers.Where(member => member.Item1.Equals("user"))
                                                                     .Select(member => member.Item2)
                                                                     .Select(member => member as IUser)
                                                                     .ToList();

                    List<DirectoryEntry> _OnPremContactObjects = onPremAdFunctions.GetOUContactObjects(config.FQDomainName, config.ContactsDestinationOUDN, onPremAdHelper, Logger);

                    #region Add Contact Objects to AD Contacts OU
                    //foreach user in Cloud check if they reside onprem and add them if they dont.

                    if (config.AllowCreationOfADObjects)
                    {
                        Dictionary<string, IUser> azureUsers = _AzureGroupUsers.Where(x => x.Mail != null)
                                                                               .ToDictionary(x => x.Mail.ToLower(), x => x);

                        foreach (string OnPremUser in _OnPremContactObjects.Where(x => x.Properties["Mail"].Value != null)
                                                                           .Select(x => x.Properties["Mail"].Value.ToString()))
                        {
                            azureUsers.Remove(OnPremUser.ToLower());
                        }

                        int CreatedUsers = onPremAdFunctions.CreateADUserContacts(Logger, config, _OnPremContactsDirectoryEntry, onPremAdHelper, azureUsers);

                        Logger.Debug(String.Format("Created {0} user(s) in On-Prem Active Directory", CreatedUsers.ToString()));
                        Console.WriteLine("Created {0} user(s) in On-Prem Active Directory", CreatedUsers.ToString());

                    }
                    #endregion

                    #region Delete Contact Objects from AD OU
                    //foreach user onprem check if they reside in cloud - delete them from AD if they dont (Make this over-rideable with a key)
                    if (config.AllowDeletionOfADObjects)
                    {
                        Dictionary<string, DirectoryEntry> onpremUsers = _OnPremContactObjects.Where(y => y.Properties["Mail"].Value != null)
                                                                                              .ToDictionary(y => y.Properties["Mail"].Value.ToString().ToLower(), y => y);

                        foreach (string AzureUser in _AzureGroupUsers.Where(y => y.Mail != null)
                                                                     .Select(y => y.Mail.ToLower()))
                        {
                            onpremUsers.Remove(AzureUser.ToLower());
                        }

                        int DeletedUsers = onPremAdFunctions.DeleteADContacts(Logger, config, _OnPremContactsDirectoryEntry, onpremUsers);

                        Logger.Debug(String.Format("Deleted {0} user(s) in On-Prem Active Directory", DeletedUsers.ToString()));
                        Console.WriteLine("Deleted {0} user(s) in On-Prem Active Directory", DeletedUsers.ToString());
                    }
                }
                else
                {
                    Console.WriteLine("Could not find any USER objects in group {0}", config.AzureADUserGroup);
                    Logger.Error(String.Format("Could not find any USER objects in group {0}", config.AzureADUserGroup));
                }

            }
            else
            {
                Console.WriteLine("Could not find Group in Azure ({0} to enumerate users from", config.AzureADUserGroup);
                Logger.Error(String.Format("Could not find Group in Azure ({0} to enumerate users from", config.AzureADUserGroup));
            }

            //Close AD Directory Entry Handle
            onPremAdHelper.DisposeADDirectoryEntry(_OnPremContactsDirectoryEntry, Logger);

            Console.WriteLine("Contact Creation/Deletion complete - Changes will be reflected on Office365 Sync on Next Dir-Sync Cycle but may not appear in Address book until the following day.");
            Logger.Debug(@"Contact Creation/Deletion complete - Changes will be reflected on Office365 upon next DirSync.");

            #endregion
        }
示例#58
0
 public static void Debug(string message, params object[] args)
 {
     _logger.Debug(message, args);
 }
示例#59
0
        public RegistryBase(string hivePath)
        {
            if (hivePath == null)
            {
                throw new ArgumentNullException("hivePath cannot be null");
            }

            if (!File.Exists(hivePath))
            {
                throw new FileNotFoundException();
            }

            var fileStream = new FileStream(hivePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var binaryReader = new BinaryReader(fileStream);

            binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);

            FileBytes = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);

            binaryReader.Close();
            fileStream.Close();

            _logger = LogManager.GetLogger(hivePath);

            if (!HasValidSignature())
            {
                _logger.Error("'{0}' is not a Registry hive (bad signature)", hivePath);

                throw new Exception($"'{hivePath}' is not a Registry hive (bad signature)");
            }

            HivePath = hivePath;

            _logger.Debug("Set HivePath to {0}", hivePath);

            Initialize();
        }
示例#60
0
 public void Debug(string msg)
 {
     _log.Debug(msg);
 }