コード例 #1
0
ファイル: EpubMaker.cs プロジェクト: nikitazu/jphtml
        public async Task ConvertHtmlToEpub(ContentsInfo contents)
        {
            _log.Debug("epub start");
            using (var epubStream = File.Create(_outputFile))
                using (var epubWriter = await EPubWriter.CreateWriterAsync(
                           epubStream,
                           Path.GetFileNameWithoutExtension(_outputFile),
                           _author,
                           _bookId))
                {
                    epubWriter.Publisher = _publisher;
                    foreach (var chapter in contents.ChapterFiles)
                    {
                        await epubWriter.AddChapterAsync(
                            chapter.Name + ".html",
                            Path.GetFileNameWithoutExtension(chapter.Name),
                            chapter.XhtmlContent.ToString());
                    }
                    await epubWriter.AddResourceAsync(
                        "style.css",
                        "text/css",
                        File.ReadAllBytes(Path.Combine(_resourceLocator.ResourcesPath, "data", "epub", "style.css")));

                    await epubWriter.WriteEndOfPackageAsync().ContinueWith(_ =>
                    {
                        _log.Debug("epub done");
                    });
                }
        }
コード例 #2
0
        public void Intercept(IInvocation invocation)
        {
            string methodName = invocation.TargetType.FullName + "." + invocation.GetConcreteMethod().Name;

            _logger.Debug(GetDateInLogFormat() + " " + methodName + " Entered");
            invocation.Proceed();
            _logger.Debug(GetDateInLogFormat() + " " + methodName + " Exited");
        }
コード例 #3
0
        public async Task Convert()
        {
            _log.Debug("Convert start");
            _counter.Start();

            ContentsInfo contents = await Task.Factory.StartNew(CreateAnnotatedXhtmlContents);

            await ConvertXhtmlToEpub(contents).ContinueWith(_ =>
            {
                _counter.Stop();
                _log.Debug("Convert end");
            });
        }
コード例 #4
0
        public JmdicReader(ILogWriter log, string path, IMultiDictionary dictionary)
        {
            _log = log;
            Stopwatch sw = new Stopwatch();

            sw.Start();
            _log.Debug($"Loading {path}");
            _dictionary = dictionary;
            _document   = new XmlDocument();
            _document.Load(path);
            _log.Debug($"Indexing {path}");
            CreateDictionary();
            sw.Stop();
            _log.Debug($"done in {sw.ElapsedMilliseconds}ms");
        }
コード例 #5
0
 /// <summary>
 /// DO NOT USE THIS! See Jason/Blair.
 /// </summary>
 /// <param name="entityType"></param>
 /// <returns></returns>
 public ISession For(Type entityType)
 {
     Logger.Debug("Acquiring session for {0}", entityType);
     return //UnitOfWork.Current == null ?
            (CreateSession()
            //: UnitOfWork.Current.Session
            );
 }
コード例 #6
0
ファイル: JmdicFastReader.cs プロジェクト: nikitazu/jphtml
        public JmdicFastReader(
            ILogWriter log,
            IResourceLocator resourceLocator,
            IMultiDictionary dictionary)
        {
            _log        = log;
            _path       = Path.Combine(resourceLocator.ResourcesPath, "data", "dic", "JMdict_e");
            _dictionary = dictionary;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            _log.Debug($"Indexing {_path}");

            ReadDictionary();

            sw.Stop();
            _log.Debug($"done in {sw.ElapsedMilliseconds}ms");
        }
コード例 #7
0
        internal Func <XpressRuntimeContext, bool> Translate(IXpressParseTree parseTree, ILogWriter log)
        {
            try
            {
                var ironyParseTree = (ParseTree)parseTree.Root;
                var parseNodes     = ironyParseTree.Root.ChildNodes;

                var requestInfoParam = Expression.Parameter(typeof(XpressRuntimeContext), "context");
                var ctx = new XpressCompilationContext {
                    RuntimeContextParameter = requestInfoParam
                };

                Expression condition = null;

                foreach (var parseNode in parseNodes)
                {
                    if (parseNode.Term.Name == XpressConstants.Tokens.NonTerminals.Expression)
                    {
                        condition = TranslateExpression(ctx, parseNode);

                        if (!IsRuntimeContextGetExpression(condition) && condition.Type != typeof(bool))
                        {
                            throw new Exception($"Expression must evluate to a 'boolean' value. Error at '{parseNode.FindTokenAndGetText()}' on position {parseNode.Span.Location.Position}");
                        }
                        condition = ConvertToBoolean(condition);

                        if (condition != null)
                        {
                            log.Debug($"{condition.ToString()}");
                        }
                    }
                }


                // Define a return statement label and expression
                var returnTarget     = Expression.Label(typeof(bool));
                var returnExpression = Expression.Return(returnTarget, condition);

                // Define func body statements
                List <Expression> bodyStatements = new List <Expression>();
                bodyStatements.Add(returnExpression);
                bodyStatements.Add(Expression.Label(returnTarget, condition));

                var bodyExpression   = Expression.Block(bodyStatements);
                var lambdaExpression = Expression.Lambda <Func <XpressRuntimeContext, bool> >(bodyExpression, requestInfoParam);

                return(lambdaExpression.Compile());
            }
            catch (Exception ex)
            {
                log.Error($"Error interpreting parse tree: {ex.Message}");
            }

            return(null);
        }
