Example #1
0
        //Field.Store.YES:存储字段值(未分词前的字段值)
        //Field.Store.NO:不存储,存储与索引没有关系
        //Field.Store.COMPRESS:压缩存储,用于长文本或二进制,但性能受损

        //Field.Index.ANALYZED:分词建索引
        //Field.Index.ANALYZED_NO_NORMS:分词建索引,但是Field的值不像通常那样被保存,而是只取一个byte,这样节约存储空间
        //Field.Index.NOT_ANALYZED:不分词且索引
        //Field.Index.NOT_ANALYZED_NO_NORMS:不分词建索引,Field的值去一个byte保存

        //TermVector表示文档的条目(由一个Document和Field定位)和它们在当前文档中所出现的次数
        //Field.TermVector.YES:为每个文档(Document)存储该字段的TermVector
        //Field.TermVector.NO:不存储TermVector
        //Field.TermVector.WITH_POSITIONS:存储位置
        //Field.TermVector.WITH_OFFSETS:存储偏移量
        //Field.TermVector.WITH_POSITIONS_OFFSETS:存储位置和偏移量

        #endregion

        #endregion 批量BuildIndex 索引合并

        #region 单个/批量索引增删改

        /// <summary>
        /// 新增一条数据的索引
        /// </summary>
        /// <param name="model"></param>
        /// <param name="fieldModelList"></param>
        public void InsertIndex(T model, IEnumerable <FieldDataModel> fieldModelList)
        {
            IndexWriter writer = null;

            try
            {
                if (model == null)
                {
                    return;
                }
                string rootIndexPath            = StaticConstant.IndexPath;
                System.IO.DirectoryInfo dirInfo = System.IO.Directory.CreateDirectory(rootIndexPath);

                bool      isCreate  = dirInfo.GetFiles().Count() == 0;          //下面没有文件则为新建索引
                Directory directory = FSDirectory.Open(dirInfo);
                writer                 = new IndexWriter(directory, CreateAnalyzerWrapper(fieldModelList), isCreate, IndexWriter.MaxFieldLength.LIMITED);
                writer.MergeFactor     = 100;            //控制多个segment合并的频率,默认10
                writer.UseCompoundFile = true;           //创建符合文件 减少索引文件数量
                CreateModelIndex(writer, model, fieldModelList);
            }
            catch (Exception ex)
            {
                m_logger.Error("InsertIndex异常", ex);
            }
            finally
            {
                if (writer != null)
                {
                    //if (fileNum > 50)
                    //    writer.Optimize();
                    writer.Dispose();
                }
            }
        }
        public Task <List <RepositoryCommit> > GetLastCommitsAsync(Project entity, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo, CustomLogger runnerLogger, int count)
        {
            return(Task.Run(async() =>
            {
                var info = authInfo as AuthInfo;
                if (info == null)
                {
                    return null;
                }

                try
                {
                    var checkoutResult = await ImportAsync(entity, appConfiguration, authInfo, runnerLogger);
                    if (checkoutResult.HasErrors)
                    {
                        return null;
                    }

                    List <RepositoryCommit> result = null;
                    using (var client = new SharpSvn.SvnClient())
                    {
                        //client.Authentication.DefaultCredentials = new NetworkCredential(info.Username, info.Password);

                        if (client.GetLog(checkoutResult.CheckOutDirectory, new SharpSvn.SvnLogArgs()
                        {
                            Limit = count
                        }, out var items))
                        {
                            result = items
                                     .Select(x => new RepositoryCommit(x.Revision.ToString(), x.LogMessage, x.Time.ToUniversalTime(), $"{x.Author}"))
                                     .ToList();
                        }
                    }

                    try
                    {
                        // Clean up the directory.
                        Directory.Delete(checkoutResult.CheckOutDirectory, recursive: true);
                    }
                    catch (Exception exp)
                    {
                        runnerLogger.Error(exp);
                    }

                    return result;
                }
                catch (Exception exp)
                {
                    runnerLogger.Error(exp);

                    return null;
                }
            }));
        }
