Example #1
0
        // Advance:執行把資料建置到Listview
        private void GenerateListviewItem(int page)
        {
            lvwAdvanceClassify.ItemsSource = null;
            lvwAdvanceClassify.Items.Clear();
            cmbPager.ItemsSource = null;
            _dataPager.Clear();

            dynamic files = GetAdvanceFileList();
            int totalRecordNum = Enumerable.Count(files);
            _advCurrentPage = page;

            if (totalRecordNum <= _advPageSize)
            {
                _advTotalPage = 1;
                cmbPager.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                _advTotalPage = totalRecordNum % _advPageSize == 0 ?
                             totalRecordNum / _advPageSize :
                             totalRecordNum / _advPageSize + 1;
                if (_advTotalPage == 0)
                    _advTotalPage = 1;

                for (int i = 1; i <= _advTotalPage; i++)
                {
                    _dataPager.Add(i);
                }
                cmbPager.Visibility = System.Windows.Visibility.Visible;
                cmbPager.SelectedItem = page ;
            }
            cmbPager.ItemsSource = _dataPager;
            int skipNum = (_advCurrentPage - 1) * _advPageSize;
            files = GetAdvanceFileList(skipNum, _advPageSize);

             // For list mode datasource
             System.Collections.ObjectModel.ObservableCollection<FileInfo> fileCollection =
                 new System.Collections.ObjectModel.ObservableCollection<FileInfo>();

            ApiHelper api = new ApiHelper();
            foreach (var file in files)
            {
                if (_isAdvanceTileView)
                {
                    bool isImageFile = false;
                    lvwAdvanceClassify.View = lvwAdvanceClassify.FindResource("TileView") as ViewBase;

                    // Using store procedure to get full path.
                    string path = DBHelper.GenerateFileFullPath(file.Id);
                    if (api.CheckPath(path))
                    {
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;

                        ExtensionHelper helper = new ExtensionHelper();
                        string iconPath = helper.GetIconPath(
                            System.IO.Path.GetExtension(file.NickName));

                        if (iconPath != "img.ico")
                        {
                            bitmap.UriSource = new Uri(iconPath);
                        }
                        else
                        {
                            isImageFile = true;
                            bitmap.UriSource = new Uri(String.Format(GlobalHelper.ApiThumb, path));
                        }

                        bitmap.EndInit();
                        Image img = new Image();
                        if (!isImageFile)
                        {
                            img.Width = 60;
                            img.Height = 60;
                        }
                        else
                        {
                            img.Width = 120;
                            img.Height = 120;
                        }

                        img.Source = bitmap;
                        string title = Convert.ToString(file.NickName);
                        Tile tile = new Tile();
                        tile.FontFamily = new FontFamily("Microsoft JhengHei");
                        tile.Width = 120;
                        tile.Height = 120;
                        tile.Margin = new Thickness(5);
                        tile.Content = img;
                        tile.Tag = path; // Download Path
                        tile.ToolTip = file.NickName;
                        tile.Click += new RoutedEventHandler(tileAdvance_Click);
                        tile.MouseDoubleClick += new MouseButtonEventHandler(tileAdvance_MouseDoubleClick);
                        if (isImageFile)
                        {
                            tile.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
                        }
                        else
                        {
                            tile.Title = title.Length > 12 ? String.Format("{0}…", title.Substring(0, 11)) : title;
                        }
                        lvwAdvanceClassify.Items.Add(tile);
                    }
                }
                else
                {
                    lvwAdvanceClassify.View = lvwAdvanceClassify.FindResource("AdvanceListView") as ViewBase;
                     string path = DBHelper.GenerateFileFullPath(file.Id);
                     if (api.CheckPath(path))
                     {
                         fileCollection.Add(new FileInfo
                         {
                             FileName = file.Name,
                             FilePath = DBHelper.GenerateFileFullPath(file.Id),
                             FileId = file.Id
                         });
                     }
                }
            }
            // 修改Listview Datasource
            if (!_isAdvanceTileView)
            {
                lvwAdvanceClassify.ItemsSource = fileCollection;
            }
            if (lvwAdvanceClassify.Items.Count == 0)
            {
                lbMessage.Visibility = System.Windows.Visibility.Visible;
                lbMessage.Content = "搜尋完成,無資料紀錄";
            }
            else
            {
                lbMessage.Visibility = System.Windows.Visibility.Hidden;
                lbMessage.Content = "";
            }
        }