コード例 #8
0
ファイル: UnitOfWork.cs プロジェクト: vikavisoft/lacjam
 public override void Start()
 {
     if (_session == null)
     {
         _logWriter.Debug("UnitOfWork - new session");
         this.UseSupportForOutsidePersistentCall = true;
         _session = SessionFactory.OpenSession();
         Bind();
     }
     DoStart();
 }
コード例 #9
0
        public IXpressParseTree Parse(string sourceCode, ILogWriter log)
        {
            log.Debug(XpressConstants.Messages.ParserDebugMessageStartParse,
                      DateTime.Now.ToString(XpressConstants.Messages.FormatLongDateTime));
            try
            {
                if (string.IsNullOrEmpty(sourceCode))
                {
                    throw new ArgumentNullException(codeParamName);
                }


                ParseTree parseTree = _parser.Parse(sourceCode);
                foreach (var parserMessage in parseTree.ParserMessages)
                {
                    if (parserMessage.Level == ErrorLevel.Error)
                    {
                        log.Error("Parse error {0}, at location [{1}]", parserMessage.Message, parserMessage.Location.ToString());
                    }
                    else
                    {
                        log.Debug(parserMessage.Message);
                    }
                }
                if (parseTree.HasErrors())
                {
                    _parser.RecoverFromError();
                }

                return(new XpressParseTree(sourceCode, parseTree));
            }
            catch (Exception ex)
            {
                log.Error(XpressConstants.Messages.ParserErrorMessage, ex.Message);
                log.Error(XpressConstants.Messages.ParserErrorMessageDetailed, ex);
                _parser.RecoverFromError();
            }

            log.Debug(XpressConstants.Messages.ParserDebugMessageEndParse, DateTime.Now.ToString(XpressConstants.Messages.FormatLongDateTime));
            return(null);
        }
コード例 #10
0
        public void Publish <T>(T @event, long seq = -1, bool?runImmediately = true) where T : IEvent
        {
            try
            {
                _logger.Debug(EventIds.Dispatcher, "Dispatching " + seq);
                _logger.Debug(EventIds.Dispatcher, "Dispatching " + JsonConvert.SerializeObject(@event));

                CheckHandlers();
                DispatchToHandlers(@event, runImmediately);

                if (seq > 0 && runImmediately != true)
                {
                    _handlerSequenceRespository.Save(seq, "Dispatcher");
                }
            }
            catch (Exception e)
            {
                _logger.Error(EventIds.Dispatcher, "RunHandlers", e);
                throw;
            }
        }
コード例 #11
0
 public ViewController(IntPtr handle) : base(handle)
 {
     _dialog          = new CocoaDialogCreator();
     _fileManager     = new FinderFileManager();
     _resourceLocator = new MacResourceLocator();
     _log             = new LoggingConfig(_resourceLocator).CreateRootLogWriter();
     _log.Debug("start");
     _jmdicReaderTask = Task.Factory.StartNew(() => new JmdicFastReader(
                                                  _log,
                                                  _resourceLocator,
                                                  new Jmdictionary()
                                                  ));
 }
