public static void WriteFTPFiles(string serverAddress, string serverUsername, string serverPassword, string outputFileName, int requestTimeout) { try { var request = (FtpWebRequest)WebRequest.Create(serverAddress); request.Timeout = requestTimeout; request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential(serverUsername, serverPassword); using (var response = (FtpWebResponse)request.GetResponse()) using (var responseStream = response.GetResponseStream()) using (var reader = new StreamReader(responseStream)) { foreach (var item in reader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { var itemUrl = $"{serverAddress}{item}"; var itemUri = new Uri(itemUrl); if (!ExistingFileURLs.Contains(itemUri.AbsoluteUri.Replace("#", "%23"))) // Checks if this file isn't a duplicate { if (IsFile(itemUrl)) // Check if item is file by requesting file size, otherwise returning false if an error occurs { // Create a new FTP File object to write to output var newFile = new FtpFile { Name = Path.GetFileName(new Uri(itemUrl).LocalPath), Size = FileExtensions.FtpFileSize(itemUrl, serverUsername, serverPassword), Modified = FileExtensions.FtpFileTimestamp(itemUrl, serverUsername, serverPassword), URL = itemUri.AbsoluteUri.Replace("#", "%23") }; using (StreamWriter sw = File.AppendText(outputFileName)) { sw.WriteLine(JsonConvert.SerializeObject(newFile)); ExistingFileURLs.Add(newFile.URL); LogFtpMessage("File Added : " + newFile.Name + " [" + newFile.URL + "]"); ResultsTotalSize = ResultsTotalSize + newFile.Size; ResultsTotalSize++; } } else { if (!item.StartsWith("#") || !item.EndsWith("#")) { WriteFTPFiles($"{itemUrl}/", serverUsername, serverPassword, outputFileName, requestTimeout); } } } } } } catch (StackOverflowException ex) { LogFtpMessage($"Overflow exception occurred (Sometimes happens with large items) - {ex.Message}"); // Can't seem to overcome this issue, perhaps invoke StreamReader? } catch (Exception ex) { LogFtpMessage($"Unable to get directory listing [{serverAddress}] - {ex.Message}"); } }
private static async Task <bool> _monitorArchive(FtpFile f, FtpPath p, CancellationToken ct) { var sw = new Stopwatch(); sw.Start(); await logger.Log($"Обрабатываю архив {f.Name} по пути {p.Path}"); var sw1 = new Stopwatch(); sw1.Start(); var allEntriesInArchive = FtpClient.Get(logger).GetArchiveEntries(p.Path + f.Name, p.Login, p.Password); await logger.Log($"Архив получен {sw1.Elapsed}"); sw1.Restart(); new ZipHelper().ParseArchve(f, allEntriesInArchive); await logger.Log($"Дерево файлов построено {sw1.Elapsed}"); sw1.Restart(); var data = JsonConvert.SerializeObject(f); await logger.Log($"Дерево файлов сериализовано {sw1.Elapsed}, отправляю на сервер"); sw1.Restart(); var res = await apiDataProvider.SendFileTreeAsync(new StringContent(data, Encoding.UTF8, MediaTypeNames.Application.Json), p.Id, ct); await logger.Log($"Дерево файлов отправлено на сервер {sw1.Elapsed}"); sw1.Stop(); await logger.Log($"Архив {f.Name} обработан ОБЩЕЕ ВРЕМЯ АРХИВА: {sw.Elapsed}"); sw.Stop(); return(true); }
private void UploadAsync() { var ftpClient = this.GetFtpClient(); ThreadPool.QueueUserWorkItem(callBack => { var value = "hallo ich bin's ... wer bist'n du??"; var bytes = Encoding.UTF8.GetBytes(value); var ftpFile = new FtpFile("/test12/hello.txt"); using (ftpClient) { bool success; var memoryStream = new MemoryStream(bytes); using (memoryStream) { success = ftpClient.Upload(memoryStream, ftpFile); } this.Dispatcher.BeginInvoke(() => { var messageBoxText = string.Format("success: {0}", success); MessageBox.Show(messageBoxText); }); } }); }
public void Upload_Throws_Exception() { var archiveService = Substitute.For <IArchiveService>(); archiveService .Create(Arg.Is("TestName"), Arg.Any <Action <ArchiveCreated> >()) .Returns(new BeginArchive("TestName", (m, o) => { })); var ftpClientFactory = Substitute.For <IFtpClientFactory>(); var ftpClient = Substitute.For <IFtpClient>(); ftpClientFactory.Create(Arg.Is("ftp://localhost")) .Returns(ftpClient); ftpClient.Upload(Arg.Any <string>(), Arg.Any <Stream>(), Arg.Is(false)) .Returns("done"); using (IApplicationContext context = ApplicationContext.Create(application => application .ConfigureForUnitTest() .Services(services => services .Advanced(advanced => advanced .Register(kernel => archiveService) .Register(kernel => ftpClientFactory))) .UseGlobase(globase => globase .FtpConnectionString(ConnectionString.FromText("ftp://localhost")) .EnableArchiving(options => options.Named("TestName").ExpiresAfterDays(1))))) { var file = FtpFile.Csv("records", "content"); var uploader = context.Resolve <IFtpUploader>(); string[] result = uploader.Upload(new[] { file }); CollectionAssert.AreEqual(new[] { "done" }, result); } }
public FileInfo(FtpFile file) { this.name = file.name; this.fullname = file.fullname; this.size = file.size; this.lastWriteTime = file.lastWriteTime; this.isDirectory = file.isDirectory; }
/// <summary>刪除指定的檔案</summary> /// <param name="ftpFile">欲刪除的檔案資訊</param> public void DeleteFile(FtpFile ftpFile) { /* 開啟串流並直接移除 */ using (var rsp = GetResponse(ftpFile.Uri, WebRequestMethods.Ftp.DeleteFile)) { /* 不需要做啥 */ rsp.Close(); } }
public void ParseArchve(FtpFile root, IEnumerable <ZipArchiveEntry> entries) { var files = entries.ToDictionary(e => e.FullName.Split(@"\")); foreach (var pair in files) { a(root, pair.Key, pair.Value, 0); } }
public override string Process(Edi_Customer c, string s, string _EdiBase) { string _Log = ""; if (c.Mode == true) { FtpFile.RemoveFile(c.RSSBus_PortId + "/Receive", _EdiBase, s); } return(_Log); }
private void SetReadOnly(FtpFile folder, String userName) { folder.UserRead = true; folder.UserWrite = false; folder.WorldRead = false; folder.WorldWrite = false; folder.GroupRead = false; folder.GroupWrite = false; folder.OwningUser = userName; }
public FtpPath(FtpPath currentPath, FtpFile file) { File = file; if (currentPath.Path.EndsWith("/")) { Path = currentPath + file.Name; } else { Path = currentPath.Path + "/" + file.Name; } }
/// <summary> /// test edi job business /// 1. get edi customer table prd/test /// 2. download edi message file © to ./Edi /// 3. parser edi message to set sap order /// 4. create order /// 4.1. insert to edi order table /// 4.2. success/fail status /// 5. success:delete source file /// 6. email to key user /// 7. response 855 message /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnTest_Click(object sender, EventArgs e) { string _Log = ""; string _CustomerId = ""; string _ParserFile = ""; try { btnLogin.PerformClick(); btnGet.PerformClick(); string _EdiBase = ConfigurationManager.AppSettings["EdiBase"]; foreach (Edi_Customer c in _edi_Customerlist) { _CustomerId = c.SapCustomerId; _Log = "\r\n" + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + " CreateOrder: Customer Id:" + _CustomerId; if (c.Mode == _EdiMode)//PRD { List <string> _FileList = FtpFile.GetList(c.RSSBus_PortId + "/Receive", _EdiBase); if (FtpFile.ListError.Count == 0) { foreach (string s in _FileList) { _Log = "\r\n" + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + " CreateOrder: Customer Id:" + _CustomerId; _ParserFile = FtpFile.Download("Edi", c.RSSBus_PortId + "/Receive", _EdiBase, s); if (FtpFile.ListError.Count == 0) { readEdi(_ParserFile, c, s); } else { _Log = _Log + " File :" + _ParserFile + "\r\n" + FtpFile.ListError[0]; logger.Error(_Log); txtLog.Text += _Log; } } } else { _Log = _Log + "\r\n" + FtpFile.ListError[0]; logger.Error(_Log); txtLog.Text += _Log; } } } } catch (Exception ex) { _Log = "\r\n" + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + " CreateOrder: Customer Id:" + _CustomerId + " File :" + _ParserFile + "\r\n" + ex.Message; logger.Error(_Log); txtLog.Text += _Log; } }
protected override int AscSorter(object x, object y) { int result = 0; FtpFile filex = x as FtpFile; FtpFile filey = y as FtpFile; result = filex.Type - filey.Type; if (result == 0) { result = filex.Modified.CompareTo(filey.Modified); } return(result); }
public async Task Should_not_blow_up_if_file_does_not_exist() { string fileName = $"{Guid.NewGuid()}.txt"; using (var localFtpClient = ResourceHelpers.GetLocalFtpClient(Logger)) { var sut = new FtpFile(localFtpClient, fileName); sut.Exists.Should().BeFalse(); await sut.DeleteAsync(); } }
public async Task Should_give_stream() { string fileName = $"{Guid.NewGuid()}.txt"; await ResourceHelpers.CreateFileWithContentAsync(fileName, FileContent, Logger); var sut = new FtpFile(ResourceHelpers.GetLocalFtpClient(Logger), fileName); using (var stream = await sut.OpenReadAsync()) { stream.Should().NotBe(null); } await sut.DeleteAsync(); }
/// <summary> /// /// </summary> /// <param name="ftpFile">需要上传的文件</param> /// <param name="targetDir">目标路径</param> public void UploadFile(FtpFile ftpFile, string targetDir) { if (string.IsNullOrEmpty(targetDir)) { return; } //string target = string.Empty; //target = Guid.NewGuid().ToString(); //使用临时文件名 //string url = "FTP://" + hName + "/" + targetDir + "/" + target; string url = "ftp://" + ip + "/" + targetDir + "/" + ftpFile.Name; FtpWebRequest ftp = GetRequest(url); }
private void a(FtpFile parent, string[] nameParts, ZipArchiveEntry file, int i) { if (i >= nameParts.Length || string.IsNullOrWhiteSpace(nameParts[i])) { return; } if (i == nameParts.Length - 1) { parent.AddChild(nameParts[i], file.Length, file.LastWriteTime); } else { a(parent.AddChild(nameParts[i]), nameParts, file, i + 1); } }
public async Task Should_return_contents_of_file() { string fileName = $"{Guid.NewGuid()}.txt"; await ResourceHelpers.CreateFileWithContentAsync(fileName, FileContent, Logger); using (var sut = new FtpFile(ResourceHelpers.GetLocalFtpClient(Logger), fileName)) { var bytes = await sut.ReadToEndAsync(); string contents = Encoding.UTF8.GetString(bytes); contents.Should().Be(FileContent); await sut.DeleteAsync(); } }
/// <summary> /// Show details/info for a WebFile /// </summary> /// <param name="File">WebFile object</param> /// <param name="parentDataGrid">Parent data grid to scroll</param> /// <param name="createNewInstance">Whether to create a new instance</param> public void ShowFileDetails(FtpFile File, DataGridView parentDataGrid, bool createNewInstance = true) { Program.Log.Info("Loading file details : " + File.URL); if (createNewInstance) { FormFileDetails = new FileDetailsWindow(); } FormFileDetails.FileExtension = Path.GetExtension(File.URL).Replace(".", "").ToUpper(); FormFileDetails.ParentDataGrid = parentDataGrid; FormFileDetails.CurrentFile = File; FormFileDetails.LabelFileName.Text = File.Name; FormFileDetails.LabelValueName.Text = File.Name; FormFileDetails.LabelValueSize.Text = StringExtensions.BytesToPrefix(File.Size); FormFileDetails.LabelValueRefferer.Text = new Uri(File.URL).Host; // Builds parts of the URL into a better presented string, simply replaces '/' with '>' and no filename var url = new Uri(File.URL); var directories = new StringBuilder(); directories.Append(new Uri(File.URL).Host); foreach (var path in url.LocalPath.Split('/', '\\')) { if (!Path.HasExtension(path)) { directories.Append(path + "> "); } } FormFileDetails.LabelValueDirectory.Text = directories.ToString(); FormFileDetails.LabelValueExtension.Text = Path.GetExtension(File.URL).Replace(".", "").ToUpper(); FormFileDetails.LabelValueAge.Text = StringExtensions.TimeSpanAge(File.DateModified); FormFileDetails.InfoFileURL.Text = Uri.UnescapeDataString(File.URL); if (!createNewInstance) { FormFileDetails.CheckFileEvents(); } else { FormFileDetails.ShowDialog(this); } FormFileDetails.Text = File.Name + " - File Details"; Program.Log.Info("Completed file details"); }
public async Task Should_write_content_to_file_with_base_path() { var sut = new FtpFile(ResourceHelpers.GetLocalFtpClient(Logger, $"/{Guid.NewGuid()}/abc/123"), $"{Guid.NewGuid()}.txt", "test1"); using (var stream = await sut.OpenWriteAsync()) using (var writer = new StreamWriter(stream)) { writer.Write(WRITE_CONTENT); } string fileContents = Encoding.UTF8.GetString(await sut.ReadToEndAsync()); fileContents.Should().Be(WRITE_CONTENT); await sut.DeleteAsync(); }
/// <summary>下載檔案至指定的本機資料夾內</summary> /// <param name="file">欲下載的檔案資訊</param> /// <param name="localFold">欲存放的本機資料夾,如 @"D:\Recipe"</param> public void Download(FtpFile file, string localFold) { /* 檢查本機存放的目錄位置是否存在,不存在則建立之 */ if (!Directory.Exists(localFold)) { Directory.CreateDirectory(localFold); } /* 組裝本地檔案路徑,將名稱給加到後方 */ var path = localFold.EndsWith("\\") ? $"{localFold}{file.Name}" : $@"{localFold}\{file.Name}"; /* 建立串流並直接寫入檔案 */ using (var rsp = GetResponse(file.Uri, WebRequestMethods.Ftp.DownloadFile)) { using (var sr = rsp.GetResponseStream()) { /* 開啟本地檔案的串流 */ using (var fs = new FileStream(path, FileMode.Create)) { /* 重設旗標 */ mEvtArg.File = file; mEvtArg.CurrentSize = 0; mEvtArg.FullSize = file.FileSize; /* 因為 while 條件,先讓他跑第一次 */ while (mEvtArg.CurrentSize < mEvtArg.FullSize) { mCnt = sr.Read(mBuf.Value, 0, BUFFER_LENGTH); if (mCnt > 0) { fs.Write(mBuf.Value, 0, mCnt); /* 累計當前數量 */ mEvtArg.CurrentSize += mCnt; } /* 發報更新 */ RaiseUpd(); } } } } /* 取得該檔案的原始時間 */ using (var rsp = GetResponse(file.Uri, WebRequestMethods.Ftp.GetDateTimestamp)) { /* 更改本地檔案的時間 */ var time = rsp.LastModified; var fi = new FileInfo(path) { CreationTime = time, LastAccessTime = time, LastWriteTime = time }; } }
public async Task Should_give_md5_hash_of_file() { string fileName = $"{Guid.NewGuid()}.txt"; await ResourceHelpers.CreateFileWithContentAsync(fileName, FileContent, Logger); using (var localFtpClient = ResourceHelpers.GetLocalFtpClient(Logger)) { localFtpClient.Logger = Logger; var sut = new FtpFile(localFtpClient, fileName); var hash = await sut.GetHashAsync(); hash.Should().NotBeEmpty(); hash.Should().Be("081cb72eaaacae3df4502708ff956d23"); await sut.DeleteAsync(); } }
public async Task Should_delete_file_properly() { string fileName = $"{Guid.NewGuid()}.txt"; await ResourceHelpers.CreateFileWithContentAsync(fileName, "test", Logger); using (var localFtpClient = ResourceHelpers.GetLocalFtpClient(Logger)) { localFtpClient.Logger = Logger; var sut = new FtpFile(localFtpClient, fileName); sut.Exists.Should().BeTrue(); await sut.DeleteAsync(); sut.Exists.Should().BeFalse(); } }
public static async Task <FtpFile> CreateFileWithContentAsync(string filename, string content, ILogger logger) { using (var client = GetLocalFtpClient(logger)) { var ftpFile = new FtpFile(client, filename); using (var stream = await ftpFile.OpenWriteAsync()) { using (var writer = new StreamWriter(stream)) { writer.Write(content); } } await client.LogOutAsync(); return(ftpFile); } }
/// <summary> /// Get web file info from internal database, or creates a new object if it doesn't exist /// </summary> /// <param name="URL">Used to match with WebFile.URL to return class</param> /// <returns>WebFile object</returns> public static FtpFile FtpFile(string URL) { // Checks loaded files for a matching URL and returns the Web File object foreach (var file in MainForm.DbOpenFiles) { if (file.URL == URL) { return(file); } } // Create a new Web File object as this URL doesn't exist in the database there anymore var newWebFile = new FtpFile(Path.GetFileName(new Uri(URL).LocalPath), WebExtensions.FtpFileSize(URL), WebExtensions.FtpFileTimestamp(URL), new Uri(URL).AbsoluteUri); // Add the new Web File to this instance of application MainForm.DbOpenFiles.Add(newWebFile); // Return the new Web File return(newWebFile); }
private void DownloadAsync() { var ftpClient = this.GetFtpClient(); Task.Factory.StartNew(() => { using (ftpClient) { var foo = ftpClient.GetCurrentFtpDirectory(); long size; using (var memoryStream = new MemoryStream()) { { var ftpFile = new FtpFile("/pub/mozilla/nightly/README"); var success = ftpClient.Download(ftpFile, memoryStream); if (!success) { size = -1; } else { size = memoryStream.Length; } } { var ftpFile = new FtpFile("/pub/README"); var success = ftpClient.Download(ftpFile, memoryStream); } } this.Dispatcher.BeginInvoke(() => { var messageBoxText = string.Format("size: {0}", size); MessageBox.Show(messageBoxText); }); } }); }
public override string Process(Edi_Customer c, string s, string _EdiBase) { string _Log = ""; string _ParserFile = ""; string _OrderNumber = FormJob.creatOrder(edi.SapSalesOrder); if (_OrderNumber != "") { insertZSDT046(_OrderNumber); if (c.Mode == true) { FtpFile.RemoveFile(c.RSSBus_PortId + "/Receive", _EdiBase, s); } } else { _Log = _Log + " File :" + _ParserFile + "\r\n" + "Create order fail"; logger.Error(_Log); } return(_Log); }
public IEnumerable <FtpItem> GetDirectoryContents() { // Intitialize File Transfer this.LIST(); // Read Bytes from Stream, save them to disk var result = new StreamReader(Data.Stream).ReadToEnd(); foreach (string line in result.Split(new [] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.StartsWith("d")) { yield return(FtpDirectory.Parse(line)); } else { yield return(FtpFile.Parse(line)); } } // Wait for Confirmation on File Transfer. Stream will be closed by the Server! MessageHandler.WaitOne(); }
protected override int AscSorter(object x, object y) { int result = 0; FtpFile filex = x as FtpFile; FtpFile filey = y as FtpFile; string tmpx = filex.Size.Trim(); string tmpy = filey.Size.Trim(); result = filex.Type - filey.Type; if (result == 0) { if (string.IsNullOrEmpty(tmpx) || string.IsNullOrEmpty(tmpy)) { result = tmpx.CompareTo(tmpy); } else { result = filex.ByteSize.CompareTo(filey.ByteSize); } } tmpx = null; tmpy = null; return(result); }
public async Task Should_be_able_to_read_file_contents_from_stream() { string fileName = $"{Guid.NewGuid()}.txt"; await ResourceHelpers.CreateFileWithContentAsync(fileName, FileContent, Logger); using (var localFtpClient = ResourceHelpers.GetLocalFtpClient(Logger)) { localFtpClient.Logger = Logger; var sut = new FtpFile(localFtpClient, fileName); using (var stream = await sut.OpenReadAsync()) { using (var reader = new StreamReader(stream)) { string content = await reader.ReadToEndAsync(); content.Should().NotBeEmpty(); content.Should().StartWith(FileContent); } } await sut.DeleteAsync(); } }
private void btnStart_Click(object sender, EventArgs e) { btnStart.Enabled = false; try { Xceed.Ftp.Licenser.LicenseKey = "FTN42-K40Z3-DXCGS-PYGA"; data.Columns.Clear(); data.Rows.Clear(); data.Columns.Add("name", "Точка"); data.Columns.Add("rezult", "Результат"); data.Columns[0].Width = 200; data.Columns[1].Width = 350; cn = new SqlConnection(setting.Connection_string); cn.Open(); cmd = new SqlCommand("SELECT * FROM [place];", cn); DataTable tbl = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(tbl); pb.Minimum = 0; pb.Maximum = tbl.Rows.Count; pb.Value = 0; foreach (DataRow r in tbl.Rows) { try { using (FtpConnection connection = new FtpConnection( r["server"].ToString().Trim(), r["username"].ToString().Trim(), r["password"].ToString().Trim())) { connection.Timeout = 10; string tmp = Guid.NewGuid().ToString(); StreamWriter w = new StreamWriter(System.IO.Path.GetTempPath() + tmp); w.Write(tmp); w.Close(); connection.Encoding = Encoding.GetEncoding(1251); DiskFile source = new DiskFile(System.IO.Path.GetTempPath() + tmp); string ftp_to = r["path"].ToString().Trim(); if (ftp_to.Substring(0, 1) == "/") ftp_to = ftp_to.Substring(1); FtpFolder destination = new FtpFolder(connection, ftp_to); source.CopyTo(destination, true); Thread.Sleep(2000); FtpFile remote = new FtpFile(connection, ftp_to + tmp); remote.Delete(); } data.Rows.Add(new string[] { r["name"].ToString().Trim(), "ok" }); } catch (Exception ex) { data.Rows.Add(new string[] { r["name"].ToString().Trim(), "ошибка: " + ex.Message }); } finally { pb.Value++; Application.DoEvents(); } } } catch { } finally { btnStart.Enabled = true; MessageBox.Show("ok"); } }
/// <summary> /// Raises <see cref="FileAdded"/> event. /// </summary> /// <param name="file">A <see cref="FtpFile"/> file.</param> protected void OnFileAdded(FtpFile file) { if (FileAdded != null) FileAdded(this, new EventArgs<FtpFile>(file)); }
public ActionResult Index(WXSaleAfterMain main) { ObjectParameter ftpparameter = new ObjectParameter("PKID", typeof(string)); entity.SysGetObjectPKId(null, "FtpFile", ftpparameter); if (Request.Files.Count > 0 && !string.IsNullOrEmpty(Request.Files[0].FileName)) { Request.Files[0].SaveAs(Server.MapPath("~/App_Data/") + Request.Files[0].FileName); int lastindex = Request.Files[0].FileName.LastIndexOf("."); string postfix = Request.Files[0].FileName.Substring(lastindex); try { FTPHelper.FtpUploadBroken(Server.MapPath("~/App_Data/") + Request.Files[0].FileName, "MesSaleAfter", (string)ftpparameter.Value + postfix); main.Filename = (string)ftpparameter.Value + postfix; } catch (Exception ex) { ViewBag.Content = ex.Message; return(View("Done")); } } entity.WXSaleAfterMain.Add(main); entity.SaveChanges(); if (main.ServiceReason == "故障检查维修" || main.ServiceReason == "安装调试" || main.ServiceReason == "日常回访" || main.ServiceReason == "其他") { if (main.IsXJR == "否") { ObjectParameter parameter = new ObjectParameter("PKID", typeof(string)); entity.SysGetObjectPKId(null, "Ter_Customer_Com_Records", parameter); Ter_Customer_Com_Records tccr = new Ter_Customer_Com_Records(); tccr.Ter_Customer_Com_RecordsId = (string)parameter.Value; tccr.MOName = main.MoID; if (!string.IsNullOrEmpty(main.MoID)) { MO mo = entity.MO.Where(p => p.MOName == main.MoID).FirstOrDefault(); //tccr.MOName = mo.MOName; if (mo != null) { tccr.MachineNo = mo.SAP_CHARG; } } int serialNumber = (int)entity.Ter_Customer_Com_Records.Max(p => p.SerialNumber); tccr.SerialNumber = serialNumber + 1; tccr.ComplaintTime = DateTime.Now; tccr.ComplaintContent = main.ProblemDescription; tccr.CustomerAddress = main.CustomerAddress; tccr.CustomerContact = main.CustomerContact + "," + main.CustomerPhone; tccr.CustomerName = main.CustomerName; tccr.DefectType = main.ProblemType; tccr.CustomerId = main.ID.ToString(); tccr.ProblemCompletion = "进行中"; tccr.CreateDate = DateTime.Now; tccr.WorkflowStepId = "WFS10000033Z"; tccr.WorkflowStatus = "1"; if (!string.IsNullOrEmpty(main.Filename)) { FtpFile ftpfile = new FtpFile(); ftpfile.FtpFileId = (string)ftpparameter.Value; ftpfile.FtpFileName = main.Filename; ftpfile.FtpDirectory = ""; ftpfile.FtpFileSize = 0; ftpfile.PluginCommand = "TCCR"; ftpfile.UploadUser = main.UserName; ftpfile.UploadComputer = ""; ftpfile.CreateDate = DateTime.Now; ftpfile.PKId = (string)parameter.Value; entity.FtpFile.Add(ftpfile); tccr.ImageID = (string)ftpparameter.Value; } entity.Ter_Customer_Com_Records.Add(tccr); entity.SaveChanges(); } else { ObjectParameter parameter = new ObjectParameter("PKID", typeof(string)); entity.SysGetObjectPKId(null, "Q_issue_Rec_ForCustomer", parameter); Q_issue_Rec_ForCustomer qirf = new Q_issue_Rec_ForCustomer(); qirf.Q_issue_Rec_ForCustomerId = (string)parameter.Value; qirf.OrderName = main.MoID; if (!string.IsNullOrEmpty(main.MoID)) { MO mo = entity.MO.Where(p => p.MOName == main.MoID).FirstOrDefault(); ///qirf.OrderName = mo.MOName; if (mo != null) { qirf.MachineNo = mo.SAP_CHARG; } } qirf.CustomerId = "CUS10000027Y"; ProductRoot pr = entity.ProductRoot.Where(p => p.ProductName == main.ProductID).FirstOrDefault(); if (pr != null) { qirf.ProductID = pr.DefaultProductId; } qirf.FeedbackDate = DateTime.Now; qirf.IssueDesc = main.ProblemDescription; if (!string.IsNullOrEmpty(main.Filename)) { FtpFile ftpfile = new FtpFile(); ftpfile.FtpFileId = (string)ftpparameter.Value; ftpfile.FtpFileName = main.Filename; ftpfile.FtpDirectory = ""; ftpfile.FtpFileSize = 0; ftpfile.PluginCommand = "QIRF"; ftpfile.UploadUser = main.UserName; ftpfile.UploadComputer = ""; ftpfile.CreateDate = DateTime.Now; ftpfile.PKId = (string)parameter.Value; entity.FtpFile.Add(ftpfile); qirf.Image4ID = (string)ftpparameter.Value; } qirf.WorkflowStepId = "WFS10000033X"; qirf.WorkflowStatus = "1"; entity.Q_issue_Rec_ForCustomer.Add(qirf); entity.SaveChanges(); } } ViewBag.Content = "添加售后维护单成功!"; return(View("Done")); }
public FtpPath(string path, FtpFile file) { Path = path; this.File = file; }
/// <summary> /// Raises <see cref="FileDeleted"/> event. /// </summary> /// <param name="file">A <see cref="FtpFile"/> file.</param> protected void OnFileDeleted(FtpFile file) { if ((object)FileDeleted != null) FileDeleted(this, new EventArgs<FtpFile>(file)); }
public void UploadOrders() { try { Xceed.Ftp.Licenser.LicenseKey = "FTN42-K40Z3-DXCGS-PYGA"; //Xceed.FileSystem.Licenser.LicenseKey = ""; if (!UploadWork) { try { UploadWork = true; SqlConnection db_connection = new SqlConnection(prop.Connection_string); db_connection.Open(); file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выбираем заказы на экспорт"); file.Flush(); SqlCommand db_command = new SqlCommand("SELECT [number], [auto_export], [id_place] FROM [order] WHERE [auto_export] > 0;", db_connection); SqlDataAdapter db_adapter = new SqlDataAdapter(db_command); DataTable tbl = new DataTable(); db_adapter.Fill(tbl); foreach (DataRow rw in tbl.Rows) { try { file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Подготавливаем к выгрузке заказ " + rw["number"].ToString().Trim()); file.Flush(); PSA.Lib.Util.ExportOrder.autoExport((int)rw["auto_export"], rw["number"].ToString().Trim()); db_command = new SqlCommand("SELECT [server], [path], [username], [password] FROM [place] WHERE [id_place] = " + rw["id_place"], db_connection); db_adapter = new SqlDataAdapter(db_command); DataTable ptbl = new DataTable(); db_adapter.Fill(ptbl); if (ptbl.Rows.Count > 0) { DataRow place = ptbl.Rows[0]; file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выгружаем заказ " + rw["number"].ToString().Trim() + " на " + place["server"].ToString().Trim() + " в " + place["path"].ToString().Trim()); file.Flush(); using (FtpConnection connection = new FtpConnection( place["server"].ToString().Trim(), place["username"].ToString().Trim(), place["password"].ToString().Trim())) { connection.Encoding = Encoding.GetEncoding(1251); file.WriteLine("from: " + prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\"); file.Flush(); DiskFolder source = new DiskFolder(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\"); string ftp_to = place["path"].ToString().Trim() + rw["number"].ToString().Trim() + "/"; if (ftp_to.Substring(0, 1) == "/") ftp_to = ftp_to.Substring(1); file.WriteLine("to: " + ftp_to); file.Flush(); try { FtpFolder _ftp_to = new FtpFolder(connection, ftp_to); _ftp_to.Delete(); } catch { } FtpFolder destination = new FtpFolder(connection, ftp_to); StreamWriter _tmp = new StreamWriter(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\.lock"); _tmp.Write("\n"); _tmp.Close(); db_command = new SqlCommand("UPDATE [order] SET [status_export] = 'Началась выгрузка', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection); db_command.ExecuteNonQuery(); source.CopyFilesTo(destination, true, true); FtpFile _lock = new FtpFile(connection, ftp_to + ".lock"); _lock.Delete(); db_command = new SqlCommand("UPDATE [order] SET [auto_export] = -1, [status_export] = 'Отправлен', [status] = '500000', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection); db_command.ExecuteNonQuery(); file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выгружен заказ " + rw["number"].ToString().Trim()); file.Flush(); Directory.Delete(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\", true); } } } catch (Exception ex) { db_command = new SqlCommand("UPDATE [order] SET [status_export] = '" + ex.Message + "', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection); db_command.ExecuteNonQuery(); file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Ошибка выгрузки заказа " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace); file.Flush(); } } } catch (Exception ex) { file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Ошибка выгрузки заказов " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace); file.Flush(); } finally { UploadWork = false; } } } catch (Exception ex) { file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Глобальная ошибка по время отправления " + ex.Message); file.Flush(); } }
private static async Task _startMonitoringArchives(CancellationToken ct) { await logger.Log($"Начинаю обработку архивов"); #if DEBUG var creds = File.ReadAllLines("creds.txt"); #endif FTPEntry archive; try { archive = await apiDataProvider.GetNextArchiveForIndexing <FTPEntry>(ct); } catch (Exception exp) { await logger.Log("Не удалось получить архив для обработки. Прерываю работу."); await logger.Log(exp.Message); return; } while (archive != null) { try { await logger.Log($"Получил архив {archive.Id}"); var pathid = archive.Path; await logger.Log($"Идентификатор пути {archive.Id}"); var path = await apiDataProvider.GetPathById <FtpPath>(pathid, ct); await logger.Log($"Получил путь {path.Id}"); #if DEBUG path.Login = creds[0]; path.Password = creds[1]; #endif var file = new FtpFile(archive.Name, archive.Size, archive.Modified); await _monitorArchive(file, path, ct); } catch (Exception exp) { await logger.Log($"Произошла ошибка в момент обработки архива {archive.Id}"); await logger.Log(exp.Message); await logger.Log($"Отправляю уведомление об ошибке"); try { await apiDataProvider.SendArchiveFailedNotice(archive.Id, ct); } catch (Exception e) { await logger.Log($"Произошла ошибка при отправке уведомления об ошибке. Продолжаю без уведомления"); await logger.Log(e.Message); } } try { archive = await apiDataProvider.GetNextArchiveForIndexing <FTPEntry>(ct); } catch (Exception exp) { await logger.Log("Не удалось получить архив для обработки. Прерываю работу."); await logger.Log(exp.Message); return; } } await logger.Log($"Все архивы обработаны"); }