예제 #1
0
        internal BusBuilderConfiguration()
        {
            Debugging = new BusBuilderDebuggingConfiguration();
            LargeMessageStorageConfiguration = new LargeMessageStorageConfiguration();
            Router = new DestinationPerMessageTypeRouter();

            Logger = new NullLogger();
            Compressor = new NullCompressor();
        }
예제 #2
0
 public void SimpleLogTest()
 {
     var myLogger = new NullLogger();
     myLogger.Debug("FooBar");
     myLogger.Warning("FooBar");
     myLogger.Error("FooBar");
     myLogger.Error(new Exception(), "FooBar");
     myLogger.Info("FooBar");
     myLogger.Info("FooBar", "Bar");
     Assert.AreEqual(myLogger.IsDebugEnabled, myLogger.IsDebugEnabled); // We don't care about the actual value.
 }
예제 #3
0
 public MemoryStrategy()
 {
     Logger = new NullLogger();
 }
        public static string Authorize(this BaseProtocolClient ingoing_mail_client, MailServerSettings settings, int wait_timeout = 5000, ILogger log = null)
        {
            if (log == null)
            {
                log = new NullLogger();
            }

            string last_response;

            IAsyncResult async_res;

            switch (settings.EncryptionType)
            {
            case EncryptionType.SSL:
                log.Debug("SSL connecting to {0}", settings.Url);
                async_res = ingoing_mail_client.BeginConnectSsl(settings.Url, settings.Port,
                                                                result =>
                                                                log.Debug("OnConnectSSL: completed {0}",
                                                                          result.IsCompleted ? "SUCCESS" : "FAIL"));
                if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout))
                {
                    log.Warn("BeginConnectSsl: operation timeout = {0} seconds",
                             TimeSpan.FromMilliseconds(wait_timeout).Seconds);
                    ingoing_mail_client.EndAsyncOperation(async_res);
                    async_res.AsyncWaitHandle.Close();
                    throw new TimeoutException();
                }
                last_response = ingoing_mail_client.EndAsyncOperation(async_res);

                break;

            default:
                log.Debug("PLAIN connecting to {0}", settings.Url);
                async_res = ingoing_mail_client.BeginConnectPlain(settings.Url, settings.Port, result =>
                                                                  log.Debug(
                                                                      "OnConnect: completed {0}",
                                                                      result
                                                                      .IsCompleted
                                                                                                           ? "SUCCESS"
                                                                                                           : "FAIL"));

                if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout))
                {
                    log.Warn("BeginConnect: operation timeout = {0} seconds",
                             TimeSpan.FromMilliseconds(wait_timeout).Seconds);
                    ingoing_mail_client.EndAsyncOperation(async_res);
                    async_res.AsyncWaitHandle.Close();
                    throw new TimeoutException();
                }
                last_response = ingoing_mail_client.EndAsyncOperation(async_res);

                if (ingoing_mail_client is SmtpClient &&
                    (settings.AuthenticationType != SaslMechanism.None ||
                     settings.EncryptionType == EncryptionType.StartTLS))
                {
                    last_response = ingoing_mail_client.SendEhloHelo();
                }

                if (settings.EncryptionType == EncryptionType.StartTLS)
                {
                    log.Debug("StartTLS {0}", settings.Url);
                    last_response = ingoing_mail_client.StartTLS(settings.Url);
                }

                break;
            }

            if (settings.AuthenticationType == SaslMechanism.Login)
            {
                log.Debug("Login as {0} with secret password", settings.AccountName);
                async_res = ingoing_mail_client.BeginLogin(settings.AccountName, settings.AccountPass, result =>
                                                           log.Debug("OnLogin: completed {0}",
                                                                     result.IsCompleted ? "SUCCESS" : "FAIL"));

                if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout))
                {
                    log.Warn("BeginLogin: operation timeout = {0} seconds", TimeSpan.FromMilliseconds(wait_timeout).Seconds);
                    ingoing_mail_client.EndAsyncOperation(async_res);
                    async_res.AsyncWaitHandle.Close();
                    throw new TimeoutException();
                }

                last_response = ingoing_mail_client.EndAsyncOperation(async_res);
            }
            else
            {
                if (ingoing_mail_client is SmtpClient && settings.AuthenticationType == SaslMechanism.None)
                {
                    log.Debug("Authentication not required");
                    return(last_response);
                }

                log.Debug("Authenticate as {0} with secret password", settings.AccountName);
                async_res = ingoing_mail_client.BeginAuthenticate(settings.AccountName, settings.AccountPass, settings.AuthenticationType, result =>
                                                                  log.Debug("OnAuthenticate: completed {0}",
                                                                            result.IsCompleted ? "SUCCESS" : "FAIL"));

                if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout))
                {
                    log.Warn("BeginAuthenticate: operation timeout = {0} seconds", TimeSpan.FromMilliseconds(wait_timeout).Seconds);
                    ingoing_mail_client.EndAsyncOperation(async_res);
                    async_res.AsyncWaitHandle.Close();
                    throw new TimeoutException();
                }

                last_response = ingoing_mail_client.EndAsyncOperation(async_res);
            }

            return(last_response);
        }
예제 #5
0
 public PictureDatabase(PicDbContext ctx)
 {
     _ctx   = ctx;
     Logger = new NullLogger <PictureDatabase>();
 }
예제 #6
0
 static LoggerManager()
 {
     Instance = new NullLogger();
 }
        public void GetTypeTest()
        {
            var logger = new NullLogger();

            Assert.IsNotNull(logger.ForType <NullLoggerTests>());
        }
예제 #8
0
        public new void SetUp()
        {
            _shippingSettings = new ShippingSettings
            {
                UseCubeRootMethod = true,
                ConsiderAssociatedProductsDimensions = true,
                ShipSeparatelyOneItemEach            = false
            };

            _shippingMethodRepository = new Mock <IRepository <ShippingMethod> >();
            _warehouseRepository      = new Mock <IRepository <Warehouse> >();
            _logger = new NullLogger();
            _productAttributeParser  = new Mock <IProductAttributeParser>();
            _checkoutAttributeParser = new Mock <ICheckoutAttributeParser>();

            var cacheManager = new TestCacheManager();

            _productService = new Mock <IProductService>();

            _eventPublisher = new Mock <IEventPublisher>();
            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            var customerService = new Mock <ICustomerService>();
            var loger           = new Mock <ILogger>();
            var webHelper       = new Mock <IWebHelper>();

            _catalogSettings = new CatalogSettings();
            var pluginService = new PluginService(_catalogSettings, customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, webHelper.Object);

            _pickupPluginManager   = new PickupPluginManager(pluginService, _shippingSettings);
            _shippingPluginManager = new ShippingPluginManager(pluginService, _shippingSettings);

            _localizationService     = new Mock <ILocalizationService>();
            _addressService          = new Mock <IAddressService>();
            _genericAttributeService = new Mock <IGenericAttributeService>();
            _priceCalcService        = new Mock <IPriceCalculationService>();

            _store = new Store {
                Id = 1
            };
            _storeContext = new Mock <IStoreContext>();
            _storeContext.Setup(x => x.CurrentStore).Returns(_store);

            _shoppingCartSettings = new ShoppingCartSettings();

            _shippingService = new ShippingService(_addressService.Object,
                                                   cacheManager,
                                                   _checkoutAttributeParser.Object,
                                                   _eventPublisher.Object,
                                                   _genericAttributeService.Object,
                                                   _localizationService.Object,
                                                   _logger,
                                                   _pickupPluginManager,
                                                   _priceCalcService.Object,
                                                   _productAttributeParser.Object,
                                                   _productService.Object,
                                                   _shippingMethodRepository.Object,
                                                   _warehouseRepository.Object,
                                                   _shippingPluginManager,
                                                   _storeContext.Object,
                                                   _shippingSettings,
                                                   _shoppingCartSettings);
        }
