Exemple #1
0
        public virtual ApiResult Process(Action action, bool needRetry = false, int retryCount = 50, Func <Exception, string> getExceptionMessage = null)
        {
            ApiResult apiResult = null;

            getExceptionMessage = getExceptionMessage ?? GetExceptionMessage;
            do
            {
                try
                {
                    action();
                    apiResult = new ApiResult();
                    needRetry = false;
                }
                catch (Exception ex)
                {
                    if (!(ex is OptimisticConcurrencyException) || !needRetry)
                    {
                        var baseException = ex.GetBaseException();
                        if (baseException is DomainException)
                        {
                            var sysException = baseException as DomainException;
                            apiResult = new ApiResult(sysException.ErrorCode, getExceptionMessage(sysException));
                            Logger?.Warn(ex);
                        }
                        else
                        {
                            apiResult = new ApiResult(ErrorCode.UnknownError, getExceptionMessage(ex));
                            Logger?.Error(ex);
                        }
                        needRetry = false;
                    }
                }
            } while (needRetry && retryCount-- > 0);
            return(apiResult);
        }
        private static IUnitOfWork GetCurrentUow(ILogger logger)
        {
            var unitOfWorkKey = CallContext.LogicalGetData(ContextKey) as string;
            if (unitOfWorkKey == null)
            {
                return null;
            }

            IUnitOfWork unitOfWork;
            if (!UnitOfWorkDictionary.TryGetValue(unitOfWorkKey, out unitOfWork))
            {
                logger.Warn("There is a unitOfWorkKey in CallContext but not in UnitOfWorkDictionary!");
                CallContext.FreeNamedDataSlot(ContextKey);
                return null;
            }

            if (unitOfWork.IsDisposed)
            {
                logger.Warn("There is a unitOfWorkKey in CallContext but the UOW was disposed!");
                UnitOfWorkDictionary.TryRemove(unitOfWorkKey, out unitOfWork);
                CallContext.FreeNamedDataSlot(ContextKey);
                return null;
            }

            return unitOfWork;
        }
Exemple #3
0
        //public static IUserGroupPermissionProvider DefaultUserGroupPermissionProvider()
        //{
        //    return new DefaultUserGroupPermissionProvider();
        //}

        public override Task <AdobeConnectUser> FindAsync(string userName, string password)
        {
            Task <AdobeConnectUser> taskInvoke = Task.Run(async() =>
            {
                string[] parts      = userName.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                string companyToken = parts[0];
                string acDomain     = parts[1];
                string acLogin      = parts[2];

                if (!_acDomainValidator.IsValid(companyToken, acDomain))
                {
                    _logger?.Warn($"[UserManager.FindAsync] AC domain is not valid for companyToken. AcDomain={acDomain}");
                    return(null);
                }

                string sessionToken;
                var connectionDetails = new ConnectionDetails(new Uri(acDomain));
                var provider          = new AdobeConnectProvider(connectionDetails);
                UserInfo acPrincipal  = TryLogin(provider, new AdobeConnectAccess(new Uri(acDomain), acLogin, password), out sessionToken);
                _logger?.Info($"[UserManager.FindAsync] ACSession={sessionToken}");

                if (acPrincipal == null)
                {
                    _logger?.Warn($"[UserManager.FindAsync] Principal not found. AcDomain={acDomain}, AcLogin={acLogin}");
                    return(null);
                }

                var roles = new List <string>();
                if (_userAuthorizationProvider != null)
                {
                    roles.AddRange(_userAuthorizationProvider.GetUserPermissions(provider, acPrincipal));
                }

                var applicationUser = new AdobeConnectUser
                {
                    Id       = acPrincipal.UserId,
                    UserName = acLogin,

                    CompanyToken   = companyToken,
                    AcDomain       = acDomain,
                    AcSessionToken = sessionToken,
                    Roles          = roles
                };
                var store = Store as IEdugameCloudUserStore <AdobeConnectUser>;
                if (store != null)
                {
                    var user = await store.FindByPrincipalIdAndCompanyTokenAndAcDomainAsync(applicationUser.Id, companyToken,
                                                                                            acDomain);
                    if (user == null)
                    {
                        _logger?.Warn($"[UserManager.FindAsync] UserStore.CreateAsync. PrincipalId={applicationUser.Id}");
                        await store.CreateAsync(applicationUser, password);
                    }
                }

                return(applicationUser);
            });

            return(taskInvoke);
        }
Exemple #4
0
        private bool ExistsOrCreate()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_fileName))
                {
                    _logger?.Warn("Имя файла для сервис-хранилища пусто.");
                    return(false);
                }

                var dir = Directory.GetParent(_fileName).FullName;

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                if (!File.Exists(_fileName))
                {
                    using (var file = File.Create(_fileName))
                    {
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                _logger?.Warn($"Ошибка при создании/проверки существования файла ({_fileName}) : {e}.");
                return(false);
            }
        }
Exemple #5
0
        public void Start()
        {
            Task.Run(() => _connectionListener.StartListening(NetworkConfig.Instance.ListeningPort));

            _connectionListener.IncomingConnection += OnIncomingConnection;
            _connectionListener.ListeningStopped   += OnListeningStopped;

            if (!_isBp)
            {
                _maintenanceTimer = new Timer(e => DoPeerMaintenance(), null, _initialMaintenanceDelay, _maintenancePeriod);
            }

            // Add the provided bootnodes
            if (NetworkConfig.Instance.Bootnodes != null && NetworkConfig.Instance.Bootnodes.Any())
            {
                // todo add jobs
                foreach (var btn in NetworkConfig.Instance.Bootnodes)
                {
                    NodeData nd      = NodeData.FromString(btn);
                    var      dialJob = new PeerManagerJob {
                        Type = PeerManagerJobType.DialNode, Node = nd
                    };
                    _jobQueue.Add(dialJob);
                }
            }
            else
            {
                _logger?.Warn("Bootnode list is empty.");
            }

            Task.Run(() => StartProcessing()).ConfigureAwait(false);
        }
Exemple #6
0
        private static TableConfigurations GetPrebuiltConfigurationFromEmbeddedResource(
            Type tableType,
            Guid tableId,
            ISerializer serializer,
            ILogger logger)
        {
            var tableAttribute = tableType.GetCustomAttribute <PrebuiltConfigurationsEmbeddedResourceAttribute>();

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

            try
            {
                var tableAssembly = Assembly.GetAssembly(tableType);
                Debug.Assert(tableAssembly != null, "Unable to retrieve assembly for a table type.");

                var resourceName = tableAssembly.GetManifestResourceNames()
                                   .Single(name => name.EndsWith(tableAttribute.EmbeddedResourcePath));

                if (string.IsNullOrWhiteSpace(resourceName))
                {
                    logger?.Warn(
                        $"Unable to retrieve embedded resource for prebuilt configurations in table {tableType}.");
                    return(null);
                }

                IEnumerable <TableConfigurations> tableConfigurations;
                using (var resourceStream = tableAssembly.GetManifestResourceStream(resourceName))
                {
                    tableConfigurations = serializer.DeserializeTableConfigurations(resourceStream);
                }

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

                foreach (var tableConfiguration in tableConfigurations)
                {
                    if (tableConfiguration.TableId != tableId)
                    {
                        continue;
                    }

                    return(tableConfiguration);
                }
            }
            catch (Exception e)
            {
                logger?.Warn(
                    $"Unable to retrieve embedded resource for prebuilt configurations in table {tableType}\n" +
                    $"{e.Message}.");
            }

            return(null);
        }