Example #3
0
    private void SpawnDate()
    {
        if (!LevelDataManager.Instance.TryGetNPCSpawnPoint(DateSpawnPointId, out Transform spawnpoint))
        {
            CustomLogger.Error(nameof(DateStateManager), $"Could not find spawnpoint with id \"{DateSpawnPointId}\"");
            return;
        }
        if (!PooledObjectManager.Instance.UsePooledObject(_dateData.UnitPrefabId, out PooledObject pooledObject))
        {
            CustomLogger.Error(nameof(DateStateManager), $"Could not retrieve pooled object with id \"{_dateData.UnitPrefabId}\"");
            return;
        }
        DateInitializationData initData = new DateInitializationData();

        initData.OverrideUniqueId = _dateData.UnitPrefabId;
        initData.UnitData         = _dateData;
        DateUnit dateUnit = pooledObject as DateUnit;

        dateUnit.Initialize(initData);
        dateUnit.transform.position = spawnpoint.position;
        dateUnit.Spawn();
        dateUnit.TargetManager.OnCurrentTargetSet += OnDateCurrentTargetSet;
        dateUnit.OnUnitDefeated += DateDefeated;
        OnDateSpawned?.Invoke();
    }
        public EmailNotificationResponse SendEmail(NotifyEmail notifyEmail)
        {
            if (EmailIsAnonymised(notifyEmail.EmailAddress))
            {
                return(null);
            }

            try
            {
                EmailNotificationResponse response = _client.SendEmail(
                    notifyEmail.EmailAddress,
                    notifyEmail.TemplateId,
                    notifyEmail.Personalisation);

                return(response);
            }
            catch (NotifyClientException e)
            {
                CustomLogger.Error(
                    "EMAIL FAILURE: Error whilst sending email using Gov.UK Notify",
                    new {
                    NotifyEmail            = notifyEmail,
                    Personalisation        = JsonConvert.SerializeObject(notifyEmail.Personalisation),
                    ErrorMessageFromNotify = e.Message
                });
                throw;
            }
        }