コード例 #12
0
        private void ListenExecute(object obj)
        {
            Socket client = obj as Socket;

            try
            {
                string ip     = (client.RemoteEndPoint as System.Net.IPEndPoint).Address.ToString();
                byte[] buffer = new byte[1024];
                int    count  = client.Receive(buffer);
                if (count > 0)
                {
                    string content = Encoding.UTF8.GetString(buffer, 0, count);
                    if (content.IndexOf("@chatroom") == -1)
                    {
                        return;
                    }
                    //_log.Debug("请求一次微信群组调用:" + content);
                    _log.Debug(DateTime.Now.ToString() + "收到了一次socket请求:http://localhost:83/Home/About?a=" + content);
                    //System.IO.File.AppendAllText("c:/socketLog.txt", "socket:" + ip + ":" + port + ":" + content);
                    ////发起请求,获取微信群组列表
                    ChatRoomMember.GetChatRoomUser(pid, content);
                    try
                    {
                        string data = JsonSerializeHelper.JsonSerialize(new { status = "success", errorMessage = "" });
                        client.Send(Encoding.UTF8.GetBytes(data));
                    }
                    catch (Exception ex)
                    {
                        string data = JsonSerializeHelper.JsonSerialize(new { status = "error", errorMessage = ex.Message });
                        client.Send(Encoding.UTF8.GetBytes(data));
                    }
                    finally
                    {
                    }
                }
            }
            catch { }
            finally
            {
                try
                {
                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
                    client.Dispose();
                }
                catch { }
            }
        }
コード例 #13
0
ファイル: MainWindow.xaml.cs プロジェクト: nikitazu/jphtml
 public MainWindow()
 {
     InitializeComponent();
     _model           = new MainWindowViewModel();
     _dialog          = new WpfDialogCreator(this);
     _fileManager     = new WindowsExplorerFileManager();
     _resourceLocator = new WindowsResourceLocator();
     _log             = new LoggingConfig(_resourceLocator).CreateRootLogWriter();
     _log.Debug("start");
     _jmdicReaderTask = Task.Factory.StartNew(() => new JmdicFastReader(
                                                  _log,
                                                  _resourceLocator,
                                                  new Jmdictionary())
                                              );
     DataContext = _model;
 }
コード例 #14
0
        private void InitializeNHibernate()
        {
            if (_logWriter == null)
            {
                _logWriter = new LogWriter();
            }

            try
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    var dir        = AppDomain.CurrentDomain.BaseDirectory.ToLowerInvariant();
                    var configPath = Path.Combine(
                        AppDomain.CurrentDomain.BaseDirectory,
                        dir.EndsWith("wcfbackend\\") || dir.EndsWith("quotefacade\\") ? "bin\\" : "",
                        "NHibernate.config");

                    if (!File.Exists(configPath))
                    {
                        _logWriter.Error(EventIds.BACKEND_SERVER_DOWN, "Phoenix:: Cannot find NHibernate.config file ");
                        throw new ApplicationException(configPath + " does not exist");
                    }

                    _logWriter.Debug(EventIds.DEBUG_INFORMATION, "Phoenix:: found NH config file " + configPath);

                    _configuration = CreateConfiguration().Configure(configPath);
                }
                else
                {
                    var props = new Dictionary <string, string>
                    {
                        { "dialect", "NHibernate.Dialect.MsSql2005Dialect" },
                        { "connection.driver_class", "NHibernate.Driver.SqlClientDriver" },
                        { "connection.provider", "NHibernate.Connection.DriverConnectionProvider" },
                        { "connection.release_mode", "auto" },
                        { "adonet.batch_size", "500" },
                        { "current_session_context_class", "thread_static" },
                        { "show_sql", "true" },
                        { "prepare_sql", "true" },
                        { "connection.connection_string", _connectionString.Trim() }
                    };

                    _configuration = CreateConfiguration().AddProperties(props);
                }

                var generator = _assembly == null
                                    ? new AutoPersistenceModelGenerator()
                                    : new AutoPersistenceModelGenerator(_assembly);

                CreateFluentConfiguration(generator.Generate());
            }
            catch (ReflectionTypeLoadException ex)
            {
                var sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    if (exSub is FileNotFoundException)
                    {
                        var exFileNotFound = exSub as FileNotFoundException;
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();
                //Display or log the error based on your application.
                _logWriter.Error(EventIds.BACKEND_SERVER_DOWN, errorMessage);
            }

            catch (Exception ex)
            {
                //Display or log the error based on your application.
                _logWriter.Error(EventIds.BACKEND_SERVER_DOWN, "InitializeNHibernate" + ex);
                throw;
            }
        }