Exemple #7
0
        /// <summary>
        /// Gets the filtered file system entries.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="searchPattern">The search pattern.</param>
        /// <param name="flattenFolderDepth">The flatten folder depth.</param>
        /// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
        /// <param name="args">The args.</param>
        /// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
        /// <exception cref="System.ArgumentNullException">path</exception>
        public static Dictionary<string, FileSystemInfo> GetFilteredFileSystemEntries(string path, ILogger logger, string searchPattern = "*", int flattenFolderDepth = 0, bool resolveShortcuts = true, ItemResolveArgs args = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            var dict = new Dictionary<string, FileSystemInfo>(StringComparer.OrdinalIgnoreCase);
            
            var entries = new DirectoryInfo(path).EnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);

            foreach (var entry in entries)
            {
                var isDirectory = entry.Attributes.HasFlag(FileAttributes.Directory);

                if (resolveShortcuts && FileSystem.IsShortcut(entry.FullName))
                {
                    var newPath = FileSystem.ResolveShortcut(entry.FullName);

                    if (string.IsNullOrWhiteSpace(newPath))
                    {
                        //invalid shortcut - could be old or target could just be unavailable
                        logger.Warn("Encountered invalid shortcut: " + entry.FullName);
                        continue;
                    }

                    var data = FileSystem.GetFileSystemInfo(newPath);

                    if (data.Exists)
                    {
                        // add to our physical locations
                        if (args != null)
                        {
                            args.AddAdditionalLocation(newPath);
                        }

                        dict[data.FullName] = data;
                    }
                    else
                    {
                        logger.Warn("Cannot add unavailble/non-existent location {0}", data.FullName);
                    }
                }
                else if (flattenFolderDepth > 0 && isDirectory)
                {
                    foreach (var child in GetFilteredFileSystemEntries(entry.FullName, logger, flattenFolderDepth: flattenFolderDepth - 1, resolveShortcuts: resolveShortcuts))
                    {
                        dict[child.Key] = child.Value;
                    }
                }
                else
                {
                    dict[entry.FullName] = entry;
                }
            }

            return dict;
        }
Exemple #8
0
        public void Send(IPEndPoint remote, ArraySegment <byte> bytes)
        {
            if (!_connections.TryGetValue(remote, out ITcpConnection connection))
            {
                _logger?.Warn($"Send error, connection not found - {remote}");
                return;
            }

            connection.Send(bytes);
        }
Exemple #9
0
        private void MessageReaderOnStreamClosed(object sender, EventArgs eventArgs)
        {
            Dispose();

            _logger?.Warn($"Peer connection has been terminated : {DistantNodeData}.");

            PeerDisconnected?.Invoke(this, new PeerDisconnectedArgs {
                Peer = this, Reason = DisconnectReason.StreamClosed
            });
        }
Exemple #10
0
        public async Task <Block> GetBlockAtHeight(int height)
        {
            if (height <= 0)
            {
                _logger?.Warn($"Cannot get block - height {height} is not valid.");
                return(null);
            }

            var block = (Block)await BlockChain.GetBlockByHeightAsync((ulong)height);

            return(block != null ? await FillBlockWithTransactionList(block) : null);
        }
