关于豆丁文库效果的实现(类似百度文库),注册WINDOWS服务,以拒绝分配给IIS过高的权限

最近应用FLASHPAPER2.2来实现百度文库(豆丁文库)的功能,但是要服务器配置的时候IIS需要配置到管理员的权限才能实现打印。

CSDN讨论地址:http://topic.csdn.net/u/20120717/07/55bb1837-07a7-465b-bc88-895a7c45882a.html

在WEB上给网站如此高的运行权限会有相当大的完全隐患,特别是文档功能需要开放上传功能,安全隐患就更高了。

因此我将文档转换的操作从WEB中分享出来,写成服务注册到服务器上,在服务器上定时进行文档转换。

创建一个新的控制台应用程序,将最下的代码贴入(各有所好,请自我调整)。

并在VS的控制台使用命令

installutil     xxx.exe(你的应用程序生成的文件)

来注册服务,卸载服务的命令是 installutil  /u   xxx.exe(你的应用程序生成的文件)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;
using System.Threading;
using System.IO;

namespace cxfwzx.FlashPrinter
{
    class Program : ServiceBase
    {
        #region 常量
        public const string SERVICE_NAME = "文档转换服务";
        public const string CUSTOMSRC_NAME = "文档转换服务,用于将可阅读的文档转换成SWF文件";
        public const string LOG_NAME = "flashprinter";

        #endregion

        #region 字段
        string foldPath;
        TimeSpan interval;
        TimeSpan delay;
        Timer timer;

        #endregion

        #region 私有方法
        void Reset()
        {
            interval = TimeSpan.FromSeconds(3600);//默认每小时进行一次,由服务参数第二参数决定单位秒;
            delay = TimeSpan.Zero;
        }

        void ParseArgs(string[] args)
        {
            foldPath = args.Length > 0 ? args[0] : foldPath;
            if (string.IsNullOrEmpty(foldPath))
                throw new ArgumentException();
            if (args.Length >= 2)
                interval = TimeSpan.FromSeconds(Convert.ToInt32(args[1]));
        }

        void RaiseTimer()
        {
            timer = new Timer(TimerCallback, null, delay, interval);
        }
        void TryStopTimer()
        {
            if (timer != null)
                timer.Dispose();
            timer = null;
        }

        /// <summary>
        /// 主方法,在此方法中调用FLASHPRINTER进行文档转换
        /// </summary>
        /// <param name="state"></param>
        void TimerCallback(object state)
        {
            DateTime startTime = DateTime.Now;
            //获取目标文件夹下,需要转换的文档文件
            DirectoryInfo dir = new DirectoryInfo(foldPath);
            List<string> fileList = dir.GetFileList();
            WriteLogEntry(String.Format("开始进行文档转换,此次转换总记录{0}条", fileList.Count), false);
            int count = 0;
            while (fileList.Count > 0)
            {
                if (Process.GetProcessesByName("FlashPrinter").Count<Process>() > 0)
                {
                    Thread.Sleep(10000); continue;
                }
                else
                {
                    foreach (var item in Process.GetProcesses()
                            .Where(u =>
                               u.ProcessName == "EXCEL" ||
                               u.ProcessName == "WINWORD" ||
                               u.ProcessName == "POWERPNT" ||
                               u.ProcessName == "AcroRd32")

                        )
                    {
                        try
                        {
                            item.Kill();
                        }
                        catch { }
                    }
                }
                string filePath = fileList[0];
                fileList.RemoveAt(0);
                string swfPath = filePath.Substring(0, filePath.LastIndexOf('.')) + ".swf";
                if (!File.Exists(filePath) || File.Exists(swfPath)) { continue; }

                FileInfo finfo = new FileInfo(filePath);
                int time = ((int)(finfo.Length / (1024 * 1204))) * 20 + 20;
                Process pc = new System.Diagnostics.Process();
                pc.StartInfo.FileName = "flashprinter";
                pc.StartInfo.Arguments = string.Format("{0} -o {1}", filePath, swfPath);
                pc.StartInfo.CreateNoWindow = true;
                pc.StartInfo.UseShellExecute = false;
                pc.StartInfo.RedirectStandardInput = false;
                pc.StartInfo.RedirectStandardOutput = false;
                pc.StartInfo.RedirectStandardError = true;
                pc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                pc.Start();
                bool res = pc.WaitForExit(time * 1000);
                if (res) { count++; }

                pc.Close();
                pc.Dispose();
                Thread.Sleep(10000);
            }
            WriteLogEntry(String.Format("文档转换结束,此次成功转换记录{0}条", count), false);

        }

