Example #1
0
        //public JobLogger(IConfig config, int skipFrames)
        //{
        //    _pageName = config.SessionContext.PageName;
        //    _aspSessionId = config.SessionContext.AspSessionId;
        //    _sessionId = config.SessionContext.SessionId;
        //    _clientIp = config.SessionContext.ClientIp;
        //    _syslog = GetLogger(config, skipFrames);
        //}
        protected override void WriteOutput(string message, Severity severity, LogTo logTo)
        {
            if (logTo.HasFlag(LogTo.File))
            {
                _fileHandler.WriteMessage(message, severity.ToString());
            }
            if (logTo.HasFlag(LogTo.DataBase))
            {
                _logDataAccess.InsertMessage(message, (int) severity);
            }
            if (logTo.HasFlag(LogTo.Console))
            {
                //TODO:implements console
                switch(severity)
                {
                    case Severity.Message:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                    case Severity.Warning:
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        break;
                    case Severity.Error:
                        Console.ForegroundColor = ConsoleColor.Red;
                        break;
                    default:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                }

                Console.WriteLine("{0} {1}", DateTime.Now.ToShortDateString(), message);
            }
        }
Example #2
0
 public void LogMessage(string message, LoggerBase.Severity severity, LogTo logTo)
 {
     try
     {
         this.WriteOutput(message, severity, logTo);
     }
     catch(Exception ex)
     {
         this.WriteOutput(ex.Message, Severity.Error, logTo);
     }
 }
 public void ReportError(string message)
 {
     LogTo.Error(message);
 }
 public void LogErrors()
 {
     LogTo.Debug(new Exception(), "Debug");
     LogTo.Info(new Exception(), "Info");
     LogTo.Warning(new Exception(), "Warn");
 }
    public void DelegateMethod()
    {
        Action action = () => LogTo.Debug("Foo");

        action();
    }
        public async Task <IList <MutationDocument> > CreateMutationsAsync(UnimaConfig config, IList <IMutator> mutationOperators)
        {
            try
            {
                var workspace = MSBuildWorkspace.Create();

                LogTo.Info("Opening solution..");
                var solution = await workspace.OpenSolutionAsync(config.SolutionPath);

                LogTo.Info("Starting to analyze test..");

                var list = new List <MutationDocument>();

                foreach (var mutationProjectInfo in config.MutationProjects)
                {
                    var currentProject = solution.Projects.FirstOrDefault(p => p.Name == mutationProjectInfo.Name);

                    if (currentProject == null)
                    {
                        LogTo.Error($"Could not find any project with the name {mutationProjectInfo.Name}");
                        continue;
                    }

                    var documentIds = currentProject.DocumentIds;

                    LogTo.Info($"Starting to create mutations for {currentProject.Name}..");
                    foreach (var documentId in documentIds)
                    {
                        try
                        {
                            var document = currentProject.GetDocument(documentId);

                            if (config.Filter != null && !config.Filter.ResourceAllowed(document.FilePath))
                            {
                                LogTo.Info($"Ignoring {document.Name}.");
                                continue;
                            }

                            LogTo.Info($"Creating mutation for {document.Name}..");

                            var root = document.GetSyntaxRootAsync().Result;
                            var mutationDocuments = new List <MutationDocument>();

                            foreach (var mutationOperator in mutationOperators)
                            {
                                var mutatedDocuments = mutationOperator.GetMutatedDocument(root, document);
                                mutationDocuments.AddRange(mutatedDocuments.Where(m => config.Filter == null || config.Filter.ResourceLinesAllowed(document.FilePath, GetDocumentLine(m))));
                            }

                            list.AddRange(mutationDocuments);
                        }
                        catch (Exception ex)
                        {
                            LogTo.Error("Error when creating mutation: " + ex.Message);
                        }
                    }
                }

                if (!list.Any())
                {
                    LogTo.Warn("Could not find a single mutation. Maybe check your filter?");
                }

                return(list);
            }
            catch (Exception ex)
            {
                LogTo.ErrorException("Unknown exception when creating mutation documents", ex);
                throw new MutationDocumentException("Unknown exception when creating mutation documents", ex);
            }
        }
Example #7
0
 public override void Debug(string msg,
                            params object[] args)
 {
     LogTo.Debug(msg,
                 args);
 }
 void AddUnsupportedKey(string key)
 {
     LogTo.Warning("Key '{key}' is not supported.", key);
     unsupportedKeys.Add(key);
 }
 public async void AsyncMethod()
 {
     LogTo.Debug();
 }
 public void LogErrors()
 {
     LogTo.DebugException("Debug", new Exception());
     LogTo.InfoException("Info", new Exception());
     LogTo.WarnException("Warn", new Exception());
 }
Example #11
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     LogTo.Information("Background task CvLab.MicroserviceTemplate2 started");
 }
Example #12
0
        public void CommitFromMemory(
            IRegistryFileDescriptor registryFileDesc,
            SparseClusteredArray <byte> memSCA,
            SparseClusteredArray <byte> rtxSCA)
        {
            memSCA.Lock.EnterUpgradeableReadLock();
            rtxSCA.Lock.EnterUpgradeableReadLock();

            try
            {
                foreach (var memStream in memSCA.GetStreams())
                {
                    var memElems = memStream.StreamToStruct <RegMemElem17, RegMemElem17>(
                        RegMemElem17.SizeOfMemElem,
                        e => e
                        );

                    foreach (var memElemKeyValue in memElems.OrderBy(kv => kv.Value.rtxOffset))
                    {
                        var id      = memElemKeyValue.Key;
                        var memElem = memElemKeyValue.Value;

                        var lower = memElem.rtxOffset - 1;
                        var upper = memElem.rtxOffset + memElem.rtxLength - 2;

                        if (upper < lower || upper < 0)
                        {
                            LogTo.Warning(
                                "({RegistryName}) Invalid rtx offsets, upper: {Upper}, lower: {Lower}",
                                registryFileDesc.RegistryName,
                                upper, lower);
                            continue;
                        }

                        SparseClusteredArray <byte> .Bounds rtxBounds = new SparseClusteredArray <byte> .Bounds(
                            lower,
                            upper
                            );

                        using (var rtStream = rtxSCA.GetSubsetStream(rtxBounds))
                        {
                            RegRtElem17 rtxElem = default;

                            if (rtStream != null)
                            {
                                rtxElem = ParseRtStream(rtStream,
                                                        memElem);
                            }

                            Commit(id, memElem, rtxElem);
                        }
                    }
                }

                memSCA.Clear();
                rtxSCA.Clear();
            }
            finally
            {
                memSCA.Lock.ExitUpgradeableReadLock();
                rtxSCA.Lock.ExitUpgradeableReadLock();
            }
        }