Exemple #11
0
        /// <summary>
        /// Handles a list of transactions sent by another node, these transactions are either
        /// issues from a broadcast or a request.
        /// </summary>
        /// <returns></returns>
        private async Task HandleTransactionMessage(TransactionsReceivedEventArgs txsEventArgs)
        {
            var txs = txsEventArgs.Transactions;

            _logger?.Debug($"Handling transaction list message : {txs.ToDebugString()} from {txsEventArgs.Peer}");

            var receivedTxs = new List <byte[]>();

            foreach (var tx in txs.Transactions)
            {
                try
                {
                    // Every received transaction, provided that it's valid, should be in the pool.
                    var result = await _poolService.AddTxAsync(tx, !IsInitialSyncInProgress);

                    byte[] transactionBytes = tx.GetHashBytes();

                    if (result == TxValidation.TxInsertionAndBroadcastingError.Success)
                    {
                        receivedTxs.Add(transactionBytes);
                    }
                    else if (result == TxValidation.TxInsertionAndBroadcastingError.AlreadyInserted)
                    {
                        SetTransactions(receivedTxs);
                    }
                    else
                    {
                        _logger?.Warn($"Failed to add the following transaction to the pool (reason: {result}): "
                                      + $"{tx.GetTransactionInfo()}");

                        foreach (var pendingBlock in PendingBlocks)
                        {
                            var pendingTx =
                                pendingBlock.MissingTxs.FirstOrDefault(mstx => mstx.Hash.BytesEqual(transactionBytes));

                            if (pendingTx != null)
                            {
                                pendingTx.IsRequestInProgress = false;
                                break;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger?.Error(e, "Error while hadling transactions.");
                }
            }

            EnqueueJob(new Job {
                Transactions = receivedTxs
            });
        }
        private static void SetCurrentUow(IUnitOfWork value, ILogger logger)
        {
            if (value == null)
            {
                ExitFromCurrentUowScope(logger);
                return;
            }

            var unitOfWorkKey = CallContext.LogicalGetData(ContextKey) as string;
            if (unitOfWorkKey != null)
            {
                IUnitOfWork outer;
                if (UnitOfWorkDictionary.TryGetValue(unitOfWorkKey, out outer))
                {
                    if (outer == value)
                    {
                        logger.Warn("Setting the same UOW to the CallContext, no need to set again!");
                        return;
                    }

                    value.Outer = outer;
                }
            }

            unitOfWorkKey = value.Id;
            if (!UnitOfWorkDictionary.TryAdd(unitOfWorkKey, value))
            {
                throw new AbpException("Can not set unit of work! UnitOfWorkDictionary.TryAdd returns false!");
            }

            logger.Debug("Entering a new UOW scope: " + unitOfWorkKey);
            CallContext.LogicalSetData(ContextKey, unitOfWorkKey);
        }
Exemple #13
0
        public async Task <BlockValidationResult> ValidateBlockAsync(IBlock block, IChainContext context)
        {
            if (_doingRollback)
            {
                _logger?.Trace("Could not validate block during rollbacking!");
                return(BlockValidationResult.DoingRollback);
            }

            MessageHub.Instance.Publish(new ValidationStateChanged(block.BlockHashToHex, block.Index, true,
                                                                   BlockValidationResult.Success));

            var resultCollection = new List <BlockValidationResult>();

            foreach (var filter in _filters)
            {
                var result = await filter.ValidateBlockAsync(block, context);

                if (result != BlockValidationResult.Success)
                {
                    _logger?.Warn($"Result of {filter.GetType().Name}: {result} - {block.BlockHashToHex}");
                }
                resultCollection.Add(result);
            }

            var finalResult = resultCollection.Max();

            MessageHub.Instance.Publish(new ValidationStateChanged(block.BlockHashToHex, block.Index, false,
                                                                   finalResult));

            return(finalResult);
        }
Exemple #14
0
        public AuthModule(ILogger<AuthModule> logger,
            IUserManager userManager,
            ITokenizer tokenizer)
            : base("auth")
        {
            Get["/setup"] = _ => !userManager.HasUsers();

            Post["/login"] = _ =>
            {
                var userData = this.Bind<UserDto>();

                // First login creates user
                if (!userManager.HasUsers())
                {
                    logger.Info("Creating user account {UserName}.", userData.UserName);
                    userManager.CreateUser(userData.UserName, userData.Password);
                }

                var user = userManager.GetUser(userData.UserName, userData.Password);

                if (user == null)
                {
                    logger.Warn("Invalid username/password: {UserName}.", userData.UserName);
                    return HttpStatusCode.Unauthorized;
                }

                var identity = new UserIdentity(user.UserName, user.Claims);
                var token = tokenizer.Tokenize(identity, Context);

                return new
                {
                    Token = token
                };
            };
        }
Exemple #15
0
        /// <summary>
        /// Create JVM.
        /// </summary>
        /// <param name="cfg">Configuration.</param>
        /// <param name="cbs">Callbacks.</param>
        /// <param name="log"></param>
        /// <returns>Context.</returns>
        internal static void CreateJvmContext(IgniteConfiguration cfg, UnmanagedCallbacks cbs, ILogger log)
        {
            lock (SyncRoot)
            {
                // 1. Warn about possible configuration inconsistency.
                JvmConfiguration jvmCfg = JvmConfig(cfg);

                if (!cfg.SuppressWarnings && _jvmCfg != null)
                {
                    if (!_jvmCfg.Equals(jvmCfg))
                    {
                        log.Warn("Attempting to start Ignite node with different Java " +
                            "configuration; current Java configuration will be ignored (consider " +
                            "starting node in separate process) [oldConfig=" + _jvmCfg +
                            ", newConfig=" + jvmCfg + ']');
                    }
                }

                // 2. Create unmanaged pointer.
                void* ctx = CreateJvm(cfg, cbs);

                cbs.SetContext(ctx);

                // 3. If this is the first JVM created, preserve it.
                if (_ctx == null)
                {
                    _ctx = ctx;
                    _jvmCfg = jvmCfg;
                }
            }
        }
        /// <summary>
        /// Resolves the types for the given assembly
        /// </summary>
        /// <remarks>
        /// The resolver will first check its cache. If the types were previously resolved for the given assembly, then those are returned
        /// If nothing has been cached before, then the types are being resolved and added to the cache before being returned.
        /// </remarks>
        /// <param name="assembly">The assembly for which the types should be resolved</param>
        /// <param name="logger">The logger to use in case an exception should occur when resolving the types</param>
        /// <returns>List of types resolved for the given assembly</returns>
        public static Type[] ResolveTypes(Assembly assembly, ILogger logger)
        {
            // GetTypes potentially throws an exception. Defensive coding as per http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx

            Type[] allTypes;
            lock (typesByAssembly)
            {
                try
                {
                    if (!typesByAssembly.TryGetValue(assembly, out allTypes))
                    {
                        allTypes = assembly.GetTypes();
                        typesByAssembly.Add(assembly, allTypes);
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    allTypes = ex.Types.Where(t => t != null).ToArray();
                    typesByAssembly.Add(assembly, allTypes);

                    foreach (var exception in ex.LoaderExceptions)
                    {
                        logger.Warn(string.Format(Resources.DiscoverGetType, assembly.FullName), exception);
                    }
                }
            }

            return allTypes;
        }
Exemple #17
0
        internal static void Fix(ILogger?logger)
        {
            var path = new PathString(AppDomain.CurrentDomain.BaseDirectory ?? Environment.CurrentDirectory)
                       .GetDirectoryName()?.GetDirectoryName()?.GetDirectoryName()?.GetDirectoryName();

            if (path is null)
            {
                logger?.Warn("Could not load the solution path.");
                return;
            }
            logger?.Info($"The solution path is: {path}");
            logger?.Info($"Ready to run.");
            ConsoleUtil.Pause();
            LoadAndConvertFiles(logger, path,
                                // Git Configurations
                                ".gitignore", ".gitattributes", ".gitmodules",
                                // Visual Studio Files
                                ".sln", ".csproj", ".editorconfig",
                                // C# Code Files and ResX Files
                                ".cs", ".resx",
                                // Document Files
                                ".txt", ".md",
                                // Batch Scripts
                                ".cmd",
                                // Data Description Language Files
                                ".xsd", ".json", ".yml",
                                // Others
                                ".partial"
                                );
        }
Exemple #18
0
        public IObservable <T> Retry <T>(IObservable <T> work)
        {
            return(work.RetryWhen(failedWork =>
            {
                var handledExceptions = new List <Exception>();
                var timer = Stopwatch.StartNew();
                var delay = _initialDelay;
                var retryCount = 1;

                return failedWork.SelectMany(exc =>
                {
                    if (!exc.IsRetriableError())
                    {
                        return Observable.Throw <int>(exc);
                    }

                    handledExceptions.Add(exc);

                    if (retryCount >= 2 && timer.ElapsedMilliseconds >= _maxRetryTimeout)
                    {
                        return Observable.Throw <int>(new ServiceUnavailableException(
                                                          $"Failed after retried for {retryCount} times in {_maxRetryTimeout} ms. " +
                                                          "Make sure that your database is online and retry again.",
                                                          new AggregateException(handledExceptions)));
                    }

                    var delayDuration = TimeSpan.FromMilliseconds(ComputeNextDelay(delay));
                    delay *= _delayMultiplier;
                    retryCount++;
                    _logger?.Warn(exc, $"Transaction failed and will be retried in {delay} ms.");
                    return Observable.Return(1).Delay(delayDuration);
                });
            }));
        }
        /// <summary>
        /// 获取当前工作单元
        /// </summary>
        /// <param name="logger">日志</param>
        /// <returns></returns>
        private static IUnitOfWork GetCurrentUow(ILogger logger)
        {
            //获取当前工作单元key
            var unitOfWorkKey = CallContext.LogicalGetData(ContextKey) as string;
            if (unitOfWorkKey == null)
            {
                return null;
            }

            IUnitOfWork unitOfWork;
            if (!UnitOfWorkDictionary.TryGetValue(unitOfWorkKey, out unitOfWork))
            {
                //如果根据key获取不到当前工作单元,那么就从当前线程集合(CallContext)中释放key
                //logger.Warn("There is a unitOfWorkKey in CallContext but not in UnitOfWorkDictionary (on GetCurrentUow)! UnitOfWork key: " + unitOfWorkKey);
                CallContext.FreeNamedDataSlot(ContextKey);
                return null;
            }

            if (unitOfWork.IsDisposed)
            {
                //如果当前工作单元已经dispose,那么就从工作单元集合中移除,并将key从当前线程集合(CallContext)中释放
                logger.Warn("There is a unitOfWorkKey in CallContext but the UOW was disposed!");
                UnitOfWorkDictionary.TryRemove(unitOfWorkKey, out unitOfWork);
                CallContext.FreeNamedDataSlot(ContextKey);
                return null;
            }

            return unitOfWork;
        }
        public void Import(IStorageReader <string> reader, IParser <string, TradeRecord> parser, IDataSaver <TradeRecord> saver,
                           ILogger logger)
        {
            ValidateOnNull(reader, nameof(reader));
            ValidateOnNull(parser, nameof(parser));
            ValidateOnNull(saver, nameof(saver));

            var data = reader.Read().ToList();

            List <TradeRecord> records = new List <TradeRecord>();

            for (int i = 0; i < data.Count; i++)
            {
                try
                {
                    records.Add(parser.Parse(data[i]));
                }
                catch (Exception e) //TODO: ValidationException (custom)
                {
                    logger?.Warn($"{e.Message} {{line #{i}}}");
                }
            }

            saver.Save(records);

            logger?.Info("Success");
        }
Exemple #21
0
        /// <summary>
        /// Gets the filtered file system entries.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="args">The args.</param>
        /// <param name="searchPattern">The search pattern.</param>
        /// <param name="flattenFolderDepth">The flatten folder depth.</param>
        /// <param name="resolveShortcuts">if set to <c>true</c> [resolve shortcuts].</param>
        /// <returns>Dictionary{System.StringFileSystemInfo}.</returns>
        /// <exception cref="System.ArgumentNullException">path</exception>
        public static Dictionary<string, FileSystemInfo> GetFilteredFileSystemEntries(string path, ILogger logger, ItemResolveArgs args, string searchPattern = "*", int flattenFolderDepth = 0, bool resolveShortcuts = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            var entries = new DirectoryInfo(path).EnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);

            if (!resolveShortcuts && flattenFolderDepth == 0)
            {
                return entries.ToDictionary(i => i.FullName, StringComparer.OrdinalIgnoreCase);
            }

            var dict = new Dictionary<string, FileSystemInfo>(StringComparer.OrdinalIgnoreCase);

            foreach (var entry in entries)
            {
                var isDirectory = (entry.Attributes & FileAttributes.Directory) == FileAttributes.Directory;

                var fullName = entry.FullName;

                if (resolveShortcuts && FileSystem.IsShortcut(fullName))
                {
                    var newPath = FileSystem.ResolveShortcut(fullName);

                    if (string.IsNullOrWhiteSpace(newPath))
                    {
                        //invalid shortcut - could be old or target could just be unavailable
                        logger.Warn("Encountered invalid shortcut: " + fullName);
                        continue;
                    }

                    // Don't check if it exists here because that could return false for network shares.
                    var data = new DirectoryInfo(newPath);

                    // add to our physical locations
                    args.AddAdditionalLocation(newPath);

                    dict[newPath] = data;
                }
                else if (flattenFolderDepth > 0 && isDirectory)
                {
                    foreach (var child in GetFilteredFileSystemEntries(fullName, logger, args, flattenFolderDepth: flattenFolderDepth - 1, resolveShortcuts: resolveShortcuts))
                    {
                        dict[child.Key] = child.Value;
                    }
                }
                else
                {
                    dict[fullName] = entry;
                }
            }

            return dict;
        }
Exemple #22
0
 public void CaughtUserCodeException(string callback, string where, Exception e)
 {
     log?.Warn((int)ErrorCode.LogConsistency_UserCodeException,
               string.Format("{0} Exception caught in user code for {1}, called from {2}",
                             grain.GrainReference,
                             callback,
                             where), e);
 }
Exemple #23
0
        public Task <AdobeConnectUser> FindAsync(string userName, string password)
        {
            string[] parts        = userName.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            string   companyToken = parts[0];
            string   acDomain     = parts[1];
            string   acLogin      = parts[2];

            if (!_acDomainValidator.IsValid(companyToken, acDomain))
            {
                _logger?.Warn($"[UserManager.FindAsync] AC domain is not valid for companyToken. AcDomain={acDomain}");
                return(Task.FromResult <AdobeConnectUser>(null));
            }

            string   sessionToken;
            var      connectionDetails = new ConnectionDetails(new Uri(acDomain));
            var      provider          = new AdobeConnectProvider(connectionDetails);
            UserInfo acPrincipal       = TryLogin(provider, new AdobeConnectAccess(new Uri(acDomain), acLogin, password), out sessionToken);

            _logger?.Info($"[UserManager.FindAsync] ACSession={sessionToken}");

            if (acPrincipal == null)
            {
                _logger?.Warn($"[UserManager.FindAsync] Principal not found. AcDomain={acDomain}, AcLogin={acLogin}");
                return(Task.FromResult <AdobeConnectUser>(null));
            }

            var roles = new List <string>();

            if (_userAuthorizationProvider != null)
            {
                roles.AddRange(_userAuthorizationProvider.GetUserPermissions(provider, acPrincipal));
            }

            var applicationUser = new AdobeConnectUser
            {
                Id       = acPrincipal.UserId,
                UserName = acLogin,

                CompanyToken   = companyToken,
                AcDomain       = acDomain,
                AcSessionToken = sessionToken,
                Roles          = roles
            };

            return(Task.FromResult(applicationUser));
        }
Exemple #24
0
        internal static T MapObject <T>(this SqlDataReader reader,
                                        //Dictionary<Guid, List<Tuple<object, string>>> navProps = null,
                                        Dictionary <string, SqlDbType> output = null)
        //where T : new()
        {
            var entity = CreateInstance <T>();

            Execute(() =>
            {
                var propertyInfos = PropertyInfosByType[typeof(T)];  //already populated

                var outputColumnName = (output != null && output.Any()) ? output.First().Key : null;
                var numberOfColumns  = reader.FieldCount;

                T tmpEntity;
                if (CheckAndProcessScalarOutput(reader, output, outputColumnName, numberOfColumns, out tmpEntity))
                {
                    entity = tmpEntity;
                    return;
                }

                for (var columnIndex = 0; columnIndex < numberOfColumns; columnIndex++)
                {
                    var kvp        = GetColumnNameAndValue(reader, columnIndex);
                    var columnName = kvp.Key;
                    var val        = kvp.Value;

                    if (!propertyInfos.ContainsKey(columnName))
                    {
                        continue;
                    }

                    try
                    {
                        propertyInfos[columnName].SetValue(entity, val, null);
                    }
                    catch (Exception)
                    {
                        Log?.Warn(string.Format(TranslationError, "1st", columnName));
                        TrySetPropertyUsingConvert(propertyInfos, columnName, val, entity);
                    }
                }
            }, "MapObject<T>");

            return(entity);
        }
        public bool Check(AbstractConnection connection, ILogger logger) {
            if (CachedResults.ContainsKey(connection.Name)) {
                return CachedResults[connection.Name];
            }

            if (!new FileInfo(connection.Server).Exists) {
                logger.Warn("{0} not found.", connection.Server);

                var type = System.Type.GetType("System.Data.SqlServerCe.SqlCeEngine, System.Data.SqlServerCe", false, true);
                dynamic engine = System.Activator.CreateInstance(type, connection.GetConnectionString());
                engine.CreateDatabase();

                logger.Warn("Created {0} database file.", connection.Server);
            };

            return CheckConnection(connection);
        }
        internal async Task <IRoutingTable> UpdateRoutingTableAsync(IRoutingTable routingTable, AccessMode mode,
                                                                    string database, Bookmark bookmark, ISet <Uri> triedUris = null)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            var knownRouters = routingTable?.Routers ?? throw new ArgumentNullException(nameof(routingTable));

            foreach (var router in knownRouters)
            {
                triedUris?.Add(router);
                try
                {
                    var conn = await _poolManager.CreateClusterConnectionAsync(router).ConfigureAwait(false);

                    if (conn == null)
                    {
                        routingTable.Remove(router);
                    }
                    else
                    {
                        var newRoutingTable =
                            await _discovery.DiscoverAsync(conn, database, bookmark).ConfigureAwait(false);

                        if (!newRoutingTable.IsStale(mode))
                        {
                            return(newRoutingTable);
                        }

                        _logger?.Debug("Skipping stale routing table received from server '{0}' for database '{1}'",
                                       router, database);
                    }
                }
                catch (SecurityException e)
                {
                    _logger?.Error(e,
                                   "Failed to update routing table from server '{0}' for database '{1}' because of a security exception.",
                                   router, database);
                    throw;
                }
                catch (FatalDiscoveryException e)
                {
                    _logger?.Error(e,
                                   "Failed to update routing table from server '{0}' for database '{1}' because of a fatal discovery exception.",
                                   router, database);
                    throw;
                }
                catch (Exception e)
                {
                    _logger?.Warn(e, "Failed to update routing table from server '{0}' for database '{1}'.", router,
                                  database);
                }
            }

            return(null);
        }
Exemple #27
0
        /// <summary>
        /// The main loop that sends queud up messages from the message queue.
        /// </summary>
        internal void DequeueOutgoingLoop()
        {
            while (!IsDisposed && _outboundMessages != null)
            {
                WriteJob job;

                try
                {
                    job = _outboundMessages.Take();
                }
                catch (Exception)
                {
                    Dispose(); // if already disposed will do nothing
                    break;
                }

                var p = job.Message;

                if (p == null)
                {
                    _logger?.Warn("Cannot write a null message.");
                    continue;
                }

                try
                {
                    if (p.Payload.Length > MaxOutboundPacketSize)
                    {
                        var partials = PayloadToPartials(p.Type, p.Payload, MaxOutboundPacketSize);

                        _logger?.Trace($"Message split into {partials.Count} packets.");

                        foreach (var msg in partials)
                        {
                            SendPartialPacket(msg);
                        }
                    }
                    else
                    {
                        // Send without splitting
                        SendPacketFromMessage(p);
                    }

                    job.SuccessCallback?.Invoke(p);
                }
                catch (Exception e) when(e is IOException || e is ObjectDisposedException)
                {
                    _logger?.Trace("Exception with the underlying socket or stream closed.");
                    Dispose();
                }
                catch (Exception e)
                {
                    _logger?.Trace(e, "Exception while dequeing message.");
                }
            }

            _logger?.Trace("Finished writting messages.");
        }
Exemple #28
0
        private async Task ProcessPeerMessage(PeerMessageReceivedArgs args)
        {
            if (args?.Peer == null)
            {
                _logger.Warn("Peer is invalid.");
                return;
            }

            if (args.Message?.Payload == null)
            {
                _logger?.Warn($"Message from {args.Peer}, message/payload is null.");
                return;
            }

            AElfProtocolMsgType msgType = (AElfProtocolMsgType)args.Message.Type;

            switch (msgType)
            {
            case AElfProtocolMsgType.Announcement:
                HandleAnnouncement(args.Message, args.Peer);
                break;

            case AElfProtocolMsgType.Block:
                MessageHub.Instance.Publish(new BlockReceived(args.Block));
                break;

            case AElfProtocolMsgType.NewTransaction:
                HandleNewTransaction(args.Message);
                break;

            case AElfProtocolMsgType.Headers:
                HandleHeaders(args.Message);
                break;

            case AElfProtocolMsgType.RequestBlock:
                await HandleBlockRequestJob(args);

                break;

            case AElfProtocolMsgType.HeaderRequest:
                await HandleHeaderRequest(args);

                break;
            }
        }
Exemple #29
0
 public DefaultRetry(ILogger logger) : base(_numAttempts)
 {
     this
         .Chain(r => r.Started += (s, e) => logger.Debug("{Action}...", e.ActionName))
         .Chain(r => r.Success += (s, e) => logger.Debug("{Action} completed successfully in {Elapsed}.", e.ActionName, e.ElapsedTime))
         .Chain(r => r.TransientFailure += (s, e) => logger.Warn(e.Exception, "A transient failure occurred in action {Action}.", e.ActionName))
         .Chain(r => r.PermanentFailure += (s, e) => logger.Error(e.Exception, "A permanent failure occurred in action {Action}.", e.ActionName))
         .WithBackoff<DefaultRetry>(Backoff)
         ;
 }
Exemple #30
0
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception exception)
            {
                _logger?.Warn("UnhandledException",
                              new LogItem("Exception", exception.Message),
                              new LogItem("StackTrace", exception.StackTrace));
            }

            Process.GetCurrentProcess().Close();
        }