Example #5
0
    public bool RegisterPooledObject(string poolId, int count, Action <bool> OnRegisterComplete = null)
    {
        PooledObjectEntry entry;

        if (_objectPool.TryGetValue(poolId, out entry))
        {
            return(true);
        }
        GameObject storedPrefab = AssetManager.Instance.GetAsset(poolId);

        if (storedPrefab == null)
        {
            CustomLogger.Error(nameof(PooledObjectManager), $"Failed to register object with id {poolId}");
            return(false);
        }

        PooledObject pooledObject = storedPrefab.GetComponent <PooledObject>();

        if (pooledObject == null)
        {
            CustomLogger.Error(nameof(PooledObjectManager), $"Asset is not a pooled object!");
            return(false);
        }
        PooledObjectEntry newEntry = new PooledObjectEntry()
        {
            BaseResource     = storedPrefab,
            AvailableObjects = new List <PooledObject>(),
            InUseObjects     = new List <PooledObject>()
        };

        _objectPool.Add(poolId, newEntry);
        CloneToPool(poolId, newEntry.BaseResource, count);
        return(true);
    }
    // instantiate a new UI object with a given prefab id, onto a specified layer
    public UIObject CreateNewUIObject(string uiPrefabId, UILayerId layerId)
    {
        if (_activeUI.ContainsKey(uiPrefabId))
        {
            CustomLogger.Error(nameof(UIManager), $"Already contains active UI with prefab Id {uiPrefabId}!");
            return(null);
        }
        if (!_uiLayers.TryGetValue(layerId, out UILayer layer))
        {
            CustomLogger.Error(nameof(UIManager), $"Layer Id {layerId} not found!");
            return(null);
        }
        GameObject obj = AssetManager.Instance.GetAsset(uiPrefabId);

        if (obj == null)
        {
            CustomLogger.Error(nameof(UIManager), $"Could not retrieve prefab for id {uiPrefabId}!");
            return(null);
        }
        UIObject uiObject = obj.GetComponent <UIObject>();

        if (uiObject == null)
        {
            CustomLogger.Error(nameof(UIManager), $"Prefab {uiPrefabId} did not contain type {nameof(UIObject)}!");
            return(null);
        }
        UILayer       parent            = _uiLayers[layerId];
        UIObject      instancedUIObject = Instantiate(uiObject, _uiLayers[layerId].transform);
        UIObjectEntry newEntry          = new UIObjectEntry(layerId, instancedUIObject);

        _activeUI.Add(uiPrefabId, newEntry);
        CustomLogger.Log(nameof(UIManager), $"Creating ui object with prefab id {uiPrefabId}");
        return(instancedUIObject);
    }
 private void RegisterPooledObjects()
 {
     if (!PooledObjectManager.Instance.RegisterPooledObject(NPCUIDisplayPrefabId, 20))
     {
         CustomLogger.Error(nameof(NPCUIDisplayManager), $"Failed to register object with id {NPCUIDisplayPrefabId}");
     }
 }
        public override Task ExecuteResultAsync(ActionContext actionContext)
        {
            string message;

            if (Enum.IsDefined(typeof(HttpStatusCode), StatusCode.Value))
            {
                message = $"{(HttpStatusCode)StatusCode.Value} ({StatusCode.Value}):  {StatusDescription}";
            }
            else
            {
                message = $"HttpStatusCode ({StatusCode.Value}):  {StatusDescription}";
            }
            if (StatusCode == 404 || StatusCode == 405)
            {
                CustomLogger.Warning(message);
            }
            else if (StatusCode >= 500)
            {
                CustomLogger.Fatal(message);
            }
            else if (StatusCode >= 400)
            {
                CustomLogger.Error(message);
            }

            ViewName = "Error";
            ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), actionContext.ModelState)
            {
                Model = new ErrorViewModel((int)StatusCode)  // set the model
            };

            return(base.ExecuteResultAsync(actionContext));
        }
 public static bool TryParseAssetBundlePath(string assetName, out string filePath)
 {
     filePath = "";
     string[] assetNameComponents = assetName.Split(AssetNameSplitter);
     // this should be split into 2 parts
     if (assetNameComponents.Length != 2)
     {
         CustomLogger.Error(nameof(IAssetManager), $"{assetName} is an invalid asset name!");
         return(false);
     }
     string[] filePathComponents = assetNameComponents[0].Split(AssetBundlePathSplitter);
     // file path components should be greater than 0
     if (filePathComponents.Length == 0)
     {
         return(false);
     }
     filePath = filePathComponents[0];
     for (int i = 1; i < filePathComponents.Length; i++)
     {
         string component = filePathComponents[i].ToLower();
         filePath = $"{filePath}/{component}";
     }
     filePath = $"Assets/BundledResources/{filePath}";
     return(true);
 }
 private void SendReminderEmailsForSectorType(
     User user,
     List <Organisation> inScopeOrganisationsForUserAndSectorTypeThatStillNeedToReport,
     SectorTypes sectorType)
 {
     try
     {
         bool anyOrganisationsToEmailAbout = inScopeOrganisationsForUserAndSectorTypeThatStillNeedToReport.Count > 0;
         if (anyOrganisationsToEmailAbout)
         {
             SendReminderEmail(user, sectorType, inScopeOrganisationsForUserAndSectorTypeThatStillNeedToReport);
         }
         SaveReminderEmailRecord(user, sectorType, anyOrganisationsToEmailAbout);
     }
     catch (Exception ex)
     {
         CustomLogger.Error(
             "Failed whilst sending or saving reminder email",
             new
         {
             user.UserId,
             SectorType      = sectorType,
             OrganisationIds = inScopeOrganisationsForUserAndSectorTypeThatStillNeedToReport.Select(o => o.OrganisationId),
             Exception       = ex.Message
         });
     }
 }