        void WriteLogEntry(string message, bool error)
        {
            EventLog.WriteEntry(CUSTOMSRC_NAME, message, error ? EventLogEntryType.Error : EventLogEntryType.Information);
        }
        #endregion

        #region 构造函数

        public Program()
        {
            base.ServiceName = SERVICE_NAME;
            base.CanStop = true;
            base.CanPauseAndContinue = true;
            base.AutoLog = false;
        }

        #endregion

        #region 继承虚方法
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            Reset();
            try
            {
                ParseArgs(args);
                WriteLogEntry(String.Format("开始运行。参数:{0}", String.Join(", ", args)), false);
                RaiseTimer();
            }
            catch (Exception ex)
            {
                WriteLogEntry("用户参数错误: " + ex.Message, true);
                Stop();
            }
        }

        protected override void OnStop()
        {
            base.OnStop();
            WriteLogEntry("停止", false);
            TryStopTimer();
        }

        protected override void OnContinue()
        {
            base.OnContinue();
            WriteLogEntry("继续", false);
            RaiseTimer();
        }

        protected override void OnPause()
        {
            base.OnPause();
            WriteLogEntry("暂停", false);
            TryStopTimer();
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            TryStopTimer();
        }

        #endregion

        #region 主函数
        static void Main(string[] args)
        {
            ServiceBase.Run(new Program());
        }

        #endregion

    }

    [RunInstaller(true)]
    public class MyInstaller : Installer
    {
        public MyInstaller()
        {
            ServiceProcessInstaller spi = new ServiceProcessInstaller();
            ServiceInstaller si = new ServiceInstaller();
            EventLogInstaller ei = new EventLogInstaller();


            spi.Account = ServiceAccount.LocalSystem;

            si.ServiceName = Program.SERVICE_NAME;
            si.StartType = ServiceStartMode.Manual;
            si.Description = "文档转换服务用于将文档转换成SWF文件以供阅读";
            si.DisplayName = Program.SERVICE_NAME;

            ei.Source = Program.CUSTOMSRC_NAME;
            ei.Log = Program.LOG_NAME;

            Installers.Add(spi);
            Installers.Add(si);
            Installers.Add(ei);

            if (EventLog.SourceExists(Program.CUSTOMSRC_NAME))
                EventLog.DeleteEventSource(Program.CUSTOMSRC_NAME);
        }
    }

    public static class fileTemp
    {
        /// <summary>
        /// 获取文件夹下的未生成.SWF的文件
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static List<string> GetFileList(this DirectoryInfo dir)
        {
            List<string> res = new List<string>();
            var fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
            var docList = fileList.Where(u => u.Extension == ".doc" ||
                u.Extension == ".docx" ||
                u.Extension == ".xls" ||
                u.Extension == ".xlsx" ||
                u.Extension == ".ppt" ||
                u.Extension == ".pptx" ||
                u.Extension == ".pdf" ||
                u.Extension == ".txt").OrderBy(u=>u.Name);
            var swfList = fileList.Where(u => u.Extension == ".swf");
            foreach (var item in docList)
            {
                string fNameNoSuffix = item.Name.Replace(item.Extension, "");
                {
                    if (swfList.Where(u => u.Name.Contains(fNameNoSuffix)).Count() <= 0)
                        res.Add(item.FullName);
                }
            }
            return res;
        }
    }


}

 

posted on 2012-07-19 15:16  Tim Feng  阅读(345)  评论(0编辑  收藏  举报

导航