Exemple #31
0
        public async Task SendAsync(IEnumerable <IRequestMessage> messages)
        {
            try
            {
                foreach (var message in messages)
                {
                    Writer.Write(message);
                    LogDebug(MessagePattern, message);
                }

                await Writer.FlushAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger?.Warn(ex, $"Unable to send message to server {_uri}, connection will be terminated.");
                await StopAsync().ConfigureAwait(false);

                throw;
            }
        }
Exemple #32
0
 public static async Task WithoutException(this Task task, ILogger logger = null)
 {
     try
     {
         await task.ConfigureAwait(false);
     }
     catch (Exception e)
     {
         logger?.Warn(e);
     }
 }
        public JavascriptOperation(
            string outKey, 
            string script, 
            Dictionary<string, Script> scripts, 
            IParameters parameters,
            ILogger logger)
            : base(string.Empty, outKey) {
            _script = script;
            _parameters = parameters;
            _addSelf = !parameters.Any();

            foreach (var pair in scripts) {
                logger.Debug("Running script {0}.", pair.Value.File);
                try
                {
                    var program = new JavaScriptParser().Parse(pair.Value.Content, new ParserOptions { Tolerant = true});
                    if (program.Errors != null && program.Errors.Count > 0) {
                        logger.Warn("Javascript Parse Failed. Script: {0}.", pair.Value.Name);
                        foreach (var error in program.Errors) {
                            logger.Warn(error.Description);
                        }
                    } else {
                        _scriptAppender.AppendLine(pair.Value.Content);
                    }
                }
                catch (Exception e) {
                    logger.Error("Javascript Parse Failed. Name: {0}. Script: {1}.", pair.Value.Name, pair.Value.Content);
                    logger.Error(e.Message);
                }
            }

            var externalScripts = _scriptAppender.ToString();
            if (externalScripts.Equals(string.Empty))
                return;

            logger.Debug("Loading scripts into Javascript engine...");
            logger.Debug(externalScripts.Replace("{","{{").Replace("}","}}"));
            _jint.Execute(externalScripts);

            Name = string.Format("Javascript({0}=>{1})", InKey, OutKey);
        }