Example #11
0
        public override Task ExecuteResultAsync(ActionContext actionContext)
        {
            string message;

            if (Enum.IsDefined(typeof(HttpStatusCode), StatusCode.Value))
            {
                message = $"{(HttpStatusCode) StatusCode.Value} ({StatusCode.Value}):  {StatusDescription}";
            }
            else
            {
                message = $"HttpStatusCode ({StatusCode.Value}):  {StatusDescription}";
            }
            if (StatusCode == 404 || StatusCode == 405)
            {
                CustomLogger.Warning(message);
            }
            else if (StatusCode >= 500)
            {
                CustomLogger.Fatal(message);
            }
            else if (StatusCode >= 400)
            {
                CustomLogger.Error(message);
            }

            return(base.ExecuteResultAsync(actionContext));
        }
        [Obsolete("Please use method 'Employer' instead.")] //, true)]
        public IActionResult EmployerDetails(string e = null, int y = 0, string id = null)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                Organisation organisation;

                try
                {
                    CustomResult <Organisation> organisationLoadingOutcome =
                        OrganisationBusinessLogic.GetOrganisationByEncryptedReturnId(id);

                    if (organisationLoadingOutcome.Failed)
                    {
                        return(organisationLoadingOutcome.ErrorMessage.ToHttpStatusViewResult());
                    }

                    organisation = organisationLoadingOutcome.Result;
                }
                catch (Exception ex)
                {
                    CustomLogger.Error("Cannot decrypt return id from query string", ex);
                    return(View("CustomError", new ErrorViewModel(400)));
                }

                string organisationIdEncrypted = organisation.GetEncryptedId();
                return(RedirectToActionPermanent(nameof(Employer), new { employerIdentifier = organisationIdEncrypted }));
            }

            if (string.IsNullOrWhiteSpace(e))
            {
                return(new HttpBadRequestResult("EmployerDetails: \'e\' query parameter was null or white space"));
            }

            return(RedirectToActionPermanent(nameof(Employer), new { employerIdentifier = e }));
        }
Example #13
0
    public void DeregisterPooledObject(string objectId)
    {
        // assert that a pool with this id exists
        if (!_objectPool.ContainsKey(objectId))
        {
            CustomLogger.Error(nameof(PooledObjectManager), $"Does not contain entry with id {objectId}!");
            return;
        }
        // despawn all currently active pooled objects
        List <PooledObject> objsToRemove = new List <PooledObject>();

        for (int i = 0; i < _objectPool[objectId].InUseObjects.Count; i++)
        {
            PooledObject pooledObject = _objectPool[objectId].InUseObjects[i];
            pooledObject.Despawn();
            pooledObject.Dispose();
            objsToRemove.Add(pooledObject);
        }
        _objectPool[objectId].AvailableObjects.AddRange(objsToRemove);
        // remove all existing pooled objects
        foreach (PooledObject pooledObject in _objectPool[objectId].AvailableObjects)
        {
            GameObject go = _objectPool[objectId].GameObjects[pooledObject];
            Destroy(go);
        }
        _objectPool.Remove(objectId);
    }
Example #14
0
    protected virtual void GenerateSoundBox(Unit unit)
    {
        PooledObject weaponSoundBoxPO;

        if (!PooledObjectManager.Instance.UsePooledObject(WeaponSoundBoxId, out weaponSoundBoxPO))
        {
            CustomLogger.Error(this.name, $"Could not retrieve weapon sound box pooled object with id: {WeaponSoundBoxId}");
            return;
        }
        WeaponSoundBox soundBox = weaponSoundBoxPO as WeaponSoundBox;

        if (soundBox == null)
        {
            CustomLogger.Error(this.name, $"Object {weaponSoundBoxPO} was not of type {nameof(WeaponSoundBox)}");
            return;
        }
        WeaponSoundBoxInitializationData initData = new WeaponSoundBoxInitializationData()
        {
            TargetSize    = _soundBoxSize,
            StartPosition = unit.MoveController.Front.position,
            Source        = unit
        };

        soundBox.Initialize(initData);
        soundBox.Spawn();
    }
 private void OnStateEnterFailed()
 {
     IsActive  = false;
     Active    = false;
     IsLoading = false;
     OnGameStateEnterFailed?.Invoke();
     CustomLogger.Error(this.name, $"Failed to enter state {StateId}!");
 }