Example #13
0
        public static async Task <CreationResult> Create(
            string urlOrId,
            double startTime    = 0,
            double endTime      = -1,
            int parentElementId = -1,
            double watchPoint   = 0,
            ViewMode viewMode   = MediaPlayerConst.DefaultViewMode,
            bool shouldDisplay  = true)
        {
            // TODO: Time the verification check
            JObject metadata = await YdlUtils.GetYouTubeVideoMetadata(urlOrId);

            if (metadata == null || string.IsNullOrWhiteSpace((string)metadata["id"]))
            {
                LogTo.Warning($"Failed to recognise {urlOrId} as a YouTube video");
                return(CreationResult.FailUnknown);
            }

            YouTubeMediaElement ytEl;
            string youtubeId    = (string)metadata["id"];
            string title        = (string)metadata["title"];
            string uploader     = (string)metadata["uploader"];
            string date         = (string)metadata["upload_date"];
            string thumbnailUrl = (string)metadata["thumbnail"];

            ytEl = new YouTubeMediaElement
            {
                Id         = youtubeId,
                StartTime  = startTime,
                EndTime    = endTime,
                WatchPoint = watchPoint,
                ViewMode   = viewMode,
            };

            List <ContentBase> contents = new List <ContentBase>();

            string elementHtml = string.Format(CultureInfo.InvariantCulture,
                                               MediaPlayerConst.YouTubeElementFormat,
                                               title,
                                               ytEl.GetJsonB64());

            contents.Add(new TextContent(true, elementHtml));
            if (Config.IncludeYouTubeThumbnail)
            {
                Image img = DownloadThumbnail(thumbnailUrl);
                if (img != null)
                {
                    var imgContent = ContentEx.CreateImageContent(img, string.Format(YTConst.VideoThumbImgRegPath, ytEl.Id));
                    if (imgContent != null)
                    {
                        contents.Add(imgContent);
                    }
                }
            }

            var refs = new References()
                       .WithTitle(title)
                       .WithAuthor(uploader)
                       .WithDate(HumanReadableDate(date))
                       .WithLink(ytEl.Url);

            var priority = MediaPlayerConst.DefaultExtractPriority;

            return(ContentEx.CreateSMElement(parentElementId, priority, contents, refs, shouldDisplay));
        }
Example #14
0
 public void Debug()
 {
     LogTo.Debug();
 }