Example #2
0
        private void GetPath()
        {
            if (String.IsNullOrEmpty(txtName.Text) || String.IsNullOrEmpty(txtNickName.Text))
            {
                lbMessage.Content = "欄位不得為空白";
                return;
            }

            if (!Regex.IsMatch(txtName.Text.Trim(), PATTERN_SYSTEMNAME))
            {
                lbMessage.Content = "系統名稱格式錯誤";
                return;
            }
            else
            {
                lbMessage.Content = "";
            }

            if (!Regex.IsMatch(txtNickName.Text.Trim(), PATTERN_NICKNAME))
            {
                lbMessage.Content = "瀏覽名稱格式錯誤";
                return;
            }
            else
            {
                lbMessage.Content = "";
            }
            // 把資料設置 Properties
            this.SystemName = txtName.Text.Trim();
            this.NickName = txtNickName.Text.Trim();
            this.ClassifyId = 0;
            this.NewPath = this.NewPath.Substring(0, this.NewPath.LastIndexOf('/') + 1) + this.SystemName;

            // 判斷如果有這個名稱則提醒
            ApiHelper api = new ApiHelper();
            // True: 可以編輯, False: 不能編輯
            if (api.CheckRenamePath(this.OldPath, this.NewPath))
            {
                txtName.Foreground = Brushes.Black;
                lbMessage.Content = "";
                this.IsDone = true;
                this.Close();
            }
            else
            {
                txtName.Foreground = Brushes.Red;
                lbMessage.Content = "此系統名稱已存在,請換別的名稱";
            }
        }