コード例 #15
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x004A)
            {
                COPYDATASTRUCT cds  = new COPYDATASTRUCT();
                Type           type = cds.GetType();
                cds = (COPYDATASTRUCT)m.GetLParam(type);

                //无效信息拦截
                if (cds.dwData != 0 && cds.dwData != 2)
                {
                    return;
                }

                if (tb_MsgBox.Text.Length > 10000)
                {
                    tb_MsgBox.Text = string.Empty;
                }

                if (cds.dwData == 0)
                {
                    //不再是传值的方式了,通过文件的方式,所以这里注释
                    ////接受到的群消息
                    //var content = Marshal.PtrToStringAnsi(cds.lpData);

                    ////处理接受到的消息
                    //new HandleReceiveMessage().HandleMessage(content, _log);

                    //tb_MsgBox.Text += content;

                    //回复消息
                    //var chatroomId = content.Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries)[0];
                    //ChatRoomMember.SendRoomAtMsg(Pid, chatroomId);

                    #region 注释
                    //拆分字符串并拼json
                    //var arrContent = content.Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries);

                    //var center = ConfigurationManager.AppSettings["MessageCenter"];

                    //如果不是文字、图片消息,就直接返回
                    //if (arrContent[3].IndexOf("no") > -1)
                    //{
                    //    return;
                    //}

                    //Task.Run(() =>
                    //{
                    //    string msgContent = "";
                    //    if (arrContent[3].IndexOf("image") > -1)
                    //    {
                    //        string u1 = GetImageBaseDir() + arrContent[4];
                    //        u1 = u1.Substring(0, u1.LastIndexOf(".dat") + 4);//防止后面有乱码
                    //        try
                    //        {
                    //            _log.Info(u1 + "\r\n");
                    //            解密图片
                    //            msgContent = DecryptImageHelper.Decrypt(u1);
                    //        }
                    //        catch (Exception ex)
                    //        {
                    //            _log.Error("解密图片时候报错:" + ex.Message + u1);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        msgContent = arrContent[2];
                    //    }

                    //    var jsonObj = new
                    //    {
                    //        GroupId = arrContent[0],
                    //        MemberId = arrContent[1],
                    //        MsgTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"),
                    //        MsgContent = msgContent,
                    //        MsgType = arrContent[3]
                    //    };

                    //    var jsonContent = JsonSerializeHelper.JsonSerialize(jsonObj);
                    //    显示日志
                    //    tb_MsgBox.Text += jsonContent;
                    //    发送到数据接口
                    //    new WebHelper().PostMessage(center, jsonContent, _log);
                    //    调用微信群组接口
                    //    ChatRoomMember.GetChatRoomUser(Pid, jsonObj.GroupId);
                    //});
                    #endregion
                }
                else if (cds.dwData == 2)
                {
                    //获取到的群成员列表
                    var content = Marshal.PtrToStringUni(cds.lpData);
                    try
                    {
                        //群组信息与成员列表切分开
                        var chatRoomIdandMember = content.Split(new string[] { "_&&_" }, StringSplitOptions.RemoveEmptyEntries);
                        //群组id
                        var chatRoomId = chatRoomIdandMember[0].Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries)[0];
                        _log.Debug("响应一次微信群组调用:" + chatRoomId);

                        //群组名称
                        var chatRoomName = chatRoomIdandMember[0].Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        //群的成员列表。
                        var           chatRoomMembers = chatRoomIdandMember[1].Split(new string[] { "_&_" }, StringSplitOptions.RemoveEmptyEntries);
                        List <object> memberList      = new List <object>();
                        chatRoomMembers.ToList().ForEach(p =>
                        {
                            var member = p.Split(new string[] { "|&|" }, StringSplitOptions.None);
                            if (member.Length == 3)
                            {
                                memberList.Add(new { MemberId = member[0], MemberNickName = member[2], MemberAreas = "", MemberNumber = member[1], MemberGroupName = member[2] });
                            }
                        });

                        var JsonObj    = new { GroupId = chatRoomId, GroupName = chatRoomName, MemberList = memberList };
                        var JsonString = JsonSerializeHelper.JsonSerialize(JsonObj);

                        tb_MsgBox.Text += JsonString;

                        var center = ConfigurationManager.AppSettings["ChatRoomMemberListCenter"];

                        Task.Run(() =>
                        {
                            new WebHelper().PostMessage(center, JsonString, _log);
                        });
                    }
                    catch (Exception ex)
                    {
                        _log.Error("获取到的群成员列表,请求过程中程序报错:" + ex.Message + "content为:" + content);
                    }
                }
            }
            else
            {
                base.WndProc(ref m);
            }
        }
コード例 #16
0
ファイル: Node.cs プロジェクト: llenroc/Banzai
 /// <summary>
 /// Resets the current node to unrun state.
 /// </summary>
 public virtual void Reset()
 {
     LogWriter.Debug("Resetting the node.");
     Status = NodeRunStatus.NotRun;
 }
コード例 #17
0
ファイル: Counter.cs プロジェクト: nikitazu/jphtml
 public void Start()
 {
     _watch.Start();
     _log.Debug($"Counter start at {DateTime.Now}");
 }