Exemple #34
0
 public static void IgnoreExceptions(Action act, ILogger logger = null)
 {
     Assert.ArgumentNotNull(act, nameof(act));
     try
     {
         act();
     }
     catch (Exception e)
     {
         logger?.Warn(e, "Explicitly ignored exception");
     }
 }
Exemple #35
0
        public static async Task <T> WithoutException <T>(this Task <T> task, ILogger logger = null)
        {
            try
            {
                return(await task.ConfigureAwait(false));
            }
            catch (Exception e)
            {
                logger?.Warn(e);
            }

            return(default);
Exemple #36
0
        private async void Process()
        {
            try {
                while (Client.Connected)
                {
                    // TODO : Configuration.
                    var limitedStream = new NotFlushingStream(new LimitedStream(_stream, 1024 * 1024, 1024 * 1024));
                    var streamReader  = new StreamReader(limitedStream);

                    var request = await _requestProvider.Provide(streamReader).ConfigureAwait(false);

                    if (request != null)
                    {
                        UpdateLastOperationTime();

                        var context = new HttpContext(request, Client.RemoteEndPoint);

                        _logger?.Debug($"{Client.RemoteEndPoint} : Got request {request.Uri}");

                        await _requestHandler(context).ConfigureAwait(false);

                        if (context.Response != null)
                        {
                            var streamWriter = new StreamWriter(limitedStream)
                            {
                                AutoFlush = false
                            };

                            await WriteResponse(context, streamWriter).ConfigureAwait(false);

                            await limitedStream.ExplicitFlushAsync().ConfigureAwait(false);

                            if (!request.Headers.KeepAliveConnection() || context.Response.CloseConnection)
                            {
                                Client.Close();
                            }
                        }

                        UpdateLastOperationTime();
                    }
                    else
                    {
                        Client.Close();
                    }
                }
            } catch (Exception e) {
                // Hate people who make bad calls.
                _logger?.Warn($"Error while serving : {_remoteEndPoint}", e);
                Client.Close();
            }

            _logger?.Debug($"Lost Client {_remoteEndPoint}");
        }
Exemple #37
0
        private async Task SendTextInternalSynchronized(ArraySegment <byte> message)
        {
            using (await _sendLocker.LockAsync().ConfigureAwait(false))
            {
                if (_isStopRequested != 0)
                {
                    return;
                }

                if (!IsOpen)
                {
                    _logger?.Warn(FormatLogMessage($"Client is not connected to server, cannot send:  {message}"));
                    return;
                }

                _logger?.Log(FormatLogMessage($"Sending: Type Text, length {message.Count}"));

                await _socket
                .SendAsync(message, WebSocketMessageType.Text, true, _stopCancellationTokenSource.Token)
                .ConfigureAwait(false);
            }
        }
Exemple #38
0
        private async Task HandleInvalidBlock(IBlock block, BlockValidationResult blockValidationResult)
        {
            _logger?.Warn(
                $"Invalid block {block.BlockHashToHex} : {blockValidationResult.ToString()}. Height: *{block.Index}*");

            MessageHub.Instance.Publish(new LockMining(false));

            // Handle the invalid blocks according to their validation results.
            if ((int)blockValidationResult < 100)
            {
                _blockSet.AddBlock(block);
            }
        }
        public static async Task ThrowIfModelIsInvalidAsync <TModel>(this TModel model, ILogger logger = null)
        {
            var result = await EnsureModelIsValidAsync(model);

            if (!result.IsValid)
            {
                logger?.Warn("Trying to execute business logic with invalid model - erorr(s): " +
                             $"{result.Errors.Count}, " +
                             $"{result.Errors.Aggregate(new StringBuilder(), (bldr, failure) => bldr.Append(failure.ErrorMessage).Append(", "))}");

                throw new ValidationException($"The model {model.GetType().FullName} is invalid", result.Errors);
            }
        }
Exemple #40
0
 public static bool TryAndReturnStatus(Action act, ILogger logger = null)
 {
     Assert.ArgumentNotNull(act, nameof(act));
     try
     {
         act();
         return(true);
     }
     catch (Exception e)
     {
         logger?.Warn(e, "Ignoring exception and returning false");
         return(false);
     }
 }
Exemple #41
0
        public static T TryGetOrDefault <T>(Func <T> func, ILogger logger = null)
        {
            Assert.ArgumentNotNull(func, nameof(func));

            try
            {
                return(func());
            }
            catch (Exception e)
            {
                logger?.Warn(e, "Ignoring exception and returning default value");
                return(default(T));
            }
        }
Exemple #42
0
 internal static void LogResult(JobResult result, ILogger logger, string jobName) {
     if (result != null) {
         if (result.IsCancelled)
             logger.Warn(result.Error, "Job run \"{0}\" cancelled: {1}", jobName, result.Message);
         else if (!result.IsSuccess)
             logger.Error(result.Error, "Job run \"{0}\" failed: {1}", jobName, result.Message);
         else if (!String.IsNullOrEmpty(result.Message))
             logger.Info("Job run \"{0}\" succeeded: {1}", jobName, result.Message);
         else
             logger.Trace("Job run \"{0}\" succeeded.", jobName);
     } else {
         logger.Error("Null job run result for \"{0}\".", jobName);
     }
 }
 static void WriteTestLog(ILogger logger)
 {
     logger.Info("输出信息");
     logger.Debug("测试信息");
     logger.Warn("警告信息");
     try
     {
         int i = 1, j = 0;
         i = i / j;
     }
     catch (Exception ex)
     {
         logger.Error(ex);
     }
 }
		private bool ProcessDeletion(RemotingPackageManifestEntry action, ILogger logger)
		{
			var currentItem = Factory.GetDatabase(action.Database).GetItem(new ID(action.ItemId));

			if (currentItem == null)
			{
				logger.Error("Cannot delete {0} because it had already been deleted.".FormatWith(action.ItemPath));
				return false;
			}

			currentItem.Delete();
			logger.Warn("[D] {0} [remoting]".FormatWith(new SitecoreSourceItem(currentItem).DisplayIdentifier));

			return true;
		}
        private static void ExitFromCurrentUowScope(ILogger logger)
        {
            var unitOfWorkKey = CallContext.LogicalGetData(ContextKey) as string;
            if (unitOfWorkKey == null)
            {
                logger.Warn("There is no current UOW to exit!");
                return;
            }

            IUnitOfWork unitOfWork;
            if (!UnitOfWorkDictionary.TryGetValue(unitOfWorkKey, out unitOfWork))
            {
                logger.Warn("There is a unitOfWorkKey in CallContext but not in UnitOfWorkDictionary");
                CallContext.FreeNamedDataSlot(ContextKey);
                return;
            }

            UnitOfWorkDictionary.TryRemove(unitOfWorkKey, out unitOfWork);
            if (unitOfWork.Outer == null)
            {
                CallContext.FreeNamedDataSlot(ContextKey);
                return;
            }

            // Restore outer UOW
            var outerUnitOfWorkKey = unitOfWork.Outer.Id;
            if (!UnitOfWorkDictionary.TryGetValue(outerUnitOfWorkKey, out unitOfWork))
            {
                // No Outer UOW
                logger.Warn("Outer UOW key could not found in UnitOfWorkDictionary!");
                CallContext.FreeNamedDataSlot(ContextKey);
                return;
            }

            CallContext.LogicalSetData(ContextKey, outerUnitOfWorkKey);
        }
        public static async Task CreateQueueIfNotExists(this NamespaceManager namespaceManager, ILogger logger, string queueIdentifier)
        {
            if (await namespaceManager.QueueExistsAsync(queueIdentifier))
                return;

            try
            {
                logger.Debug("Creating Queue:{0}", queueIdentifier);

                var queueDescription = new QueueDescription(queueIdentifier);
                await namespaceManager.CreateQueueAsync(queueDescription);
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                // the queue was created while we were trying to create it.
                logger.Warn("A queue with the name {0} already exists", queueIdentifier);
            }
        }
        public static async Task CreateTopicIfNotExists(this NamespaceManager namespaceManager, ILogger logger, string topicIdentifier)
        {
            if (await namespaceManager.TopicExistsAsync(topicIdentifier))
                return;

            try
            {
                logger.Debug("Creating topic:{0}", topicIdentifier);

                var topicDescription = new TopicDescription(topicIdentifier);
                await namespaceManager.CreateTopicAsync(topicDescription);
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                // the topic was created while we were trying to create it.
                logger.Warn("A topic with the name {0} already exists", topicIdentifier);
            }
        }
        public static async Task CreateSubscriptionIfNotExists(this NamespaceManager namespaceManager, ILogger logger, string topicIdentifier,
            string subscriptionIdentifier)
        {
            if (await namespaceManager.SubscriptionExistsAsync(topicIdentifier, subscriptionIdentifier))
                return;

            await namespaceManager.CreateTopicIfNotExists(logger, topicIdentifier);

            try
            {
                logger.Debug("Creating subscription:{0} for topic:{1}", subscriptionIdentifier, topicIdentifier);

                var subscriptionDescription = new SubscriptionDescription(topicIdentifier, subscriptionIdentifier);
                await namespaceManager.CreateSubscriptionAsync(subscriptionDescription);
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                // the subscription was created while we were trying to create it.
                logger.Warn("A subscription with the name {0} already exists", subscriptionIdentifier);
            }
        }
Exemple #49
0
 private static void LogWithLogger(LogItem logItem, ILogger logger)
 {
     switch (logItem.LogLevel)
     {
         case LogLevel.Trace:
             logger.Trace(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Info:
             logger.Info(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Warn:
             logger.Warn(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Error:
             logger.Error(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Fatal:
             logger.Fatal(() => logItem.Message, logItem.Exception);
             break;
     }
 }
        public PluginsLoadersManager(string pluginDirectory, IEnumerable<Tuple<string, string, string>> fileList, ILogger logger)
        {
            _loaders = new ConcurrentDictionary<string, Type>();
            SupportedExtensions = new List<string>();
            _logger = logger;

            string[] pluginFiles = Directory.GetFiles(pluginDirectory, "*.dll");
            foreach(var plugin in fileList)
            {
                var asm = Assembly.LoadFile(Path.Combine(pluginDirectory, plugin.Item3));
                var type = asm.GetExportedTypes().Where(t => plugin.Item2 == t.Name).FirstOrDefault();
                if (type == null)
                {
                    _logger.Warn(string.Format("Loader's type: {0} is not present in assembly: {1}", plugin.Item2, plugin.Item3));
                    continue;
                }
                    

                _loaders[plugin.Item1] = type;
                SupportedExtensions.Add(plugin.Item1);                
            }
        }
		public bool Replay(ILogger logger)
		{
			bool disableNewSerialization = UnicornDataProvider.DisableSerialization;
			try
			{
				UnicornDataProvider.DisableSerialization = true;

				bool success = true;
				foreach (var action in _package.Manifest.HistoryEntries)
				{
					switch (action.Action)
					{
						case HistoryAction.Deleted:
							success = ProcessDeletion(action, logger) && success;
							break;
						case HistoryAction.Created:
						case HistoryAction.Saved:
						case HistoryAction.AddedVersion:
						case HistoryAction.RemovedVersion:
							success = ProcessUpdate(action, logger) && success;
							break;
						case HistoryAction.Moved:
							success = ProcessMoved(action, logger) && success;
							break;
						default:
							logger.Warn("Unknown history entry {0} found for {1} - cannot process.".FormatWith(action.Action.ToString(), action.ItemPath));
							break;
					}
				}

				return success;
			}
			finally
			{
				UnicornDataProvider.DisableSerialization = disableNewSerialization;
			}
		}
 public static void CreateLogItems(ILogger logger)
 {
     foreach (var pocoLogItem in Session.List<PocoLogItem>(100).Get())
     {
         switch (pocoLogItem.LogLevel)
         {
             case LogLevel.Debug:
                 logger.Debug(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Info:
                 logger.Info(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Warning:
                 logger.Warn(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Error:
                 logger.Error(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Fatal:
                 logger.Fatal(pocoLogItem.Message, new Exception(pocoLogItem.Details));
                 break;
         }
     }
 }
Exemple #53
0
        public static bool IsInShare(ILogger log, string path, Share share)
        {
            try
            {
                // non-existent files don't yield results anyway, we might need to have them existent for the checks here later
                if (!File.Exists(path) && !Directory.Exists(path))
                    return false;

                // we should only get rooted paths, but check anyway
                if (!Path.IsPathRooted(path))
                    return false;

                // only check on parent directory path
                if (File.Exists(path))
                    path = Path.GetDirectoryName(path);

                // if share doesn't exist don't allow access
                if (!Directory.Exists(share.Path))
                    return false;

                // check if it's a subdir and log fails
                bool retval = IsSubdir(share.Path, path);
                if (!retval)
                {
                    log.Warn("Tried to access file {0} outside share {1}", path, share.Path);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                log.Error(String.Format("Exception druing IsInShare with path = {0}", path), ex);
            }
            return false;
        }
Exemple #54
0
        private static void Main(string[] args)
        {
            _logger = LogFactory.GetLogger(typeof (Program));

            IDatabaseInitializer<CashRegisterContext> seed;

            // Empty
            // seed = new EmptyInitializer();

            // Kalle Seed
            //seed = new CashProductInitializer();

            // Lærke Seed
            seed = new FullProductInitializer();

            using (var contex = new CashRegisterContext(seed))
            {
                Console.WriteLine("FLAF");
                contex.Database.Initialize(true);
                contex.SaveChanges();
            }

            IDalFacade dalFacade = new DalFacade();
            IProductDao pd = new ProductDao(dalFacade);
            IProductController pc = new ProductController(pd);

            SalesOrder o;

            using (var uow = dalFacade.UnitOfWork)
            {
                var d = new Discount
                {
                    Description = "Discount",
                    Percent = 0,
                };
                uow.DiscountRepository.Insert(d);
                uow.Save();

                o = new SalesOrder
                {
                    Date = DateTime.Now,
                    Status = OrderStatus.Created,
                };
                uow.SalesOrderRepository.Insert(o);

            }
            using (var uow = dalFacade.UnitOfWork)
            {

                var t = new Transaction
                {
                    Date = DateTime.Now,
                    Description = "Flaf",
                    PaymentType = PaymentType.Cash,
                    Price = 20,
                    SalesOrder = o,
                    Status = TransactionStatus.Created
                };
                uow.TransactionRepository.Insert(t);
                uow.Save();
            }

                Console.WriteLine("ProductTabs");
            foreach (var productTab in pc.ProductTabs)
            {
                Console.WriteLine(productTab.Priority + ": " + productTab.Name);
                foreach (var productType in productTab.ProductTypes)
                {
                    Console.WriteLine("\t" + productType.Name);
                    foreach (var productGroup in productType.ProductGroups)
                    {
                        Console.WriteLine("\t\t" + productGroup.Name);
                        foreach (var product in productGroup.Products)
                        {
                            Console.WriteLine("\t\t\t" + product.Name);
                        }
                    }
                }
            }

            _logger.Fatal("Fatal");
            _logger.Err("Error");
            _logger.Warn("Warn");
            _logger.Info("Info");
            _logger.Debug("Debug");
        }
 void SetInvalidValuesAndLog( ILogger logger, string reason, bool isWarning )
 {
     if( isWarning ) logger.Warn( reason );
     else logger.Info( reason );
     if( !InvalidValuesAlreadySet ) SetInvalidValues( reason );
 }
        private async Task<IResourceDataResult> GetCachedResourceDataAsync(IResourceDataRequest request, ILogger logger, CancellationToken cancellationToken)
        {
            // TODO isApiKeyCollectionQuery
            var cacheKey = this.GetCacheKey(request);
            if (string.IsNullOrEmpty(cacheKey))
            {
                logger.Warn($"Could not construct cacheKey for request {request.Uri}; aborting", "ReadCacheFilter.GetCachedResourceDataAsync");
                return null;
            }

            var data = await this.GetCachedValueAsync(request.Type, cacheKey, cancellationToken).ConfigureAwait(false);

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

            return new DefaultResourceDataResult(request.Action, request.Type, request.Uri, 200, data);
        }
        public override Tuple<Type, Assembly> CompileType(TypeContext context, ILogger logger) {
            if (context == null)
                throw new ArgumentNullException("context");

            var result = Compile(context);
            var compileResult = result.Item1;

            if (compileResult.Errors != null && compileResult.Errors.Count > 0) {
                logger.Warn("The following template content will not compile:");
                logger.Info(context.TemplateContent);
                foreach (var error in compileResult.Errors) {
                    logger.Error(error.ToString().Split(':').Last().Trim(' '));
                }
                throw new TemplateCompilationException(compileResult.Errors, result.Item2, context.TemplateContent);
            }

            return Tuple.Create(
                compileResult.CompiledAssembly.GetType("CompiledRazorTemplates.Dynamic." + context.ClassName),
                compileResult.CompiledAssembly);
        }
Exemple #58
0
        /// <summary>
        /// check whether all the specified users are admins of the page
        /// </summary>
        ///
        /// <param name="fbapp">
        /// Facebook application to use to retrieve data
        /// </param>
        ///
        /// <param name="pageId">
        /// ID of the page to be tested
        /// </param>
        ///
        /// <param name="userIds">
        /// IDs of all the users to be tested
        /// </param>
        ///
        /// <param name="log">
        /// logger to be used for error reporting
        /// </param>
        ///
        /// <returns>
        /// dictionary of all users specified as an input with values of admin
        /// flag
        /// </returns>
        public static Dictionary<string, bool> AreAdmins(
            FacebookClient fbapp,
            long pageId,
            string[] userIds,
            ILogger log)
        {
            var index = 0;
            var requests = new object[userIds.Length];
            foreach (var userId in userIds)
            {
                var url = string.Format("{0}/admins/{1}", pageId, userId);

                var singleRequest = new
                {
                    method = "GET",
                    relative_url = url
                };

                requests[index] = singleRequest;
                index++;
            }

            var batchRequest = new Dictionary<string, object> { { "batch", requests } };

            index = 0;
            var admins = new Dictionary<string, bool>();
            try
            {
                dynamic rslts = fbapp.Post("https://graph.facebook.com/",
                    batchRequest);
                foreach (var rslt in rslts)
                {
                    // does the result contain the name of the admin
                    var isAdmin = rslt.body.Contains("name");
                    admins.Add(userIds[index], isAdmin);
                    index++;
                }
            }
            catch (FacebookApiException e)
            {
                if (log != null)
                {
                    log.Warn("Failed to retrieve admins", e);
                }
            }
            return admins;
        }
        /// <summary>
        /// Initializes a new <see cref="SimpleRepositoryInfo"/> based on a (more complex) <see cref="Info"/>.
        /// </summary>
        /// <param name="logger">Logger that will be used.</param>
        /// <param name="info">The simplified repository information.</param>
        public SimpleRepositoryInfo( ILogger logger, RepositoryInfo info )
        {
            if( logger == null ) throw new ArgumentNullException( nameof(logger) );
            if( info == null ) throw new ArgumentNullException( nameof( info ) );

            Info = info;
            if( !HandleRepositoryInfoError( logger, info ) )
            {
                CommitSha = info.CommitSha;
                CommitDateUtc = info.CommitDateUtc;
                var t = info.ValidReleaseTag;
                // Always warn on non standard pre release name.
                if( t != null && t.IsPreRelease && !t.IsPreReleaseNameStandard )
                {
                    logger.Warn( "Non standard pre release name '{0}' is mapped to '{1}'.", t.PreReleaseNameFromTag, t.PreReleaseName );
                }
                if( info.IsDirty && !info.Options.IgnoreDirtyWorkingFolder )
                {
                    SetInvalidValuesAndLog( logger, "Working folder has non committed changes.", false );
                    logger.Info( info.IsDirtyExplanations );
                }
                else
                {
                    Debug.Assert( info.PossibleVersions != null );
                    if( info.IsDirty )
                    {
                        logger.Warn( "Working folder is Dirty! Checking this has been disabled since RepositoryInfoOptions.IgnoreDirtyWorkingFolder is true." );
                        logger.Warn( info.IsDirtyExplanations );
                    }
                    if( info.PreviousRelease != null )
                    {
                        logger.Trace( "Previous release found '{0}' on commit '{1}'.", info.PreviousRelease.ThisTag, info.PreviousRelease.CommitSha );
                    }
                    if( info.PreviousMaxRelease != null && info.PreviousMaxRelease != info.PreviousRelease )
                    {
                        logger.Trace( "Previous max release found '{0}' on commit '{1}'.", info.PreviousMaxRelease.ThisTag, info.PreviousMaxRelease.CommitSha );
                    }
                    if( info.PreviousRelease == null && info.PreviousMaxRelease == null )
                    {
                        logger.Trace( "No previous release found'." );
                    }

                    if( info.CIRelease != null )
                    {
                        IsValidCIBuild = true;
                        SetNumericalVersionValues( info.CIRelease.BaseTag, true );
                        NuGetVersion = info.CIRelease.BuildVersionNuGet;
                        SemVer = info.CIRelease.BuildVersion;
                        logger.Info( "CI release: '{0}'.", SemVer );
                        LogValidVersions( logger, info );
                    }
                    else
                    {
                        if( t == null )
                        {
                            SetInvalidValuesAndLog( logger, "No valid release tag.", false );
                            LogValidVersions( logger, info );
                        }
                        else
                        {
                            IsValidRelease = true;
                            OriginalTagText = t.OriginalTagText;
                            SetNumericalVersionValues( t, false );
                            NuGetVersion = t.ToString( ReleaseTagFormat.NuGetPackage );
                            SemVer = t.ToString( ReleaseTagFormat.SemVerWithMarker );
                            logger.Info( "Release: '{0}'.", SemVer );
                        }
                    }
                }
            }
            MajorMinor = string.Format( "{0}.{1}", Major, Minor );
            MajorMinorPatch = string.Format( "{0}.{1}", MajorMinor, Patch );
        }
        private IResourceDataResult GetCachedResourceData(IResourceDataRequest request, ILogger logger)
        {
            // TODO isApiKeyCollectionQuery
            var cacheKey = this.GetCacheKey(request);
            if (string.IsNullOrEmpty(cacheKey))
            {
                logger.Warn($"Could not construct cacheKey for request {request.Uri}; aborting", "ReadCacheFilter.GetCachedResourceData");
                return null;
            }

            var data = this.GetCachedValue(request.Type, cacheKey);

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

            return new DefaultResourceDataResult(request.Action, request.Type, request.Uri, 200, data);
        }