Example #15
0
        public Task <TestSuiteResult> RunTestsAsync(string runner, string dllPath, string dotNetPath, TimeSpan maxTime)
        {
            return(Task.Run(() =>
            {
                var allArguments = new List <string>
                {
                    runner,
                    dllPath,
                    dotNetPath
                };

                try
                {
                    using (var command = Command.Run(
                               "Unima.TestRunner.Console.exe",
                               allArguments,
                               o =>
                    {
                        o.StartInfo(si =>
                        {
                            si.CreateNoWindow = true;
                            si.UseShellExecute = false;
                            si.RedirectStandardError = true;
                            si.RedirectStandardInput = true;
                            si.RedirectStandardOutput = true;
                        });
                        o.Timeout(maxTime);
                        o.DisposeOnExit();
                    }))
                    {
                        var output = command.StandardOutput.ReadToEnd();
                        var error = command.StandardError.ReadToEnd();

                        try
                        {
                            if (!command.Result.Success)
                            {
                                LogTo.Info($"Message from test client - {output}.");
                                LogTo.Info($"Error from test client - {error}.");

                                return new TestSuiteResult
                                {
                                    IsSuccess = false,
                                    Name = $"ERROR - {error}",
                                    ExecutionTime = TimeSpan.Zero,
                                    TestResults = new List <TestResult>()
                                };
                            }
                        }
                        catch (TimeoutException)
                        {
                            LogTo.Info("Test client timed out. Infinit loop?");
                            return TestSuiteResult.Error("TIMEOUT", maxTime);
                        }


                        return JsonConvert.DeserializeObject <TestSuiteResult>(output);
                    }
                }
                catch (Win32Exception ex)
                {
                    LogTo.ErrorException("Unknown expcetion from test client process", ex);
                    throw;
                }
            }));
        }
        public void ProcessData(ref GetStartupMemoryRequest request)
        {
            //TODO : lay du lieu o day, chu y dung nguyen msg nay, ko clone
            try
            {
                #region Comment
                //if (request.Query != null)
                //{
                //    request.TemporaryTopic = null; // ghi nhan xu ly tu memory
                //    ConsoleLog.WriteLine("LOAD ENTITY = {0} BY CURRENT", request.Query.EntityName);
                //    //Lay du lieu tu database
                //    if (request.Query.QueryAction == EntityGet.GetCustomStore)
                //    {
                //        //Run by store name
                //        using (var procedureEntityDao = new ProcedureEntityDao())
                //        {
                //            var lstEntity = procedureEntityDao.GetListEntityByProcedureName(request.Query.EntityName,
                //                request.Query.StoreName);

                //            request.Query.ReturnValue = lstEntity.Select(c =>
                //                new Entity.Entity(c)).ToList();
                //        }

                //        #region Xu ly lay custom thong tin MemberInfo, UserInfo
                //        if (request.Query.EntityName == MemberInfo.EntityName() ||
                //            request.Query.EntityName == UserInfo.EntityName())
                //        {
                //            if (request.RequestWorker == WorkerType.Authentication ||
                //                request.RequestWorker == WorkerType.Dealing ||
                //                request.RequestWorker == WorkerType.Pricing ||
                //                request.RequestWorker == WorkerType.PriceCollector ||
                //                request.RequestWorker == WorkerType.RFQ ||
                //                request.RequestWorker == WorkerType.System ||
                //                request.RequestWorker == WorkerType.Session ||
                //                request.RequestWorker == WorkerType.Chat)
                //            {
                //                //Chi can lay theo store la du
                //            }
                //            else
                //            {
                //                //Lay them 1 so thong tin
                //                var entityName = request.Query.EntityName;
                //                #region Lay customer theo FxDeal Working
                //                if (entityName == MemberInfo.EntityName())
                //                {
                //                    var lstBaseEntity =
                //                        ProcedureEntityDao.GetListMemberCustomerInfoFxDeal();
                //                    foreach (var value in lstBaseEntity)
                //                    {
                //                        var entity = new Entity.Entity(value);
                //                        if (request.Query.ReturnValue == null)
                //                            request.Query.ReturnValue = new List<Entity.Entity>();
                //                        request.Query.ReturnValue.Add(entity);
                //                    }
                //                }
                //                if (entityName == UserInfo.EntityName())
                //                {
                //                    var lstBaseEntity =
                //                        ProcedureEntityDao.GetListUserCustomerInfoFxDeal();

                //                    foreach (var value in lstBaseEntity)
                //                    {
                //                        var entity = new Entity.Entity(value);
                //                        if (request.Query.ReturnValue == null)
                //                            request.Query.ReturnValue = new List<Entity.Entity>();
                //                        request.Query.ReturnValue.Add(entity);
                //                    }
                //                }
                //                #endregion

                //                #region Lay customer la nhom khach hang, customer vang lai chi dinh cho chi nhanh
                //                if (entityName == MemberInfo.EntityName())
                //                {
                //                    //Customer la nhom khach hang
                //                    var lstGroupCustomer = GetListMemberInGroupCustomer();

                //                    var lstEntity = new List<Entity.Entity>();
                //                    foreach (var value in lstGroupCustomer)
                //                    {
                //                        lstEntity.Add(new Entity.Entity(value));
                //                    }

                //                    //Customer vang lai cho chi nhanh
                //                    var lstMemberVangLai = GetListMemberInCustomerVangLai();
                //                    foreach (var memberInfo in lstMemberVangLai)
                //                    {
                //                        lstEntity.Add(new Entity.Entity(memberInfo));
                //                    }

                //                    //Do dữ liêu ràng buộc nên dùng lstVangLai để lấy luôn userinfo cho vang lai
                //                    var lstUserVangLai = GetListUserInfoInCustomerVangLai();
                //                    foreach (var userInfo in lstUserVangLai)
                //                    {
                //                        lstEntity.Add(new Entity.Entity(userInfo));
                //                    }

                //                    //Them vao lst
                //                    if (request.Query.ReturnValue == null)
                //                        request.Query.ReturnValue = new List<Entity.Entity>();
                //                    request.Query.ReturnValue.AddRange(lstEntity);
                //                }
                //                if (entityName == UserInfo.EntityName())
                //                {
                //                    //Customer la nhom khach hang (Ko can lay do nhom khach hang ko co userinfo)

                //                    //Customer vang lai cho chi nhanh (Da lay ben tren)
                //                }
                //                #endregion
                //            }
                //        }
                //        #endregion
                //    }
                //    else
                //    {
                //        if (request.Query.EntityName == SessionHistory.EntityName() &&
                //            request.Query.IsGetMaxKey == false)
                //        {
                //            LogTo.Info("Chi lay thong tin 400 phien gan nhat");

                //            #region SessionHistory

                //            var lstSessionHistory400 =
                //                Select400SessionHistory(400);

                //            var lstEntity = new List<Entity.Entity>();
                //            foreach (var value in lstSessionHistory400)
                //            {
                //                lstEntity.Add(new Entity.Entity(value));
                //            }
                //            request.Query.ReturnValue = lstEntity;
                //            #endregion
                //        }
                //        else
                //        {
                //            //Lay thong tin mac dinh theo query
                //            request.Query = GetEntityQuery(request.Query, false);
                //        }
                //    }

                //    #region Xu ly sau khi lay du lieu
                //    #region Xử lý bỏ qua 1 số dữ liệu không cần thiết
                //    if (request.Query.ReturnValue != null)
                //    {
                //        if (request.Query.EntityName == UserLayout.EntityName())
                //        {
                //            #region Khong can dung thong tin nay tren worker
                //            //Chi can de check ton tai, khong can lay du lieu layout
                //            foreach (var baseEntity in request.Query.ReturnValue)
                //            {
                //                var userLayout = baseEntity.GetEntity() as UserLayout;
                //                userLayout.CurrentLayout = null;
                //                userLayout.DefaultLayout = null;
                //            }
                //            #endregion
                //        }
                //        else if (request.Query.EntityName == ApprovalOrder.EntityName())
                //        {
                //            #region Khong can dung thong tin nay tren worker
                //            //Chi can id va trang thai de check, ko can du lieu ben trong
                //            foreach (var baseEntity in request.Query.ReturnValue)
                //            {
                //                var value = baseEntity.GetEntity() as ApprovalOrder;
                //                if (value.Status == (int)ApprovalStatus.Approval
                //                   || value.Status == (int)ApprovalStatus.Cancel
                //                   || value.Status == (int)ApprovalStatus.Reject)
                //                {
                //                    value.CurrentValue = null;
                //                    value.NewValue = null;
                //                }
                //            }
                //            #endregion
                //        }
                //        else if (request.Query.EntityName == ApprovalPreRisk.EntityName())
                //        {
                //            #region Khong can dung thong tin nay tren worker
                //            //Chi can id va trang thai de check, ko can du lieu ben trong
                //            foreach (var baseEntity in request.Query.ReturnValue)
                //            {
                //                var value = baseEntity.GetEntity() as ApprovalPreRisk;
                //                if (value.Status == (int)ApprovalStatus.Approval
                //                   || value.Status == (int)ApprovalStatus.Cancel
                //                   || value.Status == (int)ApprovalStatus.Reject)
                //                {
                //                    value.CurrentValue = null;
                //                    value.NewValue = null;
                //                }
                //            }
                //            #endregion
                //        }
                //        else if (request.Query.EntityName == ApprovalMember.EntityName())
                //        {
                //            #region Khong can dung thong tin nay tren worker
                //            //Chi can id va trang thai de check, ko can du lieu ben trong
                //            foreach (var baseEntity in request.Query.ReturnValue)
                //            {
                //                var value = baseEntity.GetEntity() as ApprovalMember;
                //                if (value.Status == (int)ApprovalStatus.Approval
                //                   || value.Status == (int)ApprovalStatus.Cancel
                //                   || value.Status == (int)ApprovalStatus.Reject)
                //                {
                //                    value.CurrentValue = null;
                //                    value.NewValue = null;
                //                }
                //            }
                //            #endregion
                //        }
                //        else if (request.Query.EntityName == ApprovalDealing.EntityName())
                //        {
                //            #region Khong can dung thong tin nay tren worker
                //            //Chi can id va trang thai de check, ko can du lieu ben trong
                //            foreach (var baseEntity in request.Query.ReturnValue)
                //            {
                //                var value = baseEntity.GetEntity() as ApprovalDealing;
                //                if (value.Status == (int)ApprovalStatus.Approval
                //                   || value.Status == (int)ApprovalStatus.Cancel
                //                   || value.Status == (int)ApprovalStatus.Reject)
                //                {
                //                    value.CurrentValue = null;
                //                    value.NewValue = null;
                //                }
                //            }
                //            #endregion
                //        }
                //        else if (request.Query.EntityName == ApprovalSystem.EntityName())
                //        {
                //            #region Khong can dung thong tin nay tren worker
                //            //Chi can id va trang thai de check, ko can du lieu ben trong
                //            foreach (var baseEntity in request.Query.ReturnValue)
                //            {
                //                var value = baseEntity.GetEntity() as ApprovalSystem;
                //                if (value.Status == (int)ApprovalStatus.Approval
                //                   || value.Status == (int)ApprovalStatus.Cancel
                //                   || value.Status == (int)ApprovalStatus.Reject)
                //                {
                //                    value.CurrentValue = null;
                //                    value.NewValue = null;
                //                }
                //            }
                //            #endregion
                //        }
                //    }

                //    #endregion

                //    #region GetMaxKey nếu worker yêu cầu
                //    if (request.Query.IsGetMaxKey)
                //    {
                //        string keyName = HistoryUtils.GetKeyName(request.Query.EntityName);
                //        object obj = GetMaxId(request.Query.EntityName, keyName) ?? (long)0;
                //        if (obj is DBNull) obj = (long)0;
                //        //Đối với các bảng có bảng history thì lấy thêm dữ liệu trong bảng hist để tạo max
                //        string entityNameHistory = GetEntityNameHist(request.Query.EntityName);
                //        if (!string.IsNullOrEmpty(entityNameHistory))
                //        {
                //            try
                //            {
                //                //keyName vẫn là keyName của bảng gốc
                //                object objHist = GetMaxId(entityNameHistory, keyName) ?? (long)0;
                //                if (objHist is DBNull)
                //                    objHist = obj;
                //                if (obj is DateTime)
                //                {
                //                    if ((DateTime)obj < (DateTime)objHist)
                //                        obj = objHist; //Nếu key bên hist lớn hơn thì max key là hist
                //                }
                //                else if (obj is string)
                //                {
                //                    if (String.Compare(obj.ToString(), objHist.ToString(), StringComparison.Ordinal) > 0)
                //                        obj = objHist;
                //                }
                //                else if (obj is decimal)
                //                {
                //                    //Phai xu ly cast lai do decimal lay tu oracle ko cast truc tiep sang long
                //                    var a1 = (decimal)obj;
                //                    var a2 = (decimal)objHist;
                //                    if (a1 < a2)
                //                        obj = (long)a2;
                //                }
                //                else
                //                {
                //                    if ((long)obj < (long)objHist) obj = objHist; //Nếu key bên hist lớn hơn thì max key là hist
                //                }
                //            }
                //            catch (Exception ex)
                //            {
                //                LogTo.Error("ENTITY NAME NOT CAST = " + request.Query.EntityName + " ERORR =" + ex.ToString());
                //            }

                //        }
                //        request.Query.ReturnMaxKey = obj;
                //    }
                //    #endregion

                //    #endregion
                //}

                //request.Done = true;
                #endregion
            }
            catch (Exception ex)
            {
                LogTo.Error(ex.ToString());
            }
            #region lay du lieu o day, chu y dung nguyen msg nay, ko clone
            #endregion

            // cuoi cung thi call ham nay
            Sendback(request);
        }
        //Cập nhật tạo mới thông tin mặc định, gửi bao nhiêu cập nhật bấy nhiêu
        public bool UpdateDefault(List <EntityCommand> listEntityActionCommand)
        {
            //MainConection
            SqlConnection  mainConnection     = null;
            SqlTransaction transactionWorking = null;


            var dicWorking = new Dictionary <SqlCommand, EntityCommand>();

            var dicBaseSqlWorking = new Dictionary <SqlCommand, EntityBaseSql>();

            //Biến báo lỗi sql tại đâu
            bool isQueryWorkingSuccess  = false; //Lỗi tại db working
            bool isCommitWorkingSuccess = false; //Lỗi commit working

            string stringCommand = "";

            try
            {
                foreach (var entityCommand in listEntityActionCommand)
                {
                    #region LẤY DIC WORKING  theo COMMAND
                    //Console.WriteLine(entityCommand.BaseEntity.GetName() + " "+listEntityActionCommand.Count);
                    stringCommand = entityCommand.BaseEntity.GetName() + "_" + entityCommand.EntityAction;
                    var entityBaseSql = EntityManager.Instance.GetMyEntity(entityCommand.BaseEntity.GetName());
                    var sqlCommand    = entityBaseSql.GetSqlCommand(entityCommand);
                    sqlCommand.CommandText = entityBaseSql.GetSqlAction(entityCommand);

                    if (mainConnection == null)
                    {
                        mainConnection     = EntityManager.Instance.GetConnection();
                        transactionWorking = mainConnection.BeginTransaction();
                    }

                    sqlCommand.Connection  = mainConnection;
                    sqlCommand.Transaction = transactionWorking;

                    dicWorking[sqlCommand]        = entityCommand;
                    dicBaseSqlWorking[sqlCommand] = entityBaseSql;
                    #endregion
                }

                #region EXECUTE NON QUERY
                foreach (var valueKey in dicWorking)
                {
                    var sqlCommand = valueKey.Key;
                    sqlCommand.ExecuteNonQuery();
                    var entityBaseSql = dicBaseSqlWorking[sqlCommand];
                    entityBaseSql.UpdateEntityId(valueKey.Value, sqlCommand);
                }
                isQueryWorkingSuccess = true; //Báo thành công db working

                #endregion

                #region TRANSACTION COMMIT

                if (transactionWorking != null)
                {
                    transactionWorking.Commit();
                    isCommitWorkingSuccess = true;
                }

                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                /* Có các trường hợp sau xảy ra
                 * 1. Mất kết nối trước khi hoặc đang gọi hàm execution non query
                 * A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
                 * 2. Mất kết nối sau khi exection non query và trước khi commit
                 * Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
                 */

                #region Comment code not test
                //if (!isQueryWorkingSuccess || !isQueryHistSuccess)
                //{
                //    #region Lỗi trong quá trình execution non query
                //    // Handle the exception if the transaction fails to commit.
                //    try
                //    {
                //        if (ex.Message.Contains("A network-related or instance-specific error occurred while " +
                //                "establishing a connection to SQL Server"))
                //        {
                //            //Lỗi mất kết nối, có gọi hàm rollback cũng không giải quyết vấn đề gì, dữ liệu transaction chưa được đưa vào db
                //            throw new Exception("UpdateEntitySql::UpdateDefault:EntityError: "
                //                            + stringCommand + ":Error occured.", ex);
                //        }
                //        else
                //        {
                //            //Lỗi do dữ liệu hoặc vấn đề nào đó trong execution non query
                //            // Attempt to roll back the transaction.
                //            if (transactionWorking != null)
                //                transactionWorking.Rollback();
                //            if (transactionHist != null)
                //                transactionHist.Rollback();
                //        }
                //    }
                //    catch (Exception exRollback)
                //    {
                //        //Ngắt kết nối trước khi rollback thì có lỗi sau :
                //        //This SqlTransaction has completed; it is no longer usable.

                //        // Throws an InvalidOperationException if the connection
                //        // is closed or the transaction has already been rolled
                //        // back on the server.
                //        LogAndWriteEntityComandWhenRollbackExeption(listEntityActionCommand);
                //        LogTo.Error("UpdateEntitySql::UpdateDefault:EntityError: " + stringCommand +
                //            ":Error occured.", ex.Message);
                //        throw new Exception("Error for Rollback: ", exRollback);
                //    }
                //    #endregion
                //}
                //else
                //{
                //    #region Lỗi trong quá trình commit
                //    try
                //    {
                //        string exTimeOut = "Timeout expired.  The timeout period " +
                //                           "elapsed prior to completion of the operation or the server is not responding.";
                //        if (!isCommitWorkingSuccess && transactionWorking != null)
                //        {
                //            #region Nếu lỗi trong quá trình xử lý commit tại db working
                //            if (ex.Message.Contains(exTimeOut))
                //            {
                //                //Mất kết nối khi commit, chưa commit bảng hist do đó ko cần xử lý hist
                //                //Nếu có khả năng thì check xem commit thành công hay chưa, nếu thành công và mất kết nối luôn thì phải rollback lại
                //                LogTo.Error("UpdateEntitySql::UpdateDefault:EntityError: " + stringCommand +
                //                                ":Error occured.", ex.Message);
                //            }
                //            else
                //            {
                //                //Lỗi khác khi đang commit
                //                // Attempt to roll back the transaction.
                //                transactionWorking.Rollback(); //ko cần rollback hist
                //            }
                //            #endregion
                //        }
                //        else if (!isCommitHistSuccess)
                //        {
                //            #region Nếu lỗi trong quá trình xử lý commit tại db hist
                //            if (ex.Message.Contains(exTimeOut))
                //            {
                //                //Mất kết nối khi commit, chưa commit bảng hist do đó ko cần xử lý hist
                //                //Nếu có khả năng thì check xem commit thành công hay chưa, nếu thành công và mất kết nối luôn thì phải rollback lại
                //                //Nhớ xử lý rollback lại commit db working nếu có khả năng
                //                LogTo.Error("UpdateEntitySql::UpdateDefault:EntityError: " + stringCommand +
                //                                ":Error occured.", ex.Message);
                //            }
                //            else
                //            {
                //                // Attempt to roll back the transaction.
                //                if (transactionWorking != null)
                //                    transactionWorking.Rollback();
                //                if (transactionHist != null)
                //                    transactionHist.Rollback();
                //            }
                //            #endregion
                //        }
                //    }
                //    catch (Exception exRollback)
                //    {
                //        // Throws an InvalidOperationException if the connection
                //        // is closed or the transaction has already been rolled
                //        // back on the server.
                //        LogAndWriteEntityComandWhenRollbackExeption(listEntityActionCommand);
                //        LogTo.Error("UpdateEntitySql::UpdateDefault:EntityError: " + stringCommand +
                //            ":Error occured.", ex.Message);
                //        throw new Exception("Error for Rollback: ", exRollback);
                //    }
                //    #endregion
                //}
                #endregion

                if (isCommitWorkingSuccess)
                {
                    //Không xử lý rollback nếu commit thành công
                    throw new Exception("UpdateEntitySql::UpdateDefault:EntityError: "
                                        + stringCommand + ":Error occured.", ex);
                }
                else
                {
                    #region ROLLBACK

                    try
                    {
                        if (transactionWorking != null)
                        {
                            transactionWorking.Rollback();
                        }
                    }
                    catch (Exception exRollback)
                    {
                        // Throws an InvalidOperationException if the connection
                        // is closed or the transaction has already been rolled
                        // back on the server.
                        LogTo.Error("UpdateEntitySql::UpdateDefault:EntityError: " + stringCommand +
                                    ":Error occured.", ex.Message);
                        throw new Exception("Error for Rollback: ", exRollback);
                    }
                    throw new Exception("UpdateEntitySql::UpdateDefault:EntityError: "
                                        + stringCommand + ":Error occured.", ex);
                    #endregion
                }
            }
            finally
            {
                #region FINALLY
                if (mainConnection != null)
                {
                    mainConnection.Close();
                    mainConnection.Dispose();
                    mainConnection = null;
                }


                foreach (var sqlCommand in dicWorking.Keys)
                {
                    sqlCommand.Dispose();
                }



                if (transactionWorking != null)
                {
                    transactionWorking.Dispose();
                    transactionWorking = null;
                }

                dicWorking.Clear();
                dicWorking = null;

                dicBaseSqlWorking.Clear();
                dicBaseSqlWorking = null;


                #endregion
            }
            return(false);
        }