コード例 #18
0
ファイル: NodeTimer.cs プロジェクト: llenroc/Banzai
 public void LogStop(ILogWriter logWriter, dynamic node, string methodName)
 {
     logWriter.Debug(() => StopTimer(node, methodName));
 }
コード例 #19
0
        async partial void ConvertButtonClicked(NSObject sender)
        {
            _log.Debug($"Convert {FileToConvert.StringValue}");

            if (string.IsNullOrWhiteSpace(FileToConvert.StringValue))
            {
                _dialog.Info("Source file wasn't chosen", "Conversion is cancelled because the source file wasn't chosen");
                return;
            }

            if (!File.Exists(FileToConvert.StringValue))
            {
                _dialog.Info("Source file doesn't exist", "Conversion is cancelled because the source file doesn't exist");
                return;
            }

            string outputFile;
            string filename = string.IsNullOrWhiteSpace(FileToConvert.StringValue) ? string.Empty : Path.GetFileNameWithoutExtension(FileToConvert.StringValue);

            if (!_dialog.SaveFile("Save epub as file", "epub", filename, out outputFile))
            {
                _dialog.Info("Target file wasn't chosen", "Conversion is cancelled because the target file wasn't chosen");
                return;
            }

            var options = new Options(new string[]
            {
                "--inputFile", FileToConvert.StringValue,
                "--outputFile", outputFile,
            });

            OpenButton.Enabled           = false;
            ConvertButton.Enabled        = false;
            FileToConvert.Enabled        = false;
            ConversionStatus.StringValue = "Conversion started...";
            ConversionProgress.StartAnimation(null);

            try
            {
                var htmlToEpub = new HtmlToEpubConverter(
                    new Counter(_log),
                    _log,
                    options,
                    new MecabParser(),
                    new MecabReader(),
                    new MecabBackend(),
                    new XHtmlMaker(),
                    await _jmdicReaderTask,
                    new ContentsBreaker(new ChapterMarkersProvider(options, new ContentsDetector())),
                    new EpubMaker(_log, options, _resourceLocator),
                    new SentenceBreaker()
                    );

                options.Print(Console.Out);

                await htmlToEpub.Convert();
            }
            catch (Exception ex)
            {
                _dialog.UnexpectedError(ex);
            }
            finally
            {
                OpenButton.Enabled           = true;
                ConvertButton.Enabled        = true;
                FileToConvert.Enabled        = true;
                ConversionStatus.StringValue = "Conversion done";
                ConversionProgress.StopAnimation(null);

                _fileManager.OpenFileManagerAndShowFile(outputFile);
            }

            _log.Debug("end");
        }
コード例 #20
0
ファイル: MainWindow.xaml.cs プロジェクト: nikitazu/jphtml
        async void ConvertButtonClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_model.SourceFile))
            {
                _dialog.Info("Source file wasn't chosen", "Conversion is cancelled because the source file wasn't chosen");
                return;
            }

            if (!File.Exists(_model.SourceFile))
            {
                _dialog.Info("Source file doesn't exist", "Conversion is cancelled because the source file doesn't exist");
                return;
            }

            string targetFile;
            string filename = string.IsNullOrWhiteSpace(_model.SourceFile) ? string.Empty : Path.GetFileNameWithoutExtension(_model.SourceFile);

            if (!_dialog.SaveFile("Save epub as file", "Epub files|*.epub", filename, out targetFile))
            {
                _dialog.Info("Target file wasn't chosen", "Conversion is cancelled because the target file wasn't chosen");
                return;
            }

            _model.TargetFile = targetFile;

            var options = new Options(new string[] {
                "--inputFile", _model.SourceFile,
                "--outputFile", _model.TargetFile
            });

            // lock ui

            try
            {
                var htmlToEpub = new HtmlToEpubConverter(
                    new Counter(_log),
                    _log,
                    options,
                    new MecabParser(),
                    new MecabReader(),
                    new MecabBackend(),
                    new XHtmlMaker(),
                    await _jmdicReaderTask,
                    new ContentsBreaker(new ChapterMarkersProvider(options, new ContentsDetector())),
                    new EpubMaker(_log, options, _resourceLocator),
                    new SentenceBreaker()
                    );

                options.Print(Console.Out);

                await htmlToEpub.Convert();
            }
            catch (Exception ex)
            {
                _dialog.UnexpectedError(ex);
                throw;
            }
            finally
            {
                // unlock ui
                _fileManager.OpenFileManagerAndShowFile(Path.GetDirectoryName(targetFile));
            }
            _log.Debug("end");
        }