예제 #9
0
        private static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            var options = new Options();

            if (!CommandLine.Parser.Default.ParseArgumentsStrict(args, options,
                                                                 () => Console.WriteLine("Bad command line parameters.")))
            {
                ShowAnyKey();
                return;
            }

            try
            {
                var reloadList = new Dictionary <int, List <int> >();

                if (!string.IsNullOrEmpty(options.PathToJson) && File.Exists(options.PathToJson))
                {
                    using (var streamReader = new StreamReader(options.PathToJson))
                    {
                        using (var reader = new JsonTextReader(streamReader))
                        {
                            var jObject = JObject.Load(reader);

                            if (jObject["data"] == null || !jObject["data"].Any())
                            {
                                Console.WriteLine("[ERROR] json tasks not found. Array is empty.");

                                ShowAnyKey();
                                return;
                            }

                            var results = jObject["data"].ToList().GroupBy(
                                p => Convert.ToInt32(p["id_mailbox"]),
                                p => Convert.ToInt32(p["id"]),
                                (key, g) => new { MailboxId = key, Ids = g.ToList() });

                            foreach (var result in results)
                            {
                                if (reloadList.ContainsKey(result.MailboxId))
                                {
                                    continue;
                                }

                                reloadList.Add(result.MailboxId, result.Ids);
                            }
                        }
                    }
                }
                else
                {
                    if (options.MailboxId < 0)
                    {
                        Console.WriteLine("[ERROR] MailboxId invalid.");

                        ShowAnyKey();
                        return;
                    }

                    if (options.MessageId < 0)
                    {
                        Console.WriteLine("[ERROR] MailboxId invalid.");

                        ShowAnyKey();
                        return;
                    }


                    reloadList.Add(options.MailboxId, new List <int> {
                        options.MessageId
                    });
                }

                foreach (var reloadItem in reloadList)
                {
                    MailClient client = null;

                    try
                    {
                        var mailboxId = reloadItem.Key;

                        Console.WriteLine("\r\nSearching account with id {0}", mailboxId);

                        var mailbox = GetMailBox(mailboxId);

                        if (mailbox == null)
                        {
                            Console.WriteLine("[ERROR] Account not found.");
                            ShowAnyKey();
                            return;
                        }

                        var messageIds = reloadItem.Value;

                        foreach (var messageId in messageIds)
                        {
                            Console.WriteLine("\r\nSearching message with id {0}", messageId);

                            if (messageId < 0)
                            {
                                Console.WriteLine("[ERROR] MessageId not setup.");
                                continue;
                            }

                            var storedMessage = GetMail(mailbox, messageId);

                            if (storedMessage == null)
                            {
                                Console.WriteLine("[ERROR] Message not found.");
                                continue;
                            }

                            var messageUid = storedMessage.Uidl;

                            if (mailbox.Imap)
                            {
                                var uidlStucture = ParserImapUidl(messageUid);
                                if (uidlStucture.folderId != MailFolder.Ids.inbox)
                                {
                                    Console.WriteLine("Only inbox messages are supported for downloading.");
                                    continue;
                                }
                            }

                            var certificatePermit = ConfigurationManager.AppSettings["mail.certificate-permit"] !=
                                                    null &&
                                                    Convert.ToBoolean(
                                ConfigurationManager.AppSettings["mail.certificate-permit"]);

                            var log = new NullLogger();

                            if (client == null)
                            {
                                client = new MailClient(mailbox, CancellationToken.None,
                                                        certificatePermit: certificatePermit);
                            }

                            MimeMessage mimeMessage;

                            try
                            {
                                mimeMessage = client.GetInboxMessage(messageUid);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("[ERROR] Failed GetInboxMessage(\"{0}\") Exception: {1}", messageUid, e);
                                continue;
                            }

                            var message = ConvertToMailMessage(mimeMessage,
                                                               new MailFolder(MailFolder.Ids.inbox, ""),
                                                               storedMessage.IsNew, storedMessage.ChainId, storedMessage.StreamId, log);

                            if (message == null)
                            {
                                Console.WriteLine("[ERROR] Failed ConvertToMailMessage(\"{0}\")", messageUid);
                                continue;
                            }

                            if (!storedMessage.From.Equals(MailUtil.NormalizeStringForMySql(message.From)) ||
                                !storedMessage.To.Equals(MailUtil.NormalizeStringForMySql(message.To)) ||
                                !storedMessage.Subject.Equals(MailUtil.NormalizeStringForMySql(message.Subject)))
                            {
                                Console.WriteLine("storedMessage.From = '{0}'", storedMessage.From);
                                Console.WriteLine("message.From = '{0}'",
                                                  MailUtil.NormalizeStringForMySql(message.From));

                                Console.WriteLine("storedMessage.To = '{0}'", storedMessage.To);
                                Console.WriteLine("message.To = '{0}'",
                                                  MailUtil.NormalizeStringForMySql(message.To));

                                Console.WriteLine("storedMessage.Subject = '{0}'", storedMessage.Subject);
                                Console.WriteLine("message.Subject = '{0}'",
                                                  MailUtil.NormalizeStringForMySql(message.Subject));

                                Console.WriteLine("[ERROR] Stored message not equals to server message");
                                continue;
                            }

                            if (storedMessage.Attachments.Any() && message.Attachments.Any())
                            {
                                var newAttachments = new List <MailAttachment>();

                                foreach (var attachment in message.Attachments)
                                {
                                    var storedAttachment =
                                        storedMessage.Attachments.FirstOrDefault(
                                            a =>
                                            (!string.IsNullOrEmpty(a.fileName) &&
                                             a.fileName.Equals(attachment.fileName,
                                                               StringComparison.InvariantCultureIgnoreCase)) ||
                                            !string.IsNullOrEmpty(a.contentId) &&
                                            a.contentId.Equals(attachment.contentId,
                                                               StringComparison.InvariantCultureIgnoreCase) ||
                                            !string.IsNullOrEmpty(a.contentLocation) &&
                                            a.contentLocation.Equals(attachment.contentLocation,
                                                                     StringComparison.InvariantCultureIgnoreCase));

                                    if (storedAttachment == null)
                                    {
                                        continue;
                                    }

                                    attachment.fileName   = storedAttachment.fileName;
                                    attachment.storedName = storedAttachment.storedName;
                                    attachment.fileNumber = storedAttachment.fileNumber;
                                    attachment.streamId   = storedAttachment.streamId;
                                    attachment.mailboxId  = storedAttachment.mailboxId;
                                    attachment.tenant     = storedAttachment.tenant;
                                    attachment.user       = storedAttachment.user;

                                    newAttachments.Add(attachment);
                                }

                                message.Attachments = newAttachments;
                            }

                            if (!TryStoreMailData(message, mailbox, log))
                            {
                                Console.WriteLine("[ERROR] Failed to store mail data");
                                continue;
                            }

                            Console.WriteLine("[SUCCESS] Mail \"{0}\" data was reloaded", messageId);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    finally
                    {
                        if (client != null)
                        {
                            client.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            ShowAnyKey();
        }
예제 #10
0
 public WithLoggingMixin()
 {
     Logger = new NullLogger();
     Errors = new List <Exception>();
 }
        public static void FixEncodingIssues(this MimeMessage mimeMessage, ILogger logger = null)
        {
            if (logger == null)
            {
                logger = new NullLogger();
            }

            try
            {
                foreach (var mimeEntity in mimeMessage.BodyParts)
                {
                    var textPart = mimeEntity as TextPart;

                    if (textPart == null ||
                        textPart.ContentObject == null ||
                        textPart.ContentObject.Encoding != ContentEncoding.Default)
                    {
                        continue;
                    }

                    try
                    {
                        string charset;
                        using (var stream = new MemoryStream())
                        {
                            textPart.ContentObject.DecodeTo(stream);
                            var bytes = stream.ToArray();
                            charset = EncodingTools.DetectCharset(bytes);
                        }

                        if (!string.IsNullOrEmpty(charset) &&
                            (textPart.ContentType == null ||
                             string.IsNullOrEmpty(textPart.ContentType.Charset) ||
                             textPart.ContentType.Charset != charset))
                        {
                            var encoding = EncodingTools.GetEncodingByCodepageName(charset);

                            if (encoding == null)
                            {
                                continue;
                            }

                            var newText = textPart.GetText(charset);

                            textPart.SetText(encoding, newText);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Warn("MimeMessage.FixEncodingIssues->ImproveBodyEncoding: {0}", ex.Message);
                    }
                }

                if (mimeMessage.Headers.Contains(HeaderId.From))
                {
                    var fromParsed = mimeMessage.From.FirstOrDefault();
                    if (fromParsed != null && !string.IsNullOrEmpty(fromParsed.Name))
                    {
                        var fromHeader = mimeMessage.Headers.FirstOrDefault(h => h.Id == HeaderId.From);
                        fromHeader.FixEncodingIssues(logger);
                    }
                }

                if (!mimeMessage.Headers.Contains(HeaderId.Subject))
                {
                    return;
                }

                var subjectHeader = mimeMessage.Headers.FirstOrDefault(h => h.Id == HeaderId.Subject);
                subjectHeader.FixEncodingIssues(logger);
            }
            catch (Exception ex)
            {
                logger.Warn("MimeMessage.FixEncodingIssues: {0}", ex.Message);
            }
        }
예제 #12
0
        public static void InstallPackage(IReadOnlyList <string> packages, bool quiet)
        {
            Init();
            RemoteWalkContext context = new RemoteWalkContext();

            ILogger            logger       = new NullLogger();
            SourceCacheContext cacheContext = new SourceCacheContext
            {
                IgnoreFailedSources = true
            };

            foreach (SourceRepository repo in Repos)
            {
                if (!repo.PackageSource.IsLocal)
                {
                    context.RemoteLibraryProviders.Add(new SourceRepositoryDependencyProvider(repo, logger, cacheContext));
                }
                else
                {
                    context.LocalLibraryProviders.Add(new SourceRepositoryDependencyProvider(repo, logger, cacheContext));
                }
            }

            Paths.User.Content.CreateDirectory();
            RemoteDependencyWalker            walker                 = new RemoteDependencyWalker(context);
            HashSet <Package>                 remainingPackages      = new HashSet <Package>(packages.Select(x => new Package(x, VersionRange.All)));
            HashSet <Package>                 encounteredPackages    = new HashSet <Package>();
            List <string>                     templateRoots          = new List <string>();
            Dictionary <string, int>          latestRoundEncountered = new Dictionary <string, int>();
            Dictionary <string, NuGetVersion> currentVersion         = new Dictionary <string, NuGetVersion>();
            int round = -1;

            while (remainingPackages.Count > 0)
            {
                ++round;
                HashSet <Package> nextRound = new HashSet <Package>();

                foreach (Package package in remainingPackages)
                {
                    string name = package.PackageId;
                    GraphNode <RemoteResolveResult> result = walker.WalkAsync(new LibraryRange(name, package.Version, LibraryDependencyTarget.All), NuGetFramework.AnyFramework, "", RuntimeGraph.Empty, true).Result;
                    RemoteMatch     match           = result.Item.Data.Match;
                    PackageIdentity packageIdentity = new PackageIdentity(match.Library.Name, match.Library.Version);

                    nextRound.UnionWith(result.Item.Data.Dependencies.Select(x => new Package(x.Name, x.LibraryRange.VersionRange)));

                    VersionFolderPathContext versionFolderPathContext = new VersionFolderPathContext(
                        packageIdentity,
                        Paths.User.PackageCache,
                        new NullLogger(),
                        packageSaveMode: PackageSaveMode.Defaultv3,
                        xmlDocFileSaveMode: XmlDocFileSaveMode.Skip,
                        fixNuspecIdCasing: true,
                        normalizeFileNames: true);

                    if (match.Library.Version == null)
                    {
                        if (!quiet)
                        {
                            throw new Exception($"Package '{package.PackageId}' version {package.Version} could not be located.");
                        }
                        else
                        {
                            continue;
                        }
                    }

                    string source = Path.Combine(Paths.User.PackageCache, match.Library.Name, match.Library.Version.ToString());

                    if (!source.Exists() && match.Provider != null)
                    {
                        PackageExtractor.InstallFromSourceAsync(
                            stream => match.Provider.CopyToAsync(match.Library, stream, CancellationToken.None),
                            versionFolderPathContext,
                            CancellationToken.None).Wait();

                        string target = Path.Combine(Paths.User.Content, match.Library.Name);
                        target.CreateDirectory();
                        target = Path.Combine(target, match.Library.Version.ToString());
                        target.CreateDirectory();
                        Paths.Copy(source, target);
                        target.Delete("*.nupkg", "*.nupkg.*");

                        string nuspec = target.EnumerateFiles("*.nuspec").FirstOrDefault();

                        //If there's a nuspec, figure out whether this package is a template and walk the dependency graph
                        if (nuspec?.Exists() ?? false)
                        {
                            XDocument doc = XDocument.Load(nuspec);
                            IReadOnlyList <PackageType> types = NuspecUtility.GetPackageTypes(doc.Root.Element(XName.Get("metadata", "http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd")), false);
                            //If the thing we got is a template...
                            if (types.Any(x => string.Equals(x.Name, "template", StringComparison.OrdinalIgnoreCase)))
                            {
                                templateRoots.Add(target);
                            }
                            else
                            {
                                latestRoundEncountered[match.Library.Name] = round;

                                NuGetVersion currentVer;
                                if (!currentVersion.TryGetValue(match.Library.Name, out currentVer) || match.Library.Version.CompareTo(currentVersion) > 0)
                                {
                                    currentVersion[match.Library.Name] = match.Library.Version;
                                }
                            }
                        }
                    }
                }

                encounteredPackages.UnionWith(remainingPackages);
                nextRound.ExceptWith(encounteredPackages);
                remainingPackages = nextRound;
            }

            foreach (KeyValuePair <string, int> package in latestRoundEncountered.OrderByDescending(x => x.Value))
            {
                string packageName = package.Key;
                string version     = currentVersion[packageName].ToString();

                foreach (string path in Path.Combine(Paths.User.Content, packageName, version).EnumerateFiles($"{package.Key}.dll", SearchOption.AllDirectories))
                {
                    if (path.IndexOf($"{Path.DirectorySeparatorChar}lib{Path.DirectorySeparatorChar}", StringComparison.OrdinalIgnoreCase) < 0
#if !NET451
                        || (path.IndexOf($"{Path.DirectorySeparatorChar}netstandard1.", StringComparison.OrdinalIgnoreCase) < 0 &&
                            path.IndexOf($"{Path.DirectorySeparatorChar}netcoreapp1.", StringComparison.OrdinalIgnoreCase) < 0)
#else
                        || path.IndexOf($"{Path.DirectorySeparatorChar}netstandard1.", StringComparison.OrdinalIgnoreCase) < 0
#endif
                        )
                    {
                        continue;
                    }

#if !NET451
                    Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
#else
                    Assembly asm = Assembly.LoadFile(path);
#endif
                    foreach (Type type in asm.GetTypes())
                    {
                        SettingsLoader.Components.Register(type);
                    }
                }
            }

            TemplateCache.Scan(templateRoots);
        }
예제 #13
0
 public ProductControllerTests()
 {
     _logger   = new NullLogger <ProductController>();
     _repoMock = new Mock <IProductRepository>();
 }
예제 #14
0
        static void Init()
        {
            lock (syncRoot)
            {
                HostMessage m = new HostMessage();
                m.Command = HostCommand.Init;

                if (state == RunState.Created)
                {
                    IEnumerable <TypeNameReference> names = null;
                    m.Message = "";

                    LogProviderBase log = null;
                    try
                    {
                        ConfigurationManager.Instance.Bootstrap();
                        ConfigurationManager.Instance.Initialize();
                        ConfigurationManager.Instance.Start();
                        if (ConfigurationManager.Instance.State == RunState.Running)
                        {
                            LogManager.Instance.Bootstrap();
                            LogManager.Instance.Initialize();
                            LogManager.Instance.Start();
                            if (LogManager.Instance.State == RunState.Running)
                            {
                                log = LogManager.Instance.GetProvider(typeof(Program));
                            }
                            if (log == null)
                            {
                                log = new NullLogger(typeof(Program));
                            }

                            ConfigurationProviderBase prov = ConfigurationManager.Instance.GetProvider();
                            if (prov != null)
                            {
                                ConfigurationParameter param = prov.Get(typeof(Program), "hostList");
                                if (param != null)
                                {
                                    string[] values = param.Value as string[];
                                    if (values != null && values.Length > 0)
                                    {
                                        HashSet <TypeNameReference> tps = new HashSet <TypeNameReference>();
                                        foreach (string s in values)
                                        {
                                            TypeNameReference cur = TypeNameReference.Parse(s);
                                            if (cur != null)
                                            {
                                                tps.Add(cur);
                                            }
                                            else
                                            {
                                                log.Log(5, "Failed to parse TypeName for: " + s);
                                            }
                                        }
                                        if (tps.Count > 0)
                                        {
                                            names = tps;
                                        }
                                    }
                                    else
                                    {
                                        m.Message = "Failed to get configuration value";
                                        log.Log(1000, m.Message);
                                    }
                                }
                                else
                                {
                                    m.Message = "Failed to get configuration parameter: hostList";
                                    log.Log(1000, m.Message);
                                }
                            }
                            else
                            {
                                m.Message = "Failed to get configuration provider";
                                log.Log(1000, m.Message);
                            }
                        }
                        else
                        {
                            m.Message = "Failed to initialize using local file, quitting (" + AppContext.BaseDirectory + ")";
                            if (log != null)
                            {
                                log.Log(1000, m.Message);
                            }
                        }
                    }
                    catch
                    {
                        m.Message = "Failed to initialize using config, falling back to local file";
                        if (log != null)
                        {
                            log.Log(1000, m.Message);
                        }
                    }

                    if (names != null)
                    {
                        HostingManager.Instance.Initialize(names);
                        state = HostingManager.Instance.State;
                        if (state == RunState.Initialized)
                        {
                            m.Message = "success " + m.Message;
                            if (log != null)
                            {
                                log.Log(0, m.Message);
                            }
                        }
                        else
                        {
                            m.Message = "failed " + m.Message;
                            if (log != null)
                            {
                                log.Log(1000, m.Message);
                            }
                        }
                    }
                    else
                    {
                        state     = HostingManager.Instance.State;
                        m.Message = "failed " + m.Message;
                        if (log != null)
                        {
                            log.Log(1000, m.Message);
                        }
                    }
                }
                else
                {
                    state     = HostingManager.Instance.State;
                    m.Message = "ignored";
                }

                comms.Send(m);
            }
        }
예제 #15
0
 /// <summary>
 /// Initializes static members of the NullLogger class.
 /// </summary>
 static NullLogger()
 {
     Instance = new NullLogger();
 }
예제 #16
0
        public async Task <StressTestServerStartResult> StartAsync()
        {
            var framework    = PlatformServices.Default.Runtime.RuntimeType;
            var fullTestName = $"{_testMethodName}.{_testName}.{framework}";

            fullTestName = fullTestName.Replace('_', '.');

            _logger = LogUtility.LoggerFactory.CreateLogger(fullTestName);

            var baseAddress = $"http://localhost:{_port}/";

            var p = new DeploymentParameters(PathHelper.GetTestAppFolder(_testName), _serverType, RuntimeFlavor.Clr, RuntimeArchitecture.x86)
            {
                SiteName = _testName,
                ApplicationBaseUriHint = baseAddress,
                PublishTargetFramework = "dnx451"
            };

            ILogger deployerLogger;

            if (StressConfig.Instance.DeployerLogging)
            {
                deployerLogger = _logger;
            }
            else
            {
                deployerLogger = new NullLogger();
            }

            _applicationDeployer = ApplicationDeployerFactory.Create(p, deployerLogger);
            var deploymentResult = _applicationDeployer.Deploy();

            baseAddress = deploymentResult.ApplicationBaseUri;

            _logger.LogInformation($"Test project is set up at {deploymentResult.WebRootLocation}");

            var result = new StressTestServerStartResult
            {
                ServerHandle = this
            };
            var serverVerificationClient = new HttpClient
            {
                BaseAddress = new Uri(baseAddress)
            };

            HttpResponseMessage response = null;

            for (int i = 0; i < 20; ++i)
            {
                try
                {
                    _logger.LogInformation($"Pinging {serverVerificationClient.BaseAddress} to ensure server booted properly");
                    response = await serverVerificationClient.GetAsync(serverVerificationClient.BaseAddress);

                    break;
                }
                catch (TimeoutException)
                {
                    _logger.LogError("Http client timeout.");
                    break;
                }
                catch (Exception)
                {
                    _logger.LogInformation("Failed to ping server. Retrying...");
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    continue;
                }
            }

            result.SuccessfullyStarted = false;
            if (response != null)
            {
                _logger.LogInformation($"Response {response.StatusCode}");

                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("Server started successfully");
                    result.SuccessfullyStarted = true;
                    ClientFactory = () => new RequestTrackingHttpClient(baseAddress, _metricCollector);
                }
            }

            return(result);
        }
예제 #17
0
        public void WhenCallingDebugShouldEnterDebugMethod()
        {
            NullLogger logger = new NullLogger();

            logger.Debug("Test String");
        }
        public void NullLogger_IsEnabled_ReturnsTrue(LogLevel logLevel)
        {
            var logger = new NullLogger <RulesEngine>();

            logger.IsEnabled(logLevel).Equals(true);
        }
예제 #19
0
        public void WhenCallingTraceShouldEnterTraceMethod()
        {
            NullLogger logger = new NullLogger();

            logger.Trace("Test String");
        }
예제 #20
0
 public FixtureBase()
 {
     TestLogger = new NullLogger();
 }
예제 #21
0
        public void WhenCallingInfoShouldEnterInfoMethod()
        {
            NullLogger logger = new NullLogger();

            logger.Info("Test String");
        }
예제 #22
0
 /// <summary>
 ///     Initializes static members of the LogFactory class.
 /// </summary>
 static LogFactory()
 {
     var logger = new NullLogger();
     BuildLogger = type => logger;
 }
예제 #23
0
        public void WhenCallingWarnShouldEnterWarnMethod()
        {
            NullLogger logger = new NullLogger();

            logger.Warn("Test String");
        }
예제 #24
0
 /// <summary>
 /// Creates a new instance of a Managed NamedPipe client. Doesn't connect to anything yet, just setups the values.
 /// </summary>
 public ManagedNamedPipeClient()
 {
     _buffer = new byte[PipeFrame.MAX_SIZE];
     Logger  = new NullLogger();
     _stream = null;
 }
예제 #25
0
        public void WhenCallingErrorShouldEnterErrorMethod()
        {
            NullLogger logger = new NullLogger();

            logger.Error("Test String", new Exception());
        }
예제 #26
0
        /// <summary>
        /// Mount a new %Dokan Volume.
        /// This function block until the device is unmount.
        /// </summary>
        /// <param name="operations">Instance of <see cref="IDokanOperations"/> that will be called for each request made by the kernel.</param>
        /// <param name="mountPoint">Mount point. Can be <c>M:\\</c> (drive letter) or <c>C:\\mount\\dokan</c> (path in NTFS).</param>
        /// <param name="mountOptions"><see cref="DokanOptions"/> features enable for the mount.</param>
        /// <param name="threadCount">Number of threads to be used internally by %Dokan library. More thread will handle more event at the same time.</param>
        /// <param name="version">Version of the dokan features requested (Version "123" is equal to %Dokan version 1.2.3).</param>
        /// <param name="timeout">Max timeout in ms of each request before dokan give up.</param>
        /// <param name="uncName">UNC name used for network volume.</param>
        /// <param name="allocationUnitSize">Allocation Unit Size of the volume. This will behave on the file size.</param>
        /// <param name="sectorSize">Sector Size of the volume. This will behave on the file size.</param>
        /// <param name="logger"><see cref="ILogger"/> that will log all DokanNet debug informations.</param>
        /// <exception cref="DokanException">If the mount fails.</exception>
        public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions,
                                 int threadCount, int version, TimeSpan timeout, string uncName = null, int allocationUnitSize = 512,
                                 int sectorSize = 512, ILogger logger = null)
        {
            if (logger == null)
            {
#if TRACE
                logger = new ConsoleLogger("[DokanNet] ");
#else
                logger = new NullLogger();
#endif
            }

            var dokanOperationProxy = new DokanOperationProxy(operations, logger);

            var dokanOptions = new DOKAN_OPTIONS
            {
                Version            = (ushort)version,
                MountPoint         = mountPoint,
                UNCName            = string.IsNullOrEmpty(uncName) ? null : uncName,
                ThreadCount        = (ushort)threadCount,
                Options            = (uint)mountOptions,
                Timeout            = (uint)timeout.TotalMilliseconds,
                AllocationUnitSize = (uint)allocationUnitSize,
                SectorSize         = (uint)sectorSize
            };

            var dokanOperations = new DOKAN_OPERATIONS
            {
                ZwCreateFile         = dokanOperationProxy.ZwCreateFileProxy,
                Cleanup              = dokanOperationProxy.CleanupProxy,
                CloseFile            = dokanOperationProxy.CloseFileProxy,
                ReadFile             = dokanOperationProxy.ReadFileProxy,
                WriteFile            = dokanOperationProxy.WriteFileProxy,
                FlushFileBuffers     = dokanOperationProxy.FlushFileBuffersProxy,
                GetFileInformation   = dokanOperationProxy.GetFileInformationProxy,
                FindFiles            = dokanOperationProxy.FindFilesProxy,
                FindFilesWithPattern = dokanOperationProxy.FindFilesWithPatternProxy,
                SetFileAttributes    = dokanOperationProxy.SetFileAttributesProxy,
                SetFileTime          = dokanOperationProxy.SetFileTimeProxy,
                DeleteFile           = dokanOperationProxy.DeleteFileProxy,
                DeleteDirectory      = dokanOperationProxy.DeleteDirectoryProxy,
                MoveFile             = dokanOperationProxy.MoveFileProxy,
                SetEndOfFile         = dokanOperationProxy.SetEndOfFileProxy,
                SetAllocationSize    = dokanOperationProxy.SetAllocationSizeProxy,
                LockFile             = dokanOperationProxy.LockFileProxy,
                UnlockFile           = dokanOperationProxy.UnlockFileProxy,
                GetDiskFreeSpace     = dokanOperationProxy.GetDiskFreeSpaceProxy,
                GetVolumeInformation = dokanOperationProxy.GetVolumeInformationProxy,
                Mounted              = dokanOperationProxy.MountedProxy,
                Unmounted            = dokanOperationProxy.UnmountedProxy,
                GetFileSecurity      = dokanOperationProxy.GetFileSecurityProxy,
                SetFileSecurity      = dokanOperationProxy.SetFileSecurityProxy,
                FindStreams          = dokanOperationProxy.FindStreamsProxy
            };

            DokanStatus status = (DokanStatus)NativeMethods.DokanMain(ref dokanOptions, ref dokanOperations);
            if (status != DokanStatus.Success)
            {
                throw new DokanException(status);
            }
        }
예제 #27
0
        public void WhenCallingFatalShouldEnterFatalMethod()
        {
            NullLogger logger = new NullLogger();

            logger.Fatal("Test String", new Exception());
        }
예제 #28
0
 static LoggerManager()
 {
     Instance = new NullLogger();
 }
예제 #29
0
        public static void ChangeAttachedFileLinksAddresses(this MailDraft draft, ILogger log = null)
        {
            if (log == null)
            {
                log = new NullLogger();
            }

            var doc = new HtmlDocument();

            doc.LoadHtml(draft.HtmlBody);

            var linkNodes = doc.DocumentNode.SelectNodes("//a[contains(@class,'mailmessage-filelink-link')]");

            if (linkNodes == null)
            {
                return;
            }

            var fileStorageService = new FileStorageServiceController();

            var setLinks = new List <Tuple <string, string> >();

            foreach (var linkNode in linkNodes)
            {
                var fileId   = linkNode.Attributes["data-fileid"].Value;
                var objectId = "file_" + fileId;

                linkNode.Attributes["class"].Remove();       // 'mailmessage-filelink-link'
                linkNode.Attributes["data-fileid"].Remove(); // 'data-fileid'

                var setLink = setLinks.SingleOrDefault(x => x.Item1 == fileId);
                if (setLink != null)
                {
                    linkNode.SetAttributeValue("href", setLink.Item2);
                    log.Info("ChangeAttachedFileLinks() Change file link href: {0}", fileId);
                    continue;
                }

                var aceCollection = new AceCollection
                {
                    Entries = new ItemList <string> {
                        objectId
                    },
                    Aces = new ItemList <AceWrapper>
                    {
                        new AceWrapper
                        {
                            SubjectId    = FileConstant.ShareLinkId,
                            SubjectGroup = true,
                            Share        = draft.FileLinksShareMode
                        }
                    }
                };

                fileStorageService.SetAceObject(aceCollection, false);
                log.Info("ChangeAttachedFileLinks() Set public accees to file: {0}", fileId);
                var sharedInfo =
                    fileStorageService.GetSharedInfo(new ItemList <string> {
                    objectId
                })
                    .Find(r => r.SubjectId == FileConstant.ShareLinkId);
                linkNode.SetAttributeValue("href", sharedInfo.SubjectName);
                log.Info("ChangeAttachedFileLinks() Change file link href: {0}", fileId);
                setLinks.Add(new Tuple <string, string>(fileId, sharedInfo.SubjectName));
            }

            linkNodes = doc.DocumentNode.SelectNodes("//div[contains(@class,'mailmessage-filelink')]");
            foreach (var linkNode in linkNodes)
            {
                linkNode.Attributes["class"].Remove();
            }

            draft.HtmlBody = doc.DocumentNode.OuterHtml;
        }
예제 #30
0
        public void GetAllResources_WhenAllResourcesRequested_ExpectAllResourcesIncludingHidden(
            DbContextOptions <ConfigurationDbContext> options)
        {
            var visibleIdentityResource = CreateIdentityTestResource();
            var visibleApiResource      = CreateApiTestResource();

            var hiddenIdentityResource = new IdentityResource
            {
                Name = Guid.NewGuid().ToString(),
                ShowInDiscoveryDocument = false
            };

            var hiddenApiResource = new ApiResource
            {
                Name   = Guid.NewGuid().ToString(),
                Scopes = new List <Scope> {
                    new Scope {
                        Name = Guid.NewGuid().ToString(),
                        ShowInDiscoveryDocument = false
                    }
                }
            };

            using (var context =
                       new ConfigurationDbContext(options, StoreOptions))
            {
                context.IdentityResources
                .Add(visibleIdentityResource.ToEntity());

                context.ApiResources.Add(visibleApiResource.ToEntity());

                context.IdentityResources
                .Add(hiddenIdentityResource.ToEntity());

                context.ApiResources.Add(hiddenApiResource.ToEntity());
                context.SaveChanges();
            }

            Resources resources;

            using (var context =
                       new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ResourceStore(
                    context,
                    NullLogger <ResourceStore> .Create()
                    );

                resources = store.GetAllResourcesAsync().Result;
            }

            Assert.NotNull(resources);
            Assert.NotEmpty(resources.IdentityResources);
            Assert.NotEmpty(resources.ApiResources);

            Assert.Contains(resources.IdentityResources,
                            x => !x.ShowInDiscoveryDocument);

            Assert.Contains(resources.ApiResources,
                            x => !x.Scopes.Any(y => y.ShowInDiscoveryDocument));
        }
 public AuthorizeLoggedInUserAttribute()
 {
     Logger = new NullLogger();
 }
예제 #32
0
        public void Log_Test()
        {
            var logger = new NullLogger();

            logger.Log(() => new LogEntry(LoggingEventType.Debug, string.Empty));
        }
예제 #33
0
        public Service()
        {
            var logger = new NullLogger();

            _service = new ChatService(new WcfChatClientsProvider(logger), logger);
        }
예제 #34
0
        public new void SetUp()
        {
            _productService           = new Mock <IProductService>();
            _storeContext             = new Mock <IStoreContext>();
            _discountService          = new Mock <IDiscountService>();
            _categoryService          = new Mock <ICategoryService>();
            _manufacturerService      = new Mock <IManufacturerService>();
            _productAttributeParser   = new Mock <IProductAttributeParser>();
            _eventPublisher           = new Mock <IEventPublisher>();
            _localizationService      = new Mock <ILocalizationService>();
            _shippingMethodRepository = new Mock <IRepository <ShippingMethod> >();
            _warehouseRepository      = new Mock <IRepository <Warehouse> >();
            _shipmentService          = new Mock <IShipmentService>();
            _paymentService           = new Mock <IPaymentService>();
            _checkoutAttributeParser  = new Mock <ICheckoutAttributeParser>();
            _giftCardService          = new Mock <IGiftCardService>();
            _genericAttributeService  = new Mock <IGenericAttributeService>();
            _geoLookupService         = new Mock <IGeoLookupService>();
            _countryService           = new Mock <ICountryService>();
            _stateProvinceService     = new Mock <IStateProvinceService>();
            _eventPublisher           = new Mock <IEventPublisher>();
            _addressService           = new Mock <IAddressService>();
            _rewardPointService       = new Mock <IRewardPointService>();
            _orderService             = new Mock <IOrderService>();
            _webHelper                  = new Mock <IWebHelper>();
            _languageService            = new Mock <ILanguageService>();
            _priceFormatter             = new Mock <IPriceFormatter>();
            _productAttributeFormatter  = new Mock <IProductAttributeFormatter>();
            _shoppingCartService        = new Mock <IShoppingCartService>();
            _checkoutAttributeFormatter = new Mock <ICheckoutAttributeFormatter>();
            _customerService            = new Mock <ICustomerService>();
            _encryptionService          = new Mock <IEncryptionService>();
            _workflowMessageService     = new Mock <IWorkflowMessageService>();
            _customerActivityService    = new Mock <ICustomerActivityService>();
            _currencyService            = new Mock <ICurrencyService>();
            _affiliateService           = new Mock <IAffiliateService>();
            _vendorService              = new Mock <IVendorService>();
            _pdfService                 = new Mock <IPdfService>();
            _customNumberFormatter      = new Mock <ICustomNumberFormatter>();
            _rewardPointService         = new Mock <IRewardPointService>();

            _workContext = null;

            _store = new Store {
                Id = 1
            };

            _storeContext.Setup(x => x.CurrentStore).Returns(_store);

            _shoppingCartSettings = new ShoppingCartSettings();
            _catalogSettings      = new CatalogSettings();

            var cacheManager = new TestCacheManager();

            _currencySettings = new CurrencySettings();

            //price calculation service
            _priceCalcService = new PriceCalculationService(_catalogSettings, _currencySettings, _categoryService.Object,
                                                            _currencyService.Object, _discountService.Object, _manufacturerService.Object, _productAttributeParser.Object,
                                                            _productService.Object, cacheManager, _storeContext.Object, _workContext, _shoppingCartSettings);

            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            var loger = new Mock <ILogger>();

            var pluginService = new PluginService(_catalogSettings, _customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, _webHelper.Object);

            _paymentPluginManager  = new PaymentPluginManager(pluginService, null, _paymentSettings);
            _pickupPluginManager   = new PickupPluginManager(pluginService, _shippingSettings);
            _shippingPluginManager = new ShippingPluginManager(pluginService, _shippingSettings);
            _taxPluginManager      = new TaxPluginManager(pluginService, _taxSettings);

            //shipping
            _shippingSettings = new ShippingSettings
            {
                ActiveShippingRateComputationMethodSystemNames = new List <string>()
            };
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod");

            _logger           = new NullLogger();
            _customerSettings = new CustomerSettings();
            _addressSettings  = new AddressSettings();

            _shippingService = new ShippingService(_addressService.Object,
                                                   cacheManager,
                                                   _checkoutAttributeParser.Object,
                                                   _eventPublisher.Object,
                                                   _genericAttributeService.Object,
                                                   _localizationService.Object,
                                                   _logger,
                                                   _pickupPluginManager,
                                                   _priceCalcService,
                                                   _productAttributeParser.Object,
                                                   _productService.Object,
                                                   _shippingMethodRepository.Object,
                                                   _warehouseRepository.Object,
                                                   _shippingPluginManager,
                                                   _storeContext.Object,
                                                   _shippingSettings,
                                                   _shoppingCartSettings);

            //tax
            _taxSettings = new TaxSettings
            {
                ShippingIsTaxable = true,
                PaymentMethodAdditionalFeeIsTaxable = true,
                DefaultTaxAddressId = 10
            };

            _addressService.Setup(x => x.GetAddressById(_taxSettings.DefaultTaxAddressId)).Returns(new Address {
                Id = _taxSettings.DefaultTaxAddressId
            });

            _taxService = new TaxService(_addressSettings,
                                         _customerSettings,
                                         _addressService.Object,
                                         _countryService.Object,
                                         _genericAttributeService.Object,
                                         _geoLookupService.Object,
                                         _logger,
                                         _stateProvinceService.Object,
                                         cacheManager,
                                         _storeContext.Object,
                                         _taxPluginManager,
                                         _webHelper.Object,
                                         _workContext,
                                         _shippingSettings,
                                         _taxSettings);

            _rewardPointsSettings = new RewardPointsSettings();

            _orderTotalCalcService = new OrderTotalCalculationService(_catalogSettings,
                                                                      _checkoutAttributeParser.Object,
                                                                      _discountService.Object,
                                                                      _genericAttributeService.Object,
                                                                      _giftCardService.Object,
                                                                      _paymentService.Object,
                                                                      _priceCalcService,
                                                                      _rewardPointService.Object,
                                                                      _shippingPluginManager,
                                                                      _shippingService,
                                                                      _shoppingCartService.Object,
                                                                      _storeContext.Object,
                                                                      _taxService,
                                                                      _workContext,
                                                                      _rewardPointsSettings,
                                                                      _shippingSettings,
                                                                      _shoppingCartSettings,
                                                                      _taxSettings);

            _paymentSettings = new PaymentSettings
            {
                ActivePaymentMethodSystemNames = new List <string>
                {
                    "Payments.TestMethod"
                }
            };
            _orderSettings = new OrderSettings();

            _localizationSettings = new LocalizationSettings();

            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            _orderProcessingService = new OrderProcessingService(_currencySettings,
                                                                 _affiliateService.Object,
                                                                 _checkoutAttributeFormatter.Object,
                                                                 _countryService.Object,
                                                                 _currencyService.Object,
                                                                 _customerActivityService.Object,
                                                                 _customerService.Object,
                                                                 _customNumberFormatter.Object,
                                                                 _discountService.Object,
                                                                 _encryptionService.Object,
                                                                 _eventPublisher.Object,
                                                                 _genericAttributeService.Object,
                                                                 _giftCardService.Object,
                                                                 _languageService.Object,
                                                                 _localizationService.Object,
                                                                 _logger,
                                                                 _orderService.Object,
                                                                 _orderTotalCalcService,
                                                                 _paymentPluginManager,
                                                                 _paymentService.Object,
                                                                 _pdfService.Object,
                                                                 _priceCalcService,
                                                                 _priceFormatter.Object,
                                                                 _productAttributeFormatter.Object,
                                                                 _productAttributeParser.Object,
                                                                 _productService.Object,
                                                                 _rewardPointService.Object,
                                                                 _shipmentService.Object,
                                                                 _shippingPluginManager,
                                                                 _shippingService,
                                                                 _shoppingCartService.Object,
                                                                 _stateProvinceService.Object,
                                                                 _storeContext.Object,
                                                                 _taxService,
                                                                 _vendorService.Object,
                                                                 _webHelper.Object,
                                                                 _workContext,
                                                                 _workflowMessageService.Object,
                                                                 _localizationSettings,
                                                                 _orderSettings,
                                                                 _paymentSettings,
                                                                 _rewardPointsSettings,
                                                                 _shippingSettings,
                                                                 _taxSettings);
        }
예제 #35
0
        public void NullLogger_LogTrace()
        {
            var logger = new NullLogger();

            logger.LogTrace("hello");
        }
예제 #36
0
		/// <summary>
		/// Directs all logging output to the logger callback specified.
		/// </summary>
		/// <param name="logger">The logger to which all logging information should be directed.</param>
		public static void LogWith(Func<Type, ILog> logger)
		{
			var nullLogger = new NullLogger();
			configured = logger ?? (type => nullLogger);
		}
예제 #37
0
        public void NullLogger_LogError()
        {
            var logger = new NullLogger();

            logger.LogError(new Exception("hello"));
        }
        public void NullLogger_Log_DoesNotThrow()
        {
            var logger = new NullLogger <RulesEngine>();

            logger.Log(LogLevel.Critical, 1, "This is a critical message.");
        }
예제 #39
0
 public FixtureBase()
 {
     TestLogger = new NullLogger();
 }
예제 #40
0
        private static IKeysFinder CreateKeysFinder(IFileSystem fileSystem)
        {
            var logger = new NullLogger <KeysFinder>();

            return(new KeysFinder(logger, fileSystem));
        }
예제 #41
0
 /// <summary>
 /// Initializes static members of the NullLogger class.
 /// </summary>
 static NullLogger()
 {
     Instance = new NullLogger();
 }
예제 #42
0
 public void GetTypeTest()
 {
     var logger = new NullLogger();
     Assert.IsNotNull(logger.ForType<ConsoleLoggerTests>());
 }
예제 #43
0
        /// <summary>
        ///     Initializes static members of the LogFactory class.
        /// </summary>
        static LogFactory()
        {
            var logger = new NullLogger();

            BuildLogger = type => logger;
        }
		void RunUpEndpoint()
		{
			// OMITTED: No empty try-catch
			//try
			//{
				//this.Logger.Debug("1 RunUpEndpoint()");

				// Get configuration settings
				XDocument confDoc = XDocument.Load("SipEndpoint.config");
				this.SetAppLevelConfiguration(confDoc.Root);

				/*  Matching levels between:
				 *  -----------------------------|--------------------------------
				 *   Platform SDK logging levels | SIP Endpoint SDK logging levels
				 *  -----------------------------|--------------------------------
				 *    All = 0                    |       NA
				 *    Debug = 1                  |       4
				 *    Trace = 2                  |       3
				 *    Interaction = 3            |       2
				 *    Standard = 4               |       1
				 *    Alarm = 5                  |       0
				 *    None = 6                   |       NA
				 *  -----------------------------|--------------------------------
				 * 
				 *  SIP Endpoint SDK logging levels
				 *  ===============================
				 *   Fatal = 0
				 *   Error = 1
				 *   Warning = 2
				 *   Info = 3
				 *   Debug = 4
				 */

				if (this.enableLogging)
				{
					// Setup logger
					LogConfiguration logConf = new LogConfiguration();
					logConf.Verbose = VerboseLevel.All;
					logConf.Targets.Trace.IsEnabled = true;

					switch (this.logLevel)
					{
						case 0:
							logConf.Targets.Trace.Verbose = VerboseLevel.Alarm;
							break;
						case 1:
							logConf.Targets.Trace.Verbose = VerboseLevel.Standard;
							break;
						case 2:
							logConf.Targets.Trace.Verbose = VerboseLevel.Interaction;
							break;
						case 3:
							logConf.Targets.Trace.Verbose = VerboseLevel.Trace;
							break;
						case 4:
							logConf.Targets.Trace.Verbose = VerboseLevel.Debug;
							break;
					}

					FileConfiguration fileConf = new FileConfiguration(true, logConf.Targets.Trace.Verbose, "logs" + Path.DirectorySeparatorChar + this.logFile);
					fileConf.MessageHeaderFormat = MessageHeaderFormat.Medium;

					logConf.Targets.Files.Add(fileConf);

					this.endpointLogger = LoggerFactory.CreateRootLogger("SipEndpoint", logConf);
					this.Logger = this.endpointLogger.CreateChildLogger("QuickStart");

					this.endpoint = SipEndpoint.EndpointFactory.CreateSipEndpoint(this.endpointLogger);
				}
				else
				{
					// Setup NULL logger
					this.nullLogger = new NullLogger();
					this.Logger = this.nullLogger;
					this.endpoint = SipEndpoint.EndpointFactory.CreateSipEndpoint();
				}

				// OMITTED: Endpoint configuration

				this.provider = this.endpoint.Resolve("IEndpointPovider") as SipProvider;

				// Setup Endpoint Logger
				if (this.enableLogging)
					this.provider.SetEndpointLogger(this.endpointLogger);
				else
					this.provider.SetEndpointLogger(this.nullLogger);

				this.endpoint.ApplyConfiguration(confDoc.Root);

				// OMITTED:
				//this.endpoint.BeginActivate();

				// At this point the actual configuration can be updated and
				// Then the Endpoint can be started
				// The next two lines of the code are unnecessary if configuration
				// is not going to be changed

				// Get updated configuration settings
				//confDoc = XDocument.Load("SipEndpoint.config");
				//this.endpoint.ApplyConfiguration(confDoc.Root);

				// The actual SIP Endpoint Start
				// OMITTED:
				//this.endpoint.Start();
				//this.Logger.Debug("this.endpoint.Start()");
			
			// OMITTED: No empty try-catch
			//}
			//catch (Exception exception)
			//{
			//	//this.Logger.Debug("2 RunUpEndpoint()" + exception.Message);
			//	//System.Windows.Forms.MessageBox.Show(exception.Message);
			//}
		}
예제 #45
0
        /// <summary>
        /// Mount a new Dokan Volume.
        /// This function block until the device is unmount.
        /// if the mount fail throw is fiered with error information.
        /// </summary>
        /// <param name="operations">Instance of <see cref="IDokanOperations"/> that will be called for each request made by the kernel.</param>
        /// <param name="mountPoint">Mount point. Can be "M:\" (drive letter) or "C:\mount\dokan" (path in NTFS)</param>
        /// <param name="mountOptions"><see cref="DokanOptions"/> features enable for the mount</param>
        /// <param name="threadCount">Number of threads to be used internally by Dokan library. More thread will handle more event at the same time.</param>
        /// <param name="version">Version of the dokan features requested (Version "123" is equal to Dokan version 1.2.3)</param>
        /// <param name="timeout">Max timeout in ms of each request before dokan give up.</param>
        /// <param name="uncName">UNC name used for network volume</param>
        /// <param name="allocationUnitSize">Allocation Unit Size of the volume. This will behave on the file size.</param>
        /// <param name="sectorSize">Sector Size of the volume. This will behave on the file size.</param>
        /// <param name="logger"><see cref="ILogger"/> that will log all DokanNet debug informations</param>
        public static void Mount(this IDokanOperations operations, string mountPoint, DokanOptions mountOptions,
                                 int threadCount, int version, TimeSpan timeout, string uncName = null, int allocationUnitSize = 512,
                                 int sectorSize = 512, ILogger logger = null)
        {
#if TRACE
            if (logger == null)
            {
                logger = new ConsoleLogger("[DokanNet] ");
            }
#endif
            if (logger == null)
            {
                logger = new NullLogger();
            }

            var dokanOperationProxy = new DokanOperationProxy(operations, logger);

            var dokanOptions = new DOKAN_OPTIONS
            {
                Version            = (ushort)version,
                MountPoint         = mountPoint,
                UNCName            = string.IsNullOrEmpty(uncName) ? null : uncName,
                ThreadCount        = (ushort)threadCount,
                Options            = (uint)mountOptions,
                Timeout            = (uint)timeout.Milliseconds,
                AllocationUnitSize = (uint)allocationUnitSize,
                SectorSize         = (uint)sectorSize
            };

            var dokanOperations = new DOKAN_OPERATIONS
            {
                ZwCreateFile         = dokanOperationProxy.ZwCreateFileProxy,
                Cleanup              = dokanOperationProxy.CleanupProxy,
                CloseFile            = dokanOperationProxy.CloseFileProxy,
                ReadFile             = dokanOperationProxy.ReadFileProxy,
                WriteFile            = dokanOperationProxy.WriteFileProxy,
                FlushFileBuffers     = dokanOperationProxy.FlushFileBuffersProxy,
                GetFileInformation   = dokanOperationProxy.GetFileInformationProxy,
                FindFiles            = dokanOperationProxy.FindFilesProxy,
                FindFilesWithPattern = dokanOperationProxy.FindFilesWithPatternProxy,
                SetFileAttributes    = dokanOperationProxy.SetFileAttributesProxy,
                SetFileTime          = dokanOperationProxy.SetFileTimeProxy,
                DeleteFile           = dokanOperationProxy.DeleteFileProxy,
                DeleteDirectory      = dokanOperationProxy.DeleteDirectoryProxy,
                MoveFile             = dokanOperationProxy.MoveFileProxy,
                SetEndOfFile         = dokanOperationProxy.SetEndOfFileProxy,
                SetAllocationSize    = dokanOperationProxy.SetAllocationSizeProxy,
                LockFile             = dokanOperationProxy.LockFileProxy,
                UnlockFile           = dokanOperationProxy.UnlockFileProxy,
                GetDiskFreeSpace     = dokanOperationProxy.GetDiskFreeSpaceProxy,
                GetVolumeInformation = dokanOperationProxy.GetVolumeInformationProxy,
                Mounted              = dokanOperationProxy.MountedProxy,
                Unmounted            = dokanOperationProxy.UnmountedProxy,
                GetFileSecurity      = dokanOperationProxy.GetFileSecurityProxy,
                SetFileSecurity      = dokanOperationProxy.SetFileSecurityProxy,
                FindStreams          = dokanOperationProxy.FindStreamsProxy
            };

            var status = NativeMethods.DokanMain(ref dokanOptions, ref dokanOperations);

            switch (status)
            {
            case DOKAN_ERROR:
                throw new DokanException(status, Resource.ErrorDokan);

            case DOKAN_DRIVE_LETTER_ERROR:
                throw new DokanException(status, Resource.ErrorBadDriveLetter);

            case DOKAN_DRIVER_INSTALL_ERROR:
                throw new DokanException(status, Resource.ErrorDriverInstall);

            case DOKAN_MOUNT_ERROR:
                throw new DokanException(status, Resource.ErrorAssignDriveLetter);

            case DOKAN_START_ERROR:
                throw new DokanException(status, Resource.ErrorStart);

            case DOKAN_MOUNT_POINT_ERROR:
                throw new DokanException(status, Resource.ErrorMountPointInvalid);

            case DOKAN_VERSION_ERROR:
                throw new DokanException(status, Resource.ErrorVersion);
            }
        }
예제 #46
0
        public IRunner CreateTeamCityRunner(StatLightConfiguration statLightConfiguration)
        {
            if (statLightConfiguration == null) throw new ArgumentNullException("statLightConfiguration");
            ILogger logger = new NullLogger();
            IWebServer webServer;
            List<IWebBrowser> webBrowsers;
            IDialogMonitorRunner dialogMonitorRunner;

            BuildAndReturnWebServiceAndBrowser(
                logger,
                statLightConfiguration,
                out webServer,
                out webBrowsers,
                out dialogMonitorRunner);

            var teamCityTestResultHandler = new TeamCityTestResultHandler(new ConsoleCommandWriter(), statLightConfiguration.Server.XapToTestPath);
            IRunner runner = new TeamCityRunner(logger, _eventSubscriptionManager, _eventPublisher, webServer, webBrowsers, teamCityTestResultHandler, statLightConfiguration.Server.XapToTestPath, dialogMonitorRunner);

            return runner;
        }
 public FantasyPremierLeagueApiDataFactory()
 {
     Properties = new Dictionary<string, object>();
     //Logger = new FantasyPremierLeagueApi.Helpers.Logger.ConsoleLogger();
     Logger = new NullLogger();
 }