Example #18
0
        /// <summary>
        ///     Parses the content and raises events.
        /// </summary>
        /// <param name="content">The content.</param>
        private void ParseContent(IStreamContent content)
        {
            if (string.IsNullOrEmpty(content.Content))
            {
                LogTo.Trace("Received Keep-Alive on streaming connection");
                return;
            }

            JsonData parsed = JsonMapper.ToObject(content.Content);
            JsonData temp;

            // Was this a direct message?
            if (parsed.TryGetValue("direct_message", out temp))
            {
                LogTo.Debug("DirectMessage received");
                var handler = DirectMessageReceived;
                handler?.Invoke(this, new DirectMessageStreamEventArgs(content.Content));
            }

            // Was this a tweet?
            else if (parsed.TryGetValue("text", out temp))
            {
                LogTo.Debug("Status recevied");
                var handler = StatusReceived;
                handler?.Invoke(this, new StatusStreamEventArgs(content.Content));
            }

            // Or has something been deleted?
            else if (parsed.TryGetValue("delete", out temp))
            {
                JsonData deleted;
                if (temp.TryGetValue("status", out deleted))
                {
                    LogTo.Debug("Status deletion received");
                    var handler = StatusDeleted;
                    handler?.Invoke(this, new DeleteStreamEventArgs(content.Content));
                }
                else
                {
                    LogTo.Debug("DirectMessage deletion received");
                    var handler = DirectMessageDeleted;
                    handler?.Invoke(this, new DeleteStreamEventArgs(content.Content));
                }
            }

            // Or a different event?
            else if (parsed.TryGetValue("event", out temp))
            {
                HandleEvent(content.Content);
            }

            // Is this the friend list of the user?
            else if (parsed.TryGetValue("friends", out temp))
            {
                LogTo.Debug("Friend list received");
                var handler = FriendsReceived;
                handler?.Invoke(this, new FriendsStreamEventArgs(content.Content));
            }
            else
            {
                LogTo.Debug("Unknown data received");
                LogTo.Debug(content.Content);
                var handler = UnknownDataReceived;
                handler?.Invoke(this, new StreamEventArgs(content.Content));
            }
        }
