zoukankan      html  css  js  c++  java
  • C# winform 广告机 网络多媒体发布系统桌面版之三

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Dare.DN.Services.EntityServices;
    using Dare.DN.Components.Entities.Media;
    using System.IO;
    using System.Threading;
    using Dare.Utilities.Model;
    using System.Xml;
    using Dare.Utilities.Microsoft;
    using Dare.Utilities.IO;

    namespace DareMediaTray
    {
        public partial class MediaImportFrm : Form
        {
            bool isNormal = false;
            MediaInfoService mediaService = Dare.DN.Services.Application.Instance.GetDbService<MediaInfoService>();
            MediaFileInfoService mediaFileService = Dare.DN.Services.Application.Instance.GetDbService<MediaFileInfoService>();
            MediaFolderInfoService folderService = Dare.DN.Services.Application.Instance.GetDbService<MediaFolderInfoService>();
            MediaUC mediaUC;
            Thread[] iThreads = null;
            AutoResetEvent[] iAutoReset = null;
            int folderId = 0;
            string[] mFiles = null;
            BackgroundWorker importBgWorker = null;
            BackgroundWorker bkWork = null;
            //int iCompleted = 0;
            int mCount = 0;
            string mPath = string.Empty;
            //private bool isAbort = false;//是否终止导入任务
            public MediaImportFrm(int fdId, string[] mdFiles, MediaUC mdUC)
            {
                InitializeComponent();
                mediaUC = mdUC;
                folderId=fdId;
                mFiles = mdFiles;
                mCount = mFiles.Length;

                MediaFolderInfo mediaFolderInfo = folderService.Get(folderId);
                if (mediaFolderInfo == null) return;

                mPath = mediaFolderInfo.PhysicalPath;
                this.Text =parentForm1.TitleText= string.Format("{0}媒体导入",mPath);
                this.parentForm1.onCloseEvent += new EventHandler(parentForm1_onCloseEvent);
                this.parentForm1.onMaxEvent += new EventHandler(parentForm1_onMaxEvent);
                this.parentForm1.onMinEvent += new EventHandler(parentForm1_onMinEvent);
                this.parentForm1.onMouseMoveEvent += new EventHandler(Form1_MouseDown);
                this.parentForm1.MaxmizeIcon(this.WindowState == FormWindowState.Maximized);
               
                this.btnSubmit.Click += delegate(object sender, EventArgs e)
                {
                    RestBackWork();
                    this.Close();
                };

                importBgWorker = new BackgroundWorker();
                importBgWorker.DoWork += new DoWorkEventHandler(importBgWorker_DoWork);
                if (!importBgWorker.IsBusy)
                {
                    importBgWorker.RunWorkerAsync();
                }
            }
            private void importBgWorker_DoWork(object sender, DoWorkEventArgs e)
            {
                StartMedia(importBgWorker, e);
            }
            private void StartMedia(BackgroundWorker worker, DoWorkEventArgs e)
            {
               int i = 0;
               iThreads = new Thread[mCount];
               iAutoReset = new AutoResetEvent[mCount];

               Program.ThreadSafe(this, delegate
               {
                   this.lvImport.Items.Clear();
                   this.lvImport.View = View.Details;
                   this.lvImport.GridLines = true;
                   this.lvImport.FullRowSelect = true;
                   this.lvImport.ShowItemToolTips = true;
                   this.btnImport.Enabled = false;
                   this.btnSubmit.Enabled = false;
                   this.lvImport.SmallImageList = imageList1;
               });

               foreach (string file in mFiles)
               {
                    FileInfo fn = new FileInfo(file);
                    Program.ThreadSafe(this, delegate
                    {
                        ListViewItem li = new ListViewItem();
                        li.SubItems[0].Text = fn.Name;
                        li.SubItems.Add(fn.DirectoryName);
                        li.SubItems.Add(new FileSizeData(fn.Length).ToString());
                        li.SubItems.Add("0%");
                        li.SubItems.Add("准备导入!");
                        li.ImageIndex = 1;
                        lvImport.Items.Add(li);
                    });

                    object[] objs = new object[4];
                    objs[0] = file;
                    objs[1] = mPath;
                    objs[2] = folderId;
                    objs[3] = i;

                    iAutoReset[i] = new AutoResetEvent(false);
                    iThreads[i] = new Thread(new ParameterizedThreadStart(MediaImport));
                    if (fn.Length < 10*1024 * 1024)
                        iThreads[i].Priority = ThreadPriority.Highest;
                    iThreads[i].IsBackground = true;
                    iThreads[i].Start(objs);
                    i++;
                }
               WaitAll(iAutoReset);//阻塞信号
               //WaitHandle.WaitAll(IAutoReset);
               foreach (Thread thread in iThreads)
               {
                   thread.Abort();
               }
               iThreads = null;
               Program.ThreadSafe(this, delegate
               {
                   this.btnImport.Enabled = true;
                   this.btnSubmit.Enabled = true;
               });
            }
            /// <summary>
            /// 媒体文件名非法字符过滤
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            private string RemoveSpecialChar(string input)
            {
                string[] aryChar = { "\"\"", "/", ":", "*", "?", "|", "&lt;", "&gt;", "&quot;", "&amp;", " ", "+", "=", ",", "'", "%", "#", };
                for (int i = 0; i < aryChar.Length; i++)
                {
                    input = input.Replace(aryChar[i], string.Empty);
                }
                return input;
            }
            /// <summary>
            /// 媒体导入方法
            /// </summary>
            /// <param name="obj"></param>
            private void MediaImport(object obj)
            {
                Thread.Sleep(150);
                object[] objs = (object[])obj;
                string file = (string)objs[0];
                string path = (string)objs[1];
                int folderId = (int)objs[2];
                int j = (int)objs[3];

                try
                {
                    if (!File.Exists(file))
                    {
                        Program.ThreadSafe(this, delegate
                        {
                            lvImport.Items[j].SubItems[4].Text = "文件[" + file + "]不存在!";
                            lvImport.Items[j].ImageIndex = 2;
                        });
                    }
                    else
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        MediaFileInfo info = new MediaFileInfo();
                        if (!mediaFileService.AnalyseAndSetMediaFileInfo(info, fileInfo))
                        {
                            Program.ThreadSafe(this, delegate
                            {
                                lvImport.Items[j].SubItems[4].Text = "获取文件[" + file + "]信息失败!";
                                lvImport.Items[j].ImageIndex = 2;
                            });
                        }
                        else
                        {
                            string copyDir = string.Empty;
                            string copyToFile = string.Empty;
                            string retavl = string.Empty;

                            info.Path = path;
                            retavl = mediaService.MediaInfoCheck(info);
                            if (retavl.Length == 0)
                            {
                                copyDir = Path.Combine(Path.Combine(Application.StartupPath, "resource"), path);
                                if (!Directory.Exists(copyDir)) Directory.CreateDirectory(copyDir);

                                //string fName = RemoveSpecialChar(fileInfo.Name);
                                string fName = fileInfo.Name;
                                info.Name = fName;

                                copyToFile = Path.Combine(copyDir, fName);
                                int copyLength = 0;

                                long fLength = fileInfo.Length;
                                using (FileStream stream = File.Open(copyToFile, FileMode.Create, FileAccess.Write))
                                {
                                    using (FileStream fileStream = fileInfo.OpenRead())
                                    {
                                        int btLength = 256 * 1024;//256k
                                        byte[] buffer = new byte[btLength];
                                        int readCount = 0;
                                        while ((readCount = fileStream.Read(buffer, 0, btLength)) > 0)
                                        {
                                            //if (isAbort)
                                            //{
                                            //    File.Delete(copyToFile);
                                            //    break;
                                            //}
                                            int tolPercent = 0;
                                            copyLength += readCount;//已经复制大小
                                            stream.Write(buffer, 0, readCount);
                                            tolPercent = (int)((float)(copyLength / (float)fLength * 100));
                                            Program.ThreadSafe(this, delegate
                                            {
                                                lvImport.Items[j].SubItems[3].Text = tolPercent.ToString() + "%";
                                                lvImport.Items[j].SubItems[4].Text = "正在导入!";
                                            });
                                        }
                                    }
                                }
                             
                                retavl = mediaService.CreateAndSaveAsMediaInfo(folderId, copyToFile, info);
                                if (retavl.Length == 0)
                                {
                                    Program.ThreadSafe(this, delegate
                                    {
                                        lvImport.Items[j].SubItems[4].Text = "成功导入!";
                                        lvImport.Items[j].ImageIndex = 0;
                                        mediaUC.MediaLViewBind(folderId);//刷新父窗体列表
                                    });
                                }
                                else
                                {
                                    Program.ThreadSafe(this, delegate
                                    {
                                        lvImport.Items[j].SubItems[4].Text = retavl;
                                        lvImport.Items[j].ImageIndex = 2;
                                    });
                                }
                            }
                            else
                            {
                                Program.ThreadSafe(this, delegate
                                {
                                    lvImport.Items[j].SubItems[4].Text = retavl;
                                    lvImport.Items[j].ImageIndex = 2;
                                });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Program.ThreadSafe(this, delegate
                    {
                        lvImport.Items[j].SubItems[4].Text = ex.Message;
                        lvImport.Items[j].ImageIndex = 2;
                    });
                    Dare.DN.Services.Application.Instance.Logger.ErrorFormat("MediaImportFrm-MediaImport-错误原因:{0}", ex.Message);
                }
                iAutoReset[j].Set();
            }
            /// <summary>
            /// 突破64个阻塞线程方法
            /// </summary>
            /// <param name="waitHandles"></param>
            private static void WaitAll(WaitHandle[] waitHandles)
            {
                if (waitHandles == null) throw new ArgumentNullException("阻塞参数非空!");
                foreach (WaitHandle waitHandle in waitHandles)
                {
                    waitHandle.WaitOne();
                }
            }
            private void Form1_MouseDown(object sender, EventArgs e)
            {
                parentForm1.MouseMoveEvent(this.Handle);
            }
            private void parentForm1_onMinEvent(object sender, EventArgs e)
            {
                this.WindowState = FormWindowState.Minimized;
            }

            private void parentForm1_onMaxEvent(object sender, EventArgs e)
            {
                if (isNormal)
                {
                    isNormal = false;
                    this.WindowState = FormWindowState.Normal;
                }
                else
                {
                    isNormal = true;
                    this.WindowState = FormWindowState.Maximized;
                }
                this.parentForm1.MaxmizeIcon(this.WindowState == FormWindowState.Maximized);
            }
            private void parentForm1_onCloseEvent(object sender, EventArgs e)
            {
                //isAbort = true;
                RestBackWork();
                this.Close();
            }
            private void btnClose_Click(object sender, EventArgs e)
            {
                //isAbort = true;
                RestBackWork();
                this.Close();
            }

            protected override void OnClosed(EventArgs e)
            {
                base.OnClosed(e);
            }

            private void RestBackWork()
            {
                if (iThreads != null)
                {
                    foreach (Thread thread in iThreads)
                    {
                        thread.Abort();
                    }
                }
                iThreads = null;
                importBgWorker = null;
                bkWork = null;
            }
            private void btnImport_Click(object sender, EventArgs e)
            {
                RestBackWork();
                string rootPath = Path.GetPathRoot(Application.StartupPath);
                DriveInfo drive = new DriveInfo(rootPath);
                if (drive.AvailableFreeSpace < 1024 * 1024)
                {
                    MessageBox.Show(this, "对不起,当前磁盘[" + rootPath + "]剩余空间[" + new FileSizeData(drive.AvailableFreeSpace).ToString() + "],请清理磁盘空间!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    string[] iFiles = null;
                    int rootFolderId=0;
                    rootFolderId = folderService.GetMediaFolderRootParentId(folderId);
                    switch (rootFolderId)
                    {
                        case 1:
                            ofd.Title = "导入audio文件";//resource\audio
                            ofd.Filter = "音频文件(*.wav,*.mp3,*.aac,*.wma)|*.wav;*.mp3;*.aac;*.wma";
                            break;
                        case 2:
                            ofd.Title = "导入background文件";//resource\background
                            ofd.Filter = "背景文件(*.bmp,*.jpg,*.jpeg,*.png,*.gif,*.tif,*.tiff)|*.bmp;*.jpg;*.jpeg;*.png;*.gif;*.tif;*.tiff";
                            break;
                        case 3:
                            ofd.Title = "导入image文件";//resource\image
                            ofd.Filter = "图片文件(*.bmp,*.jpg,*.jpeg,*.png,*.gif,*.tif,*.tiff)|*.bmp;*.jpg;*.jpeg;*.png;*.gif;*.tif;*.tiff";
                            break;
                        case 7:
                            ofd.Title = "导入text文件";//resource\text
                            ofd.Filter = "文本文件(*.txt)|*.txt";
                            break;
                        case 8:
                            ofd.Title = "导入video文件";//resource\video
                            ofd.Filter = "视频文件(*.mpg,*.mpeg,*.vob,*.avi,*.mkv,*.mov,*.mp4,*.flv,*.wmv,*.ts,*.trp)|*.mpg;*.mpeg;*.vob;*.avi;*.mkv;*.mov;*.mp4;*.flv;*.wmv;*.ts;*.trp";
                            break;
                        case 9:
                            ofd.Title = "导入document文件";//resource\text
                            ofd.Filter = "文档文件(*.ppt,*.pptx)|*.ppt;*.pptx";
                            break;
                        default://resource\unknow
                            break;
                    }
                    ofd.Multiselect = true;
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        int maxCount = Dare.DN.Services.Application.Instance.AppSettings.MediaMaxCount;
                        iFiles = ofd.FileNames;
                        if (iFiles.Length > maxCount)
                        {
                            MessageBox.Show(this, string.Format("对不起,一次最多只能导入{0}个媒体文件!", maxCount.ToString()), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        bool isResult = false;
                        foreach (string file in iFiles)
                        {
                            string extName = Path.GetExtension(file).ToLower();
                            if (extName == ".ppt" || extName == ".pptx")
                            {
                                if (!PowerPointHelper.IsPowerPointInstalled())
                                {
                                    isResult = true;
                                    break;
                                }
                            }
                        }

                        if (isResult)
                        {
                            MessageBox.Show(this, "未发现Microsoft PowerPoint 2000及以上版本安装于本机!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        //同名文件集合
                        List<string> listFiles = new List<string>();
                        //无同名文件集合
                        List<string> listNoFiles = new List<string>();
                        foreach (string file in iFiles)
                        {
                            string name = Path.GetFileName(file);
                            //if (mediaService.IsMediaExsit(folderId, RemoveSpecialChar(name)))
                            if (mediaService.IsMediaExsit(folderId, name))
                            {
                                listFiles.Add(name);
                            }
                            else
                            {
                                listNoFiles.Add(file);
                            }
                        }

                        if (listFiles.Count > 0)
                        {
                            string filesShow = string.Empty;
                            filesShow = String.Join("\r\n", listFiles.ToArray());
                            #region
                            //if (MessageBox.Show(this, string.Format("系统已存在下列同名文件:\r\n\r\n{0}\r\n\r\n按【是】全部覆盖,按【否】跳过重复.", filesShow.Length > 200 ? filesShow.Substring(0, 200) + "\r\n............................." : filesShow), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            //{
                            //    mFiles = iFiles;
                            //}
                            //else
                            //{
                            //    if (listNoFiles.Count > 0)
                            //    {
                            //        mFiles = listNoFiles.ToArray();
                            //    }
                            //    else
                            //    {
                            //        //MessageBox.Show(this, "文件全部重复,没有可跳过项!", "提示", MessageBoxButtons.OK,MessageBoxIcon.Information);
                            //        return;
                            //    }
                            //}
                            #endregion
                            MessageBox.Show(this, string.Format("系统已存在下列同名文件:\r\n\r\n{0}\r\n\r\n请更换名称后,再导入.", filesShow.Length > 200 ? filesShow.Substring(0, 200) + "\r\n............................." : filesShow), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        else
                        {
                            mFiles = iFiles;
                        }

                        mCount = mFiles.Length;
                        bkWork = new BackgroundWorker();
                        bkWork.DoWork += new DoWorkEventHandler(bkWork_DoWork);
                        if (!bkWork.IsBusy)
                        {
                            bkWork.RunWorkerAsync();
                        }
                    }
                }
            }

            void bkWork_DoWork(object sender, DoWorkEventArgs e)
            {
                StartMedia(bkWork, e);
            }

            private void importFdMenuItem_Click(object sender, EventArgs e)
            {
                btnImport_Click(sender,e);
            }
        }
    }

  • 相关阅读:
    Ubuntu下Chromium for Android 源码的编译
    Ubuntu下编译Chromium for Android
    解决Inno Setup制作安装包无法创建桌面快捷方式的问题
    linux下验证码无法显示:Could not initialize class sun.awt.X1 解决方案
    在ubuntu 14.04 64位系统上安装32位库
    zxing实现二维码生成和解析
    H264码流打包分析
    YUV格式&像素
    谈谈“色彩空间表示方法”——RGB、YUY2、YUYV、YVYU、UYVY、AYUV
    RTP与RTCP协议介绍
  • 原文地址:https://www.cnblogs.com/fx2008/p/2147275.html
Copyright © 2011-2022 走看看