Example #3
0
        /// <summary>
        /// Query of Manage: 建立目錄 Mehtod
        /// </summary>
        /// <param name="path">欲建立的完整路徑 /Origin/Path/Add/'NewFolderName'</param>
        /// <param name="idPath">前段路徑的ID Paht : /1/2/3</param>
        /// <param name="folderName">新建立的NickName</param>
        /// <returns></returns>
        private bool CreateFolder(string path, string idPath, string folderName)
        {
            string[] paths = path.Split(new char[] {'/'},StringSplitOptions.RemoveEmptyEntries);
            // ID Path 會少一層用來寫入db用
            string[] ids = idPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            int level = paths.Count();
            ApiHelper api = new ApiHelper();
            switch (level)
            {
                case 1:
                    try
                    {
                        if (api.CreateDirectory(path))
                        {
                            CLv1Classify.InsertOrUpdate(null, paths[0], folderName);
                            GetBreadcrumbBarPath();
                            navBar.Path = path;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    break;
                case 2:
                    int classfyId = Convert.ToInt32(ids[0]);
                    try
                    {
                        if (api.CreateDirectory(path))
                        {
                            CLv2Customer.InsertOrUpdate(null, paths[1], folderName, classfyId);
                            GetBreadcrumbBarPath(2);
                            navBar.Path = path;

                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    break;
                case 3:
                    int companyId = Convert.ToInt32(ids[1]);
                    try
                    {
                        if (api.CreateDirectory(path))
                        {
                            CLv3CustomerBranch.InsertOrUpdate(null, paths[2], folderName, companyId);
                            GetBreadcrumbBarPath(3);
                            navBar.Path = path;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    break;
                case 4:
                    int branchId =  Convert.ToInt32(ids[2]);
                    try
                    {
                        if (api.CreateDirectory(path) && api.CreateCategorys(path))
                        {
                            CLv4Line.InsertOrUpdate(null, paths[3], folderName, branchId);
                            GetBreadcrumbBarPath(4);
                            navBar.Path = path;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    break;
                case 5:
                    try
                    {
                        if (api.AddCategorys(paths[4]))
                        {
                            CFileCategory.InsertOrUpdate(null, paths[4], folderName);
                            GetBreadcrumbBarPath(5);
                            navBar.Path = path;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    break;
            };
            return true;
        }
Example #4
0
 /// <summary>
 /// Query of Manage: 刪除目錄或檔案
 /// </summary>
 /// <param name="path"></param>
 /// <param name="idPath"></param>
 private void DeleteFolderOrFile(string path, string idPath)
 {
     string[] paths = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
     string[] ids = idPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
     int id = 0;
     int level = paths.Count();
     ApiHelper api = new ApiHelper();
     switch (level)
     {
         case 1:
             id = Convert.ToInt32(ids[0]);
             if (System.Windows.MessageBox.Show("是否刪除?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
             {
                 try
                 {
                     if(api.RemoveDirectory(path))
                     {
                         CLv1Classify.Delete(id, GlobalHelper.LoginUserID);
                         GetBreadcrumbBarPath();
                         navBar.Path = path;
                     }
                 }
                 catch(Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 2:
             id = Convert.ToInt32(ids[1]);
             if (System.Windows.MessageBox.Show("是否刪除?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
             {
                 try
                 {
                     if( api.RemoveDirectory(path))
                     {
                         CLv2Customer.Delete(id, GlobalHelper.LoginUserID);
                         navBar.Path = path;
                     }
                 }
                 catch(Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 3:
             id = Convert.ToInt32(ids[2]);
             if (System.Windows.MessageBox.Show("是否刪除?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
             {
                 try
                 {
                     if(api.RemoveDirectory(path))
                     {
                         CLv3CustomerBranch.Delete(id, GlobalHelper.LoginUserID);
                         navBar.Path = path;
                     }
                 }
                  catch(Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 4:
             id = Convert.ToInt32(ids[3]);
             if (System.Windows.MessageBox.Show("是否刪除?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
             {
                 try
                 {
                     if(api.RemoveDirectory(path))
                     {
                         CLv4Line.Delete(id, GlobalHelper.LoginUserID);
                         navBar.Path = path;
                     }
                 }
                 catch(Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 5:
             id = Convert.ToInt32(ids[4]);
             if (System.Windows.MessageBox.Show("是否刪除?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
             {
                 try
                 {
                     // CHECK:
                     int result = api.RemoveCategorys(paths[4]);
                     if (result > 0) // 這邊需要移除所有公司的FileCategory ex BOM,Documents
                     {
                         CFileCategory.Delete(id, GlobalHelper.LoginUserID);
                         navBar.Path = path;
                     }
                 }
                 catch(Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 6:
             id = Convert.ToInt32(ids[5]);
             if (System.Windows.MessageBox.Show("是否刪除?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
             {
                 try
                 {
                     path = DBHelper.GenerateFileFullPath(id);
                     if (api.RemoveDirectory(path))
                     {
                         CFile.Delete(id, GlobalHelper.LoginUserID);
                         navBar.Path = path;
                     }
                 }
                 catch(Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
     };
 }
Example #5
0
        /// <summary>
        /// Query:效能改善: 延遲載入
        /// </summary>
        /// <param name="level">選擇到的層級才載入</param>
        public void GetBreadcrumbBarPath(int level)
        {
            WFTPDbContext db = new WFTPDbContext();

            // Get remote folder list
            ApiHelper api = new ApiHelper();
            List<string> remoteFolderList = api.Dir(_ftpPath, true).ToList();

            switch (level)
            {
                case 2:
                    var lv2 = from company in db.Lv2Customers
                              where company.ClassifyId == _catalogLevelId[1]
                              orderby company.CompanyNickName
                              select company;
                    string expr = String.Format("/bc/bc[@id={0}]", _catalogLevelId[1]);
                    XmlNode xndClassify = _xdoc.SelectSingleNode(expr);
                    if (xndClassify.ChildNodes.Count > 0)
                    {
                        XPathNavigator navigator = _xdoc.CreateNavigator();
                        XPathNavigator first = navigator.SelectSingleNode(expr + "/bc[1]");
                        XPathNavigator last = navigator.SelectSingleNode(expr + "/bc[last()]");
                        navigator.MoveTo(first);
                        navigator.DeleteRange(last);
                    }
                    foreach (var company in lv2)
                    {
                        if (!remoteFolderList.Contains(company.CompanyName)) continue;
                        XmlElement xelCompany = _xdoc.CreateElement("bc");
                        xelCompany.SetAttribute("title", company.CompanyNickName);
                        xelCompany.SetAttribute("id", company.CompanyId.ToString());
                        xndClassify.AppendChild(xelCompany);
                    }
                    break;
                case 3:
                    var lv3 = from branch in db.Lv3CustomerBranches
                              where branch.CompanyId == _catalogLevelId[2]
                              orderby branch.BranchNickName
                              select branch;
                    expr = String.Format("/bc/bc[@id={0}]/bc[@id={1}]", _catalogLevelId[1], _catalogLevelId[2]);
                    XmlNode xndCompany = _xdoc.SelectSingleNode(expr);
                    if (xndCompany.ChildNodes.Count > 0)
                    {
                        XPathNavigator navigator = _xdoc.CreateNavigator();
                        XPathNavigator first = navigator.SelectSingleNode(expr + "/bc[1]");
                        XPathNavigator last = navigator.SelectSingleNode(expr + "/bc[last()]");
                        navigator.MoveTo(first);
                        navigator.DeleteRange(last);
                    }
                    foreach (var branch in lv3)
                    {
                        if (!remoteFolderList.Contains(branch.BranchName)) continue;
                        XmlElement xelBranch = _xdoc.CreateElement("bc");
                        xelBranch.SetAttribute("title", branch.BranchNickName);
                        xelBranch.SetAttribute("id", branch.BranchId.ToString());
                        xndCompany.AppendChild(xelBranch);
                    }
                    break;
                case 4:
                    var lv4 = from line in db.Lv4Lines
                              where line.BranchId == _catalogLevelId[3]
                              orderby line.LineNickName
                              select line;
                    expr = String.Format("/bc/bc[@id={0}]/bc[@id={1}]/bc[@id={2}]", _catalogLevelId[1], _catalogLevelId[2], _catalogLevelId[3]);
                    XmlNode xndBranch = _xdoc.SelectSingleNode(expr);
                    if (xndBranch.ChildNodes.Count > 0)
                    {
                        XPathNavigator navigator = _xdoc.CreateNavigator();
                        XPathNavigator first = navigator.SelectSingleNode(expr + "/bc[1]");
                        XPathNavigator last = navigator.SelectSingleNode(expr + "/bc[last()]");
                        navigator.MoveTo(first);
                        navigator.DeleteRange(last);
                    }
                    foreach (var line in lv4)
                    {
                        if (!remoteFolderList.Contains(line.LineName)) continue;
                        XmlElement xelLine = _xdoc.CreateElement("bc");
                        xelLine.SetAttribute("title", line.LineNickName);
                        xelLine.SetAttribute("id", line.LineId.ToString());
                        xndBranch.AppendChild(xelLine);
                    }
                    break;
                case 5:
                    var lv5 = from category in db.Lv5FileCategorys
                              orderby category.ClassNickName
                              select category;
                    expr = String.Format("/bc/bc[@id={0}]/bc[@id={1}]/bc[@id={2}]/bc[@id={3}]", _catalogLevelId[1], _catalogLevelId[2], _catalogLevelId[3], _catalogLevelId[4]);
                    XmlNode xndLine = _xdoc.SelectSingleNode(expr);
                    if (xndLine.ChildNodes.Count > 0)
                    {
                        // nothing.
                    }
                    else
                    {
                        foreach (var category in lv5)
                        {
                            XmlElement xelCategory = _xdoc.CreateElement("bc");
                            xelCategory.SetAttribute("title", category.ClassNickName);
                            xelCategory.SetAttribute("id", category.FileCategoryId.ToString());
                            xndLine.AppendChild(xelCategory);
                        }
                    }
                    break;
            }
        }
Example #6
0
 // Query of Manage: 編輯名稱
 private void RenameFolder(string path, string idPath, string newPath, string newNickName)
 {
     string[] paths = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
     string[] newPaths = newPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
     string[] ids = idPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
     int level = paths.Count();
     int id = 0;
     ApiHelper api = new ApiHelper();
     switch (level)
     {
         case 1:
             id = Convert.ToInt32(ids[0]);
             if (api.Rename(path, newPath))
             {
                 try
                 {
                     CLv1Classify.InsertOrUpdate(id, newPaths[0], newNickName);
                     GetBreadcrumbBarPath();
                     navBar.Path = path;
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 2:
             id = Convert.ToInt32(ids[1]);
             int classfyId = Convert.ToInt32(ids[0]);
             if (api.Rename(path, newPath))
             {
                 try
                 {
                     CLv2Customer.InsertOrUpdate(id, newPaths[1], newNickName, classfyId);
                     GetBreadcrumbBarPath(2);
                     navBar.Path = path;
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 3:
             id = Convert.ToInt32(ids[2]);
             if (api.Rename(path, newPath))
             {
                 try
                 {
                     CLv3CustomerBranch.InsertOrUpdate(id, newPaths[2], newNickName, 0);
                     GetBreadcrumbBarPath(3);
                     navBar.Path = path;
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 4:
             id = Convert.ToInt32(ids[3]);
             if (api.Rename(path, newPath))
             {
                 try
                 {
                     CLv4Line.InsertOrUpdate(id, newPaths[3], newNickName, 0);
                     GetBreadcrumbBarPath(4);
                     navBar.Path = path;
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
         case 5:
             id = Convert.ToInt32(ids[4]);
             int result = api.RenameCategorys(paths[4], newPaths[4]);
             if (result >= 0)
             {
                 try
                 {
                     CFileCategory.InsertOrUpdate(id, newPaths[4], newNickName);
                     GetBreadcrumbBarPath(5);
                     navBar.Path = path;
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             break;
     };
 }
Example #7
0
        private void bgworkerStartUpload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Dictionary<string, string> asyncResult = (Dictionary<string, string>)e.Result;
            bool isCompleted = Convert.ToBoolean(asyncResult["IsCompleted"]);
            string fileId = asyncResult["FileId"];

            if (isCompleted || _cancelList.Contains(fileId))
            {
                List<ProgressInfo> progressList = JsonConvert.DeserializeObject<List<ProgressInfo>>(
                    File.ReadAllText(GlobalHelper.ProgressList)).Select(c => (ProgressInfo)c).ToList();

                var fileList = progressList.Where(o => o.FileId == fileId);
                List<int> fileIndex = new List<int>();
                foreach (var file in fileList)
                {
                    fileIndex.Add(progressList.IndexOf(file));
                }
                foreach (var index in fileIndex)
                {
                    progressList.RemoveAt(index);
                }

                string jsonList = JsonConvert.SerializeObject(progressList, Formatting.Indented);
                File.WriteAllText(GlobalHelper.ProgressList, jsonList, Encoding.UTF8);

                if (_cancelList.Contains(fileId))
                {
                    ApiHelper api = new ApiHelper();
                    api.DeleteFile(asyncResult["RemoteFilePath"]);
                    _cancelList.Remove(fileId);

                    // Remove cancel file from upload list
                    _dataUploadFiles.Remove(
                        _dataUploadFiles.Where(file => file.FileId == fileId).First()
                    );
                }
            }
        }
Example #8
0
        /// <summary>
        /// Query:取得目錄內容
        /// </summary>
        /// <param name="level">目錄階層</param>
        private void GetCatalog(int level)
        {
            lvwClassify.ItemsSource = null;
            lvwClassify.Items.Clear();

            // display mode switch btn
            if (level == 6)
            {
                btnListView.Visibility = Visibility.Visible;
                btnTileView.Visibility = Visibility.Visible;
            }
            else
            {
                btnListView.Visibility = Visibility.Hidden;
                btnTileView.Visibility = Visibility.Hidden;
            }

            // 取得各階層資料
            dynamic classify = null;

            switch (level)
            {
                case 1:
                    classify = GetLv1Catalog();
                    break;
                case 2:
                    classify = GetLv2Catalog();
                    break;
                case 3:
                    classify = GetLv3Catalog();
                    break;
                case 4:
                    classify = GetLv4Catalog();
                    break;
                case 5:
                    classify = GetFileCatalog();
                    break;
                case 6:
                    classify = GetFileList();
                    break;
            }

            ApiHelper api = new ApiHelper();
            List<string> remoteFolderFullPathList = api.Dir(_ftpPath).ToList();
            Dictionary<string, string> remoteFileList = new Dictionary<string, string>();
            foreach (var item in remoteFolderFullPathList)
            {
                remoteFileList.Add(item.Substring(item.LastIndexOf('/') + 1), item);
            }

            System.Collections.ObjectModel.ObservableCollection<FileInfo> fileCollection =
                new System.Collections.ObjectModel.ObservableCollection<FileInfo>();

            foreach (var classifyItem in classify)
            {
                if (remoteFileList.ContainsKey(classifyItem.Name))
                {
                    Dictionary<string, string> dicInfo = new Dictionary<string, string>();
                    dicInfo.Add("Id", classifyItem.Id.ToString());
                    dicInfo.Add("Name", classifyItem.Name);
                    dicInfo.Add("NickName", classifyItem.NickName);

                    if (_isTileView || level < 6)
                    {
                        bool isImageFile = false;

                        lvwClassify.View = lvwClassify.FindResource("TileView") as ViewBase;

                        BitmapImage bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;
                        if (level < 6)
                        {
                            bitmap.UriSource = new Uri(@"pack://application:,,,/WFTP;component/Icons/folder.ico");
                        }
                        else
                        {
                            ExtensionHelper helper = new ExtensionHelper();

                            string iconPath = helper.GetIconPath(
                                System.IO.Path.GetExtension(classifyItem.NickName));

                            if (iconPath != "img.ico")
                            {
                                bitmap.UriSource = new Uri(iconPath);
                            }
                            else
                            {
                                isImageFile = true;
                                bitmap.UriSource = new Uri(String.Format(GlobalHelper.ApiThumb, remoteFileList[classifyItem.Name]));
                            }
                        }
                        bitmap.EndInit();

                        Image img = new Image();
                        if (!isImageFile)
                        {
                            img.Width = 60;
                            img.Height = 60;
                        }
                        else
                        {
                            img.Width = 120;
                            img.Height = 120;
                        }
                        img.Source = bitmap;

                        Tile tile = new Tile();
                        tile.FontFamily = new FontFamily("Microsoft JhengHei");
                        tile.Width = 120;
                        tile.Height = 120;
                        tile.Margin = new Thickness(5);
                        tile.Content = img;

                        if (level < 6)
                        {
                            if (level == 4)
                            {
                                tile.Count = classifyItem.Counts.ToString();
                            }
                            else
                            {
                                tile.Count = Convert.ToString(api.GetCount(_ftpPath + dicInfo["Name"]));
                            }
                        }
                        else
                        {
                            tile.Count = "";
                        }

                        tile.Tag = dicInfo;
                        ToolTip tip = new ToolTip();
                        tip.Content = dicInfo["NickName"];
                        tile.ToolTip = tip;
                        tile.Click += new RoutedEventHandler(tile_Click);
                        tile.MouseDoubleClick += new MouseButtonEventHandler(tile_MouseDoubleClick);

                        if (tile.Count == "0")
                        {
                            tile.Background = new SolidColorBrush(Color.FromRgb(255, 93, 93));
                        }
                        if (isImageFile)
                        {
                            tile.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
                        }
                        else
                        {
                            tile.Title = dicInfo["NickName"].Length > 12 ? String.Format("{0}…", dicInfo["NickName"].Substring(0, 11)) : dicInfo["NickName"];
                        }

                        lvwClassify.Items.Add(tile);
                    }
                    else
                    {
                        lvwClassify.View = lvwClassify.FindResource("ListView") as ViewBase;

                        fileCollection.Add(new FileInfo
                        {
                            FileName = classifyItem.Name,
                            FilePath = remoteFileList[classifyItem.Name],
                            FileId = classifyItem.Id
                        });
                    }
                }
            }
            if (!_isTileView && level == 6)
            {
                lvwClassify.ItemsSource = fileCollection;
            }
        }
Example #9
0
        public void UpdateProgressList(string type, string remoteFilePath, string localFilePath, string fileHash="")
        {
            // Create fileId
            string fileId = String.Format("{0}_{1}",
                type, Guid.NewGuid().ToString().Replace("-", String.Empty));

            // Get remote file size
            ApiHelper api = new ApiHelper();
            long fileSize = 0;
            if (type.Equals("Download"))
            {
                fileSize = api.GetFileSize(remoteFilePath);
            }
            else
            {
                fileSize = new FileInfo(localFilePath).Length;
            }

            // Prepare CFile Object
            CFile dbFile = new CFile();
            dbFile.FileHash = fileHash;
            dbFile.OriginFileName = remoteFilePath.Substring(remoteFilePath.LastIndexOf('/') + 1).Replace(GlobalHelper.TempUploadFileExt,"");

            // Read progress list
            List<ProgressInfo> progressList = JsonConvert.DeserializeObject<List<ProgressInfo>>(
                File.ReadAllText(GlobalHelper.ProgressList)).Select(c => (ProgressInfo)c).ToList();

            // Check file is duplicated
            if (type.Equals("Download"))
            {
                if (File.Exists(localFilePath) || File.Exists(localFilePath + GlobalHelper.TempDownloadFileExt))
                {
                    int i = 1;
                    string filePathWithoutExt = String.Format(@"{0}\{1}",
                        System.IO.Path.GetDirectoryName(localFilePath),
                        System.IO.Path.GetFileNameWithoutExtension(localFilePath));
                    string filePathExt = System.IO.Path.GetExtension(localFilePath);

                    while (true)
                    {
                        localFilePath = String.Format("{0} ({1}){2}",
                            filePathWithoutExt,
                            i,
                            filePathExt);
                        if (File.Exists(localFilePath) || File.Exists(localFilePath + GlobalHelper.TempDownloadFileExt))
                        {
                            i++;
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    localFilePath += GlobalHelper.TempDownloadFileExt;
                }
            }
            else
            {
                string[] splitPath = remoteFilePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                // 命名規則:公司名稱_產線編號_檔案分類編號_時間戳記.副檔名
                WFTPDbContext db = new WFTPDbContext();
                var info =
                    (from classify in db.Lv1Classifications
                    from customer in db.Lv2Customers
                    from branch in db.Lv3CustomerBranches
                    from line in db.Lv4Lines
                    from category in db.Lv5FileCategorys
                    where classify.ClassName == splitPath[0] &&
                          customer.CompanyName == splitPath[1] && customer.ClassifyId == classify.ClassifyId &&
                          branch.BranchName == splitPath[2] && branch.CompanyId == customer.CompanyId &&
                          line.LineName == splitPath[3] && line.BranchId == branch.BranchId &&
                          category.ClassName == splitPath[4]
                    select new
                    {
                        CompanyName = customer.CompanyName,
                        LineId = line.LineId,
                        CategoryId = category.FileCategoryId
                    }).First();

                remoteFilePath = String.Format("{0}/{1}_{2}_{3}_{4}{5}{6}",
                    remoteFilePath.Substring(0, remoteFilePath.LastIndexOf('/')),
                    info.CompanyName,
                    info.LineId.ToString(),
                    info.CategoryId.ToString(),
                    System.DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                    System.IO.Path.GetExtension(remoteFilePath),
                    GlobalHelper.TempUploadFileExt);

                // Fill complete CFile value
                dbFile.FileCategoryId = info.CategoryId;
                dbFile.FileName = remoteFilePath.Substring(remoteFilePath.LastIndexOf('/') + 1).Replace(GlobalHelper.TempUploadFileExt, "");
                dbFile.LineId = info.LineId;
                dbFile.Path = remoteFilePath.Replace(GlobalHelper.TempUploadFileExt, "");

            }

            // Create new progress info
            ProgressInfo progressInfo = new ProgressInfo()
            {
                Type = type,
                RemoteFilePath = remoteFilePath,
                LocalFilePath = localFilePath,
                FileSize = fileSize,
                FileId = fileId
            };

            progressList.Add(progressInfo);

            // Serialize progress list to json format
            string jsonList = JsonConvert.SerializeObject(progressList, Formatting.Indented);

            // Overwrite progress list
            File.WriteAllText(GlobalHelper.ProgressList, jsonList, Encoding.UTF8);

            if (type.Equals("Download"))
            {
                // Add file to download list
                Switcher.progress._dataDownloadFiles.Add(new FileProgressItem
                {
                    Name = System.IO.Path.GetFileName(localFilePath).Replace(GlobalHelper.TempDownloadFileExt, String.Empty),
                    Progress = 0,
                    FileId = fileId
                });

                // Download file from FTP server
                Dictionary<string, string> fileInfo = new Dictionary<string, string>();
                fileInfo.Add("FileId", fileId);
                fileInfo.Add("RemoteFilePath", remoteFilePath);
                fileInfo.Add("LocalFilePath", System.IO.Path.GetDirectoryName(localFilePath));
                fileInfo.Add("LocalFileName", System.IO.Path.GetFileName(localFilePath));
                fileInfo.Add("RemoteFileSize", Convert.ToString(fileSize));

                StartDownload(fileInfo);
            }
            else
            {
                // Add file to upload list
                Switcher.progress._dataUploadFiles.Add(new FileProgressItem
                {
                    Name = System.IO.Path.GetFileName(localFilePath).Replace(GlobalHelper.TempUploadFileExt, String.Empty),
                    Progress = 0,
                    FileId = fileId
                });

                // Upload file to FTP server
                Dictionary<string, string> fileInfo = new Dictionary<string, string>();
                fileInfo.Add("FileId", fileId);
                fileInfo.Add("RemoteFilePath", remoteFilePath);
                fileInfo.Add("LocalFilePath", localFilePath);
                //fileInfo.Add("LocalFileName", System.IO.Path.GetFileName(localFilePath));
                fileInfo.Add("LocalFileSize", Convert.ToString(fileSize));
                fileInfo.Add("ModelCreateUser", dbFile.CreateUser);
                fileInfo.Add("ModelFileCategoryId", dbFile.FileCategoryId.ToString());
                fileInfo.Add("ModelFileHash", dbFile.FileHash);
                fileInfo.Add("ModelFileName", dbFile.FileName);
                fileInfo.Add("ModelLastEditUser", dbFile.LastEditUser);
                fileInfo.Add("ModelLineId", dbFile.LineId.ToString());
                fileInfo.Add("ModelOriginFileName", dbFile.OriginFileName);
                fileInfo.Add("ModelPath", dbFile.Path);

                StartUpload(fileInfo);
            }
        }
Example #10
0
        public void ReadProgressList()
        {
            // Read progress list
            List<ProgressInfo> progressList = JsonConvert.DeserializeObject<List<ProgressInfo>>(
                File.ReadAllText(GlobalHelper.ProgressList)).Select(c => (ProgressInfo)c).ToList();

            List<ProgressInfo> tmpProgressList = new List<ProgressInfo>();
            tmpProgressList.AddRange(progressList);

            if (progressList.Count > 0)
            {
                ApiHelper api = new ApiHelper();
                foreach (ProgressInfo info in progressList)
                {
                    // 如果本地端未完成檔案存在才顯示於進度清單中,否則就將該筆進度刪除
                    if (File.Exists(info.LocalFilePath) && api.CheckPath(info.RemoteFilePath))
                    {
                        if (info.Type.Equals("Download"))
                        {
                            long localFileSize = new FileInfo(info.LocalFilePath).Length;
                            int percentage = Convert.ToInt32(((double)localFileSize / (double)info.FileSize) * 100);
                            _dataDownloadFiles.Add(new FileProgressItem
                            {
                                Name = System.IO.Path.GetFileName(info.LocalFilePath).Replace(GlobalHelper.TempDownloadFileExt, String.Empty),
                                Progress = percentage,
                                FileId = info.FileId
                            });
                        }
                        else
                        {
                            long remoteFileSize = api.GetFileSize(info.RemoteFilePath);
                            int percentage = Convert.ToInt32(((double)remoteFileSize / (double)info.FileSize) * 100);
                            _dataUploadFiles.Add(new FileProgressItem
                            {
                                Name = System.IO.Path.GetFileName(info.LocalFilePath).Replace(GlobalHelper.TempUploadFileExt, String.Empty),
                                Progress = percentage,
                                FileId = info.FileId
                            });
                        }
                    }
                    else
                    {
                        int indexOfFile = tmpProgressList.IndexOf(info);
                        tmpProgressList.RemoveAt(indexOfFile);
                    }
                }

                // Serialize progress list to json format
                string jsonList = JsonConvert.SerializeObject(tmpProgressList, Formatting.Indented);

                // Overwrite progress list
                File.WriteAllText(GlobalHelper.ProgressList, jsonList, Encoding.UTF8);
            }
        }
Example #11
0
        public void bgworkerStartUpload_DoWorkHandler(object sender, DoWorkEventArgs e)
        {
            ApiHelper api = new ApiHelper();
            BackgroundWorker bgworkerStartUpload = sender as BackgroundWorker;
            Dictionary<string, string> fileInfo = (Dictionary<string, string>)e.Argument;
            Dictionary<string, string> asyncResult = new Dictionary<string, string>();
            asyncResult.Add("IsCompleted", "false");
            asyncResult.Add("FileId", fileInfo["FileId"]);
            asyncResult.Add("RemoteFilePath", fileInfo["RemoteFilePath"]);

            // Asynchronous FTP Upload
            Chilkat.Ftp2 ftp = new Chilkat.Ftp2();

            bool success;

            success = ftp.UnlockComponent(GlobalHelper.ComponentCode);
            if (success != true)
            {
                MessageBox.Show(ftp.LastErrorText);
                return;
            }

            ftp.Hostname = GlobalHelper.FtpHost;
            ftp.Username = GlobalHelper.FtpUsername;
            ftp.Password = GlobalHelper.FtpPasswrod;
            // Resume upload
            ftp.RestartNext = true;

            // Connect and login to the FTP server.
            success = ftp.Connect();
            if (success != true)
            {
                MessageBox.Show(ftp.LastErrorText);
                return;
            }

            string localFilename = fileInfo["LocalFilePath"];
            string remoteFilename = fileInfo["RemoteFilePath"];
            long localFilesize = Convert.ToInt64(fileInfo["LocalFileSize"]);

            success = ftp.AsyncPutFileStart(localFilename, remoteFilename);
            if (success != true)
            {
                MessageBox.Show(ftp.LastErrorText);
                return;
            }

            while (ftp.AsyncFinished != true)
            {
                if (_cancelList.Contains(fileInfo["FileId"]))
                {
                    ftp.AsyncAbort();
                    break;
                }

                if (api.CheckPath(remoteFilename))
                {
                    long remoteFilesize = api.GetFileSize(remoteFilename);
                    double percentage = ((double)remoteFilesize / (double)localFilesize) * 100;
                    bgworkerStartUpload.ReportProgress((int)percentage);
                }

                // Sleep 0.5 second.
                ftp.SleepMs(500);
            }

            bool uploadSuccess = false;
            // Did the upload succeed?
            if (ftp.AsyncSuccess == true)
            {
                uploadSuccess = true;
                bgworkerStartUpload.ReportProgress(100);
                asyncResult["IsCompleted"] = "true";
            }
            else
            {

            }

            ftp.Disconnect();
            ftp.Dispose();

            // Change Local file name back to original
            string originalFilePath = fileInfo["LocalFilePath"].Replace(GlobalHelper.TempUploadFileExt, String.Empty);
            if (uploadSuccess || _cancelList.Contains(fileInfo["FileId"]))
            {
                File.Move(fileInfo["LocalFilePath"], originalFilePath);
            }

            if (uploadSuccess)
            {
                // Move local file to Recycle bin
                FileSystem.DeleteFile(originalFilePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                // Remove temp extension from remote file
                string newName = remoteFilename.Replace(GlobalHelper.TempUploadFileExt, String.Empty);
                api.Rename(remoteFilename, newName);
                // Insert record into db
                int categoryId = Convert.ToInt32(fileInfo["ModelFileCategoryId"]);
                int lineId = Convert.ToInt32(fileInfo["ModelLineId"]);
                CFile.InsertOrUpdate(null, categoryId, lineId, fileInfo["ModelOriginFileName"],
                                           fileInfo["ModelFileName"], false, GlobalHelper.LoginUserID, fileInfo["ModelFileHash"]);
            }

            e.Result = asyncResult;
        }
Example #12
0
        /// <summary>
        /// 取得目錄內容
        /// </summary>
        /// <param name="level">目錄階層</param>
        /// <param name="id">關聯 ID</param>
        private void GetCatalog(int level)
        {
            dynamic classify = null;
            switch (level)
            {
                case 1:
                    classify = GetLv1Catalog();
                    break;
                case 2:
                    classify = GetLv2Catalog();
                    break;
                case 3:
                    classify = GetLv3Catalog();
                    break;
                case 4:
                    classify = GetLv4Catalog();
                    break;
                case 5:
                    classify = GetFileCatalog();
                    break;
            }

            ApiHelper api = new ApiHelper();
            List<string> remoteFolderFullPathList = api.Dir(_ftpPath).ToList();
            Dictionary<string, string> remoteFileList = new Dictionary<string, string>();
            foreach (var item in remoteFolderFullPathList)
            {
                remoteFileList.Add(item.Substring(item.LastIndexOf('/') + 1), item);
            }
        }
Example #13
0
        /// <summary>
        /// 處理取得路徑
        /// </summary>
        private void GetPath()
        {
            if (String.IsNullOrEmpty(txtName.Text)|| String.IsNullOrEmpty(txtNickName.Text))
            {
                lbMessage.Content = "欄位不得為空白";
                return;
            }

            if (!Regex.IsMatch(txtName.Text.Trim(), PATTERN_SYSTEMNAME))
            {
                lbMessage.Content = "系統名稱格式錯誤";
                return;
            }
            else
            {
                lbMessage.Content = "";
            }

            if (!Regex.IsMatch(txtNickName.Text.Trim(), PATTERN_NICKNAME))
            {
                lbMessage.Content = "瀏覽名稱格式錯誤";
                return;
            }
            else
            {
                lbMessage.Content = "";
            }
            this.SystemName = txtName.Text.Trim();
            this.NickName = txtNickName.Text.Trim();
            string path = this.PrePath + "/" + txtName.Text.Trim();
            // 判斷如果有這個名稱則提醒
            ApiHelper api = new ApiHelper();
            if (!api.CheckPath(path))
            {
                txtName.Foreground = Brushes.Black;
                lbMessage.Content = "";
                this.IsDone = true;
                this.Close();
            }
            else
            {
                txtName.Foreground = Brushes.Red;
                lbMessage.Content = "此系統名稱已存在,請換別的名稱";
            }
        }