Example #19
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var currentDirectory = builder.Services.BuildServiceProvider()
                                   .GetService <IOptions <ExecutionContextOptions> >().Value.AppDirectory;

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(currentDirectory)
                                .AddJsonFile(@"appSettings.json", false, true)
                                .AddJsonFile(@"appSettings.Development.json", true, true)
                                .AddEnvironmentVariables()
                                .Build();

            if (configuration.GetValue <bool>("Ghostscript"))
            {
                var binDirectory    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var ghostscriptPath = Path.Combine(binDirectory, "../Ghostscript");
                LogTo.Information("Setting Ghostscript path {0}", ghostscriptPath);
                MagickNET.SetGhostscriptDirectory(ghostscriptPath);
            }

            builder.Services.AddLogging();

            var account = new Account(
                configuration["cloudinary:name"],
                configuration["cloudinary:key"],
                configuration["cloudinary:secret"]);

            builder.Services.AddSingleton(new Cloudinary(account));

            builder.Services.AddTransient <ISourceContext>(provider => provider.GetService <SourceContext>());
            builder.Services.AddDbContext <SourceContext>(
                options => options.UseSqlServer(
                    configuration["wikibus:sources:sql"]));
            builder.Services.AddTransient <IImageStorage, CloudinaryImagesStore>();
            builder.Services.AddSingleton <IUriTemplateMatcher, DefaultUriTemplateMatcher>();
            builder.Services.AddSingleton <IUriTemplateExpander, DefaultUriTemplateExpander>();
            builder.Services.AddTransient <ISourceImageService, SourceImageService>();
            builder.Services.AddSingleton <IModelTemplateProvider, AttributeModelTemplateProvider>();
            builder.Services.AddSingleton <IBaseUriProvider, AppSettingsConfiguration>();
            builder.Services.AddTransient <ISourcesRepository, SourcesRepository>();
            builder.Services.AddTransient <EntityFactory>();
            builder.Services.AddSingleton <IWikibusConfiguration, AppSettingsConfiguration>();
            builder.Services.AddSingleton <IConfiguration>(configuration);
            builder.Services.AddSingleton <ISourcesDatabaseSettings, Settings>();
            builder.Services.AddSingleton <ICloudinarySettings, Settings>();
            builder.Services.AddSingleton <IAzureSettings, Settings>();
            builder.Services.AddSingleton <ManagementClientFactory>();
            builder.Services.AddScoped <ISourcesPersistence, SourcesPersistence>();
            builder.Services.AddScoped <IPdfService, PdfService>();
            builder.Services.AddScoped <IWishlistPersistence, WishlistPersistence>();

            if (configuration.IsDevelopment())
            {
                builder.Services.AddSingleton <IStorageQueue, NullStorageQueue>();
                builder.Services.AddSingleton <IFileStorage, LocalFileStorage>();
            }
            else
            {
                builder.Services.AddSingleton <IStorageQueue, StorageQueue>();
                builder.Services.AddSingleton <IFileStorage, BlobFileStorage>();
            }

            builder.Services.RegisterGoogleDrive(configuration);
        }