Example #16
0
 private void Awake()
 {
     if (Instance != null)
     {
         CustomLogger.Error(this.name, $"There should not be more than 1 {nameof(PooledObjectManager)} instances at a time!");
     }
     Instance = this;
 }
Example #17
0
 public override QuestObjectiveState CreateState()
 {
     if (!LevelDataManager.Instance.TryGetEnemySpawn(_spawnId, out EnemySpawn spawn))
     {
         CustomLogger.Error(nameof(EliminateTargetObjective), $"Could not retrieve enemy spawn point with id {_spawnId}!");
         return(null);
     }
     return(new EliminateTargetQuestState(this, spawn));
 }
Example #18
0
        public void OnException(ExceptionContext exceptionContext)
        {
            if (exceptionContext.Exception == null)
            {
                return;
            }

            CustomLogger.Error(exceptionContext.Exception);
        }
        public Task <List <RepositoryCommit> > GetLastCommitsAsync(Project entity, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo,
                                                                   CustomLogger runnerLogger,
                                                                   int count)
        {
            return(Task.Run(async() =>
            {
                var importResult = await ImportAsync(entity, appConfiguration, authInfo, runnerLogger);
                if (importResult.HasErrors)
                {
                    return null;
                }

                try
                {
                    List <RepositoryCommit> result = new List <RepositoryCommit>(0);

                    using (var repo = new Repository(importResult.CheckOutDirectory))
                    {
                        result = repo.Commits
                                 .Take(count)
                                 .Select(x => new RepositoryCommit(x.Id.Sha, x.Message, x.Author.When.UtcDateTime, $"{x.Author.Name} - {x.Author.Email}"))
                                 .ToList();
                    }

                    // Clean up. We no longer need the pository.
                    try
                    {
                        Directory.Delete(importResult.CheckOutDirectory, true);
                    }
                    catch (Exception exp)
                    {
                        runnerLogger.Error(exp);
                    }

                    return result;
                }
                catch (Exception exp)
                {
                    runnerLogger.Error(exp);

                    return null;
                }
            }));
        }
Example #20
0
        public void DeleteById(int?id)
        {
            if (!id.HasValue)
            {
                CustomLogger.Error("Error in Direction Service", new ValidationException("The Direction's id value is not set"));
            }

            Database.Directions.DeleteById(id.Value);
            Database.Save();
        }
Example #21
0
        public IEnumerable <UserTaskDTO> GetUserTasks(int?id)
        {
            if (!id.HasValue)
            {
                CustomLogger.Error("Error in Task Service", new ValidationException("The task id value is not set", string.Empty));
            }

            return(_mapper.Map <IEnumerable <UserTask>, ICollection <UserTaskDTO> >(Database.Tasks.
                                                                                    GetById(id.Value).UserTasks));
        }
Example #22
0
    public GameObject GetAsset(string assetName)
    {
        GameObject go;

        if (!_prefabRegistry.TryGetValue(assetName, out go))
        {
            CustomLogger.Error(nameof(AssetManager), $"Could not find object with name {assetName}");
        }
        return(go);
    }