Example #20
0
        public bool Add(out List <ElemCreationResult> results,
                        ElemCreationFlags options,
                        params ElementBuilder[]      builders)
        {
            if (builders == null || builders.Length == 0)
            {
                results = new List <ElemCreationResult>();
                return(false);
            }

            var inSMUpdateLockMode  = false;
            var inSMAUpdateLockMode = false;
            var singleMode          = builders.Length == 1;
            var toDispose           = new List <IDisposable>();

            results = new List <ElemCreationResult>(
                builders.Select(
                    b => new ElemCreationResult(
                        ElemCreationResultCode.UnknownError,
                        b))
                );

            try
            {
                bool success          = true;
                int  restoreElementId = Core.SM.UI.ElementWdw.CurrentElementId;
                int  restoreHookId    = Core.SM.UI.ElementWdw.CurrentHookId;

                //
                // Enter critical section

                _addMutex.WaitOne();

                //
                // Suspend element changed monitoring

                inSMAUpdateLockMode = Core.SM.UI.ElementWdw.EnterSMAUpdateLock();

                //
                // Save states

                toDispose.Add(new HookSnapshot());
                //toDispose.Add(new ConceptSnapshot());

                //
                // Focus

                // toDispose.Add(new FocusSnapshot(true)); // TODO: Only if inserting 1 element

                //
                // Freeze element window if we want to insert the element without displaying it immediatly

                if (singleMode == false || builders[0].ShouldDisplay == false)
                {
                    inSMUpdateLockMode = Core.SM.UI.ElementWdw.EnterSMUpdateLock(); // TODO: Pass in EnterUpdateLock
                }
                foreach (var result in results)
                {
                    result.Result    = AddElement(result.Builder, options, restoreHookId, out int elemId);
                    result.ElementId = elemId;

                    success = success && result.Result == ElemCreationResultCode.Success;
                }

                //
                // Display original element, and unfreeze window -- or simply resume element changed monitoring

                if (inSMUpdateLockMode)
                {
                    inSMUpdateLockMode = Core.SM.UI.ElementWdw.QuitSMUpdateLock() == false;

                    Core.SM.UI.ElementWdw.GoToElement(restoreElementId);

                    inSMAUpdateLockMode = Core.SM.UI.ElementWdw.QuitSMAUpdateLock(true);
                }

                else
                {
                    inSMAUpdateLockMode = Core.SM.UI.ElementWdw.QuitSMAUpdateLock();
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogTo.Error(ex,
                            "An exception was thrown while creating a new element in SM.");
                return(false);
            }
            finally
            {
                //
                // Unlock SM if necessary

                if (inSMUpdateLockMode)
                {
                    try
                    {
                        Core.SM.UI.ElementWdw.QuitSMUpdateLock();
                    }
                    catch (Exception ex)
                    {
                        LogTo.Warning(ex, "Failed to exit SM Update Lock.");
                        MessageBox.Show($@"Failed to exit SuperMemo UI update lock.
You might have to restart SuperMemo.

Exception: {ex}",
                                        "Critical error");
                    }
                }

                //
                // Restore initial context

                toDispose.ForEach(d =>
                {
                    try
                    {
                        d.Dispose();
                    }
                    catch (Exception ex)
                    {
                        LogTo.Warning(ex, "Failed to restore context after creating a new SM element.");
                        MessageBox.Show($@"Failed to restore initial context after creating a new SM element.
Your hook and/or current concept might have been changed.

Exception: {ex}",
                                        "Warning");
                    }
                });

                //
                // Unlock element changed monitoring if necessary

                if (inSMAUpdateLockMode)
                {
                    Core.SM.UI.ElementWdw.QuitSMAUpdateLock();
                }

                //
                // Exit Critical section

                _addMutex.ReleaseMutex();
            }
        }
Example #21
0
        protected Bitmap RenderArea(int pageIndex,
                                    System.Windows.Point lt,
                                    System.Windows.Point rb)
        {
            try
            {
                var page = Document.Pages[pageIndex];

                var pageRenderRect = GetRenderRect(pageIndex);

                int scaledPageWidth  = (int)pageRenderRect.Width;
                int scaledPageHeight = (int)pageRenderRect.Height;

                Bitmap fullRender;

                using (var bmp = new PdfBitmap(scaledPageWidth,
                                               scaledPageHeight,
                                               true))
                {
                    bmp.FillRect(0,
                                 0,
                                 scaledPageWidth,
                                 scaledPageHeight,
                                 System.Drawing.Color.FromArgb(PageBackColor.A,
                                                               PageBackColor.R,
                                                               PageBackColor.G,
                                                               PageBackColor.B));

                    //Render part of page into bitmap;
                    page.Render(bmp,
                                0,
                                0,
                                scaledPageWidth,
                                scaledPageHeight,
                                page.Rotation,
                                RenderFlags.FPDF_LCD_TEXT);

                    fullRender = new Bitmap(bmp.Image);
                }

                var pt1 = page.PageToDevice(0,
                                            0,
                                            scaledPageWidth,
                                            scaledPageHeight,
                                            page.Rotation,
                                            (float)lt.X,
                                            (float)lt.Y);
                var pt2 = page.PageToDevice(0,
                                            0,
                                            scaledPageWidth,
                                            scaledPageHeight,
                                            page.Rotation,
                                            (float)rb.X,
                                            (float)rb.Y);

                if (pt1.X > pt2.X)
                {
                    int tmpX = pt1.X;
                    pt1.X = pt2.X;
                    pt2.X = tmpX;
                }

                if (pt1.Y > pt2.Y)
                {
                    int tmpY = pt1.Y;
                    pt1.Y = pt2.Y;
                    pt2.Y = tmpY;
                }

                return(fullRender.Clone(
                           new Rectangle(pt1.X,
                                         pt1.Y,
                                         (int)(pt2.X - pt1.X),
                                         (int)(pt2.Y - pt1.Y)),
                           fullRender.PixelFormat
                           ));
            }
            catch (Exception ex)
            {
                LogTo.Error(ex,
                            $"Failed to render PDF area: page {pageIndex}, {lt}:{rb}");
                return(null);
            }
        }
Example #22
0
        public async Task BanChampion(Position pos, LolChampSelectChampSelectAction myAction, LolChampSelectChampSelectPlayerSelection[] myTeam)
        {
            LogTo.Debug("Trying to ban champion");

            Dictionary <Position, int> bans = Config.Current.ChampionsToBan;
            var bannable = await LoL.ChampSelect.GetBannableChampions();

            var possibleBans = new List <int>();

            possibleBans.Add(bans[pos]);
            possibleBans.Add(bans[Position.Fill]);
            LogTo.Debug("possibleBans: {0}", string.Join(", ", possibleBans));

            int preferredBan = possibleBans.FirstOrDefault(bannable.championIds.Contains);
            var banName      = preferredBan > 0 ? (await Riot.GetChampion(preferredBan)).Name : "None";

            LogTo.Debug("Preferred ban: {0}", banName);

            if (preferredBan == 0)
            {
                LogTo.Debug("Couldn't ban any champion");

                //TODO Add translatable string
                Main.ShowNotification("Couldn't ban any champion",
                                      "Maybe all of your selected champions were banned", NotificationType.Error);
                return;
            }

            var teamIntents = myTeam.Select(o => o.championPickIntent);

            if (teamIntents.Contains(preferredBan))
            {
                LogTo.Info("Wanted to ban {0}, but someone wants to play it", banName);

                Main.ShowNotification("Hey", $"Couldn't ban {banName} because someone wants to play it", NotificationType.Error);
                SystemSounds.Exclamation.Play();

                return;
            }

            LogTo.Debug("Candidate found ({0}), banning...", banName);
            myAction.championId = preferredBan;
            myAction.completed  = true;

            try
            {
                await LoL.ChampSelect.PatchActionById(myAction, myAction.id);

                LogTo.Debug("Champion banned");
            }
            catch (APIErrorException ex)
            {
                LogTo.DebugException("Couldn't ban champion", ex);
            }

            if (Config.DisableBanChampion)
            {
                LogTo.Debug("Unset auto ban champion");

                Config.AutoBanChampion = false;
                Config.Save();
            }
        }
Example #23
0
 private static void Machine_EnteredState(GameStates state)
 {
     LogTo.Debug("Entered UI state " + state);
 }
        private void OnPluginStarting(PluginInstance pluginInstance)
        {
            LogTo.Information($"Starting {pluginInstance.Denomination} {pluginInstance.Package.Id}.");

            _runningPluginMap[pluginInstance.OnStarting()] = pluginInstance;
        }
        public async Task <MutationDocumentResult> ExecuteMutationAsync(UnimaConfig config, MutationDocument mutationDocument)
        {
            var mutationResult = new MutationDocumentResult
            {
                Id           = mutationDocument.Id,
                MutationName = mutationDocument.MutationName,
                ProjectName  = mutationDocument.ProjectName,
                FileName     = mutationDocument.FileName,
                Location     = mutationDocument.MutationDetails.Location,
                Orginal      = mutationDocument.MutationDetails.Orginal.ToFullString(),
                FullOrginal  = mutationDocument.MutationDetails.FullOrginal.ToFullString(),
                Mutation     = mutationDocument.MutationDetails.Mutation.ToFullString(),
                FullMutation = mutationDocument.MutationDetails.FullMutation.ToFullString()
            };

            mutationResult.GenerateHash();

            LogTo.Info($"Running mutation: \"{mutationDocument.MutationName}\"");

            var results = new List <TestSuiteResult>();

            // Create the temporary "head" mutation directory to run all tests
            var mutationDirectoryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestRun", mutationDocument.Id.ToString());

            // Where we should save our compiled mutation
            var mutationDllPath = Path.Combine(mutationDirectoryPath, $"{config.MutationProjects.FirstOrDefault(m => m.Name == mutationDocument.ProjectName).OutputFileName}");

            Directory.CreateDirectory(mutationDirectoryPath);

            mutationResult.CompilationResult = await _compiler.CompileAsync(mutationDllPath, mutationDocument);

            if (!mutationResult.CompilationResult.IsSuccess)
            {
                return(mutationResult);
            }

            foreach (var testProject in config.TestProjects)
            {
                var baseline = config.BaselineInfos.FirstOrDefault(b => b.TestProjectName.Equals(testProject.Project.Name, StringComparison.OrdinalIgnoreCase));
                var result   = await RunTestAsync(testProject, mutationDirectoryPath, mutationDllPath, config.DotNetPath, baseline?.GetTestProjectTimeout() ?? TimeSpan.FromMinutes(config.MaxTestTimeMin));

                results.Add(result);

                if (results.Any(r => !r.IsSuccess))
                {
                    break;
                }
            }

            try
            {
                Directory.Delete(mutationDirectoryPath, true);
            }
            catch (Exception ex)
            {
                LogTo.Error($"Failed to delete test directory: {ex.Message}");
            }

            var final = CombineResult(mutationDocument.FileName, results);

            if (final.TestResults.Count == 0)
            {
                throw new MutationDocumentException("Unkown error when running, we should not have 0 tests.");
            }

            LogTo.Info($"\"{mutationDocument.MutationName}\" done. Ran {final.TestResults.Count} tests and {final.TestResults.Count(t => !t.IsSuccess)} failed.");

            mutationResult.FailedTests   = final.TestResults.Where(t => !t.IsSuccess).ToList();
            mutationResult.TestsRunCount = final.TestResults.Count;

            return(mutationResult);
        }
        private void OnPluginStopping(PluginInstance pluginInstance)
        {
            LogTo.Information($"Stopping {pluginInstance.Denomination} {pluginInstance.Package.Id}.");

            pluginInstance.OnStopping();
        }
Example #27
0
        //
        // Core hook methods

        public async Task <ProcessSharp <SMNatives> > CreateAndHook(
            SMCollection collection,
            string binPath,
            IEnumerable <ISMAHookIO> ioCallbacks,
            NativeData nativeData)
        {
            LogTo.Debug("Starting and injecting SuperMemo");

            IOCallbacks.AddRange(ioCallbacks);

            IOTargetFilePaths.AddRange(IOCallbacks.SelectMany(c => c.GetTargetFilePaths()));

            HookSuccess   = false;
            HookException = null;

            // Start a new IPC server
            var channelName = StartIPCServer();

            // Start SuperMemo application with given collection as parameter,
            // and immediately install hooks
            int pId = -1;

            try
            {
                RemoteHooking.CreateAndInject(
                    binPath,
                    collection.GetKnoFilePath().Quotify(),
                    0,
                    InjectionOptions.Default,
                    SMAFileSystem.InjectionLibFile.FullPath,
                    null,
                    out pId,
                    channelName,
                    nativeData
                    );
            }
            catch (ArgumentException ex)
            {
                LogTo.Warning(ex, $"Failed to start and inject SuperMemo. Command line: '{binPath} {collection.GetKnoFilePath().Quotify()}'");
            }

            LogTo.Debug("Waiting for signal from Injected library");

            // Wait for Signal from OnHookInstalled with timeout
            await HookInitEvent.WaitAsync(WaitTimeout);

            if (HookSuccess == false)
            {
                LogTo.Debug("Hook failed, aborting");

                StopIPCServer();

                var ex = new HookException("Hook setup failed: " + HookException?.Message,
                                           HookException);
                HookException = null;

                throw ex;
            }

            LogTo.Debug($"SuperMemo started and injected, pId: {pId}");

            return(new ProcessSharp <SMNatives>(
                       pId,
                       Process.NET.Memory.MemoryType.Remote,
                       true,
                       Core.SMA.StartupConfig.PatternsHintAddresses,
                       nativeData));
        }
Example #28
0
 protected abstract void WriteOutput(string message, LoggerBase.Severity severity, LogTo logTo);
 public void LogNoArgs()
 {
     LogTo.Debug("Debug");
     LogTo.Info("Info");
     LogTo.Warning("Warn");
 }
Example #30
0
 public void Init()
 {
     LogTo.Debug("Initializing initable");
     _initable.Init();
 }
Example #31
0
        private static async Task <FeedItemExt> DownloadFeedContent(FeedCfg feedCfg,
                                                                    FeedItem feedItem,
                                                                    SemaphoreSlim throttler,
                                                                    HttpClient client)
        {
            try
            {
                await throttler.WaitAsync();

                //
                // Check & update publishing dates

                if (feedCfg.UsePubDate)
                {
                    if (feedItem.PublishingDate == null)
                    {
                        LogTo.Warning(
                            $"Date missing, or unknown format for feed {feedCfg.Name}, item title '{feedItem.Title}', raw date '{feedItem.PublishingDateString}'");
                        return(null);
                    }

                    if (feedItem.PublishingDate <= feedCfg.LastPubDate)
                    {
                        return(null);
                    }
                }

                //
                // Check guid

                if (feedCfg.UseGuid)
                {
                    if (feedCfg.EntriesGuid.Contains(feedItem.Id))
                    {
                        return(null);
                    }
                }

                //
                // Check categories

                if (feedCfg.ShouldExcludeCategory(feedItem))
                {
                    return(null);
                }

                //
                // Download content or use inline content

                if (feedItem.Link != null)
                {
                    var httpReq = new HttpRequestMessage(HttpMethod.Get,
                                                         feedItem.MakeLink(feedCfg));
                    var httpResp = await client.SendAsync(httpReq);

                    if (httpResp != null && httpResp.IsSuccessStatusCode)
                    {
                        feedItem.Content = await httpResp.Content.ReadAsStringAsync();
                    }

                    else
                    {
                        feedItem.Content = null;
                        LogTo.Warning(
                            $"Failed to download content for feed {feedCfg.Name}, item title '{feedItem.Title}', link '{feedItem.MakeLink(feedCfg)}'. HTTP Status code : {httpResp?.StatusCode}");
                    }
                }

                else
                {
                    feedItem.Content = feedItem.Content ?? feedItem.Description;
                }

                if (string.IsNullOrWhiteSpace(feedItem.Content))
                {
                    return(null);
                }

                //
                // Process content if necessary & push back

                if (feedCfg.Filters.Any())
                {
                    feedItem.Content = string.Join(
                        "\r\n",
                        feedCfg.Filters
                        .Select(f => f.Filter(feedItem.Content))
                        .Where(s => string.IsNullOrWhiteSpace(s) == false)
                        );
                }

                if (feedItem.Link != null)
                {
                    feedItem.Content = HtmlUtils.EnsureAbsoluteLinks(feedItem.Content, new Uri(feedItem.MakeLink(feedCfg)));
                }

                // Add feed item
                return(new FeedItemExt(feedItem));
            }
            catch (Exception ex)
            {
                LogTo.Error(ex, $"Exception while downloading content for feed {feedCfg.Name}, item title '{feedItem.Title}', link '{feedItem.MakeLink(feedCfg)}'");
            }
            finally
            {
                throttler.Release();
            }

            return(null);
        }
Example #32
0
 public InitableRunner(IInitable initable)
 {
     LogTo.Debug("InitableRunner created");
     _initable = initable;
 }
 internal LogDomains(LogTo source)
 {
     _source = source;
 }
Example #34
0
#pragma warning disable 1998
        public static async Task ImportFeeds(
#pragma warning restore 1998
            ICollection <FeedData> feedsData,
            Action <int, int> progressCallback = null)
        {
            try
            {
                int i          = 0;
                int totalCount = feedsData.Sum(fd => fd.NewItems.Count);

                var builders = new List <ElementBuilder>();

                progressCallback?.Invoke(i, totalCount);

                foreach (var feedData in feedsData)
                {
                    foreach (var feedItem in feedData.NewItems.Where(fi => fi.IsSelected))
                    {
                        builders.Add(
                            new ElementBuilder(ElementType.Topic,
                                               new TextContent(true, feedItem.Content))
                            .WithParent(feedData.FeedCfg.RootElement)
                            .WithPriority(feedData.FeedCfg.Priority)
                            .WithReference(
                                // ReSharper disable once PossibleInvalidOperationException
                                r => r.WithDate(feedItem.PublishingDate?.ToString())
                                .WithTitle(feedItem.Title)
                                .WithAuthor(feedItem.Author)
                                .WithComment(StringEx.Join(", ", feedItem.Categories))
                                .WithSource($"Feed: {feedData.FeedCfg.Name} (<a>{feedData.FeedCfg.SourceUrl}</a>)")
                                .WithLink(feedItem.MakeLink(feedData.FeedCfg)))
                            .DoNotDisplay()
                            );
                    }
                }

                var res = Svc.SMA.Registry.Element.Add(
                    out var results,
                    ElemCreationFlags.CreateSubfolders,
                    builders.ToArray()
                    );

                if (res == false)
                {
                    var msg = results.GetErrorString();
                    Show.Window().For(new Alert(msg, "Feeds: Error")).RunAsync();

                    return;
                }

                progressCallback?.Invoke(++i, totalCount);

                // Update feeds state

                foreach (var feedData in feedsData)
                {
                    var lastPubDate = feedData.FeedCfg.LastPubDate;
                    var feedItems   = feedData.NewItems.Where(fi => fi.IsSelected).ToList();

                    foreach (var feedItem in feedItems)
                    {
                        // published date time
                        if (feedItem.PublishingDate.HasValue)
                        {
                            feedData.FeedCfg.LastPubDate = feedItem.PublishingDate > lastPubDate
                ? feedItem.PublishingDate.Value
                : lastPubDate;
                        }

                        // Guid
                        feedData.FeedCfg.EntriesGuid.Add(feedItem.Id);
                    }

                    if (feedItems.Any())
                    {
                        feedData.FeedCfg.LastRefreshDate = feedData.FeedCfg.PendingRefreshDate;
                    }
                }

                Svc <FeedsPlugin> .Plugin.SaveConfig();
            }
            catch (Exception ex)
            {
                // TODO: report error through callback & display
                LogTo.Error(ex, "Exception while importing feed item in SuperMemo");
            }
        }