Example #23
0
        private void LogThrottle(ApiRequestBase request, bool isTotalShutdown, string shutDownMessage)
        {
            int auditId = 0;

            auditId = this.InsertAudit(request.sAPIKey, request.iTradingPartnerID, request.sEmailAddress, name, auditId);

            _logger.SetAuditId(auditId);

            _logger.Error(name + " - " + (isTotalShutdown ? shutDownMessage : Message));
        }
        public static async Task <ReadOnlyCollection <BuildResult> > BuildTargetsAsync(string checkOutDirectory, BuildTarget[] targets,
                                                                                       ReadOnlyCollection <ISourceCodeBuilderStrategy> strategies,
                                                                                       CustomLogger customLogger)
        {
            var result = new List <BuildResult>();

            foreach (var t in targets)
            {
                var sourcePath = Path.Combine(checkOutDirectory, t.TargetRelativePath);
                var outPath    = Path.Combine(checkOutDirectory, t.Name);

                customLogger.Information($"Building Target: {t.Type} {t.Name} {t.TargetRelativePath}");

                BuildStrategyResult currentResult = default;
                var strategy = strategies.FirstOrDefault(x => x.Type == t.Type);

                if (strategy == null)
                {
                    customLogger.Error($"Unknown build target type: {t.Type}");
                    continue;
                }

                currentResult = await strategy.BuildAsync(t, sourcePath, outPath, customLogger);

                if (currentResult.IsError)
                {
                    customLogger.Error($"Output: IsError: {currentResult.IsError}");
                    customLogger.Error(currentResult.Output);
                }
                else
                {
                    customLogger.Information($"Output: IsError: {currentResult.IsError}");
                    customLogger.Information(currentResult.Output);
                }

                customLogger.Information(string.Empty);

                result.Add(new BuildResult(t, outPath, currentResult.IsError));
            }

            return(result.AsReadOnly());
        }
Example #25
0
        public async Task <bool> DeleteByIdAsync(int?id)
        {
            if (!id.HasValue)
            {
                CustomLogger.Error("Error in Task Service", new ValidationException("The task id value is not set", string.Empty));
            }

            var task = await Database.Tasks.DeleteByIdAsync(id.Value);

            return(task != null ? true : false);
        }
Example #26
0
        public DirectionDTO GetById(int id)
        {
            var direction = Database.Directions.GetById(id);

            if (direction == null)
            {
                CustomLogger.Error("Error in Direction Service", new ValidationException($"The Direction with id = ${id} was not found", string.Empty));
            }

            return(_mapper.Map <Direction, DirectionDTO>(direction));
        }
Example #27
0
        public TaskDTO GetById(int id)
        {
            var task = Database.Tasks.GetById(id);

            if (task == null)
            {
                CustomLogger.Error("Error in Task Service", new ValidationException($"The task with id = {id} was not found", string.Empty));
            }

            return(_mapper.Map <DimsTask, TaskDTO>(task));
        }
Example #28
0
    public void RemoveOccupant(IntVector3 position, ITileOccupant occupant)
    {
        if (!IsWithinMap(position))
        {
            CustomLogger.Error(nameof(LevelDataManager), $"Position {position} is out of bounds!");
            return;
        }
        ITileInfo tileInfo = _tiles[position.x][position.y];

        tileInfo.RemoveOccupant(occupant);
    }
Example #29
0
        public void DeleteById(int?id)
        {
            if (!id.HasValue)
            {
                CustomLogger.Error("Error in Task Service", new ValidationException("The Task id value is not set", string.Empty));
            }

            Database.Tasks.DeleteById(id.Value);

            Database.Save();
        }
 // destroy a given UI object with a given prefab id
 public void RemoveUIObject(string uiPrefabId)
 {
     if (!_activeUI.TryGetValue(uiPrefabId, out UIObjectEntry entry))
     {
         CustomLogger.Error(nameof(UIManager), $"Could not find UI Prefab with id {uiPrefabId}");
         return;
     }
     entry.UIObject.CleanUp();
     Destroy(entry.UIObject.gameObject);
     _activeUI.Remove(uiPrefabId);
 }