Exemplo n.º 1
0
        public static string SaveUploadedFileToFtp(ColumnField field, string strFileName, string contentType, System.IO.Stream stream)
        {
            if (!field.FtpUpload.Override && CheckIfFileExistInFtp(field, strFileName))
            {
                throw new DuradosException(field.View.Database.Localizer.Translate("File with same name already exist"));
            }


            System.Net.FtpWebRequest request = CreateFtpRequest(field, strFileName);

            request.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            byte[] buffer = new byte[stream.Length];

            //StreamReader sourceStream = new StreamReader(stream); //Only for text files !!!
            //byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());//Only for text files !!!

            int count = stream.Read(buffer, 0, buffer.Length);

            request.ContentLength = buffer.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(buffer, 0, buffer.Length);
            }

            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();

            response.Close();

            return(string.Empty);//response.StatusCode / response.StatusDescription
        }
Exemplo n.º 2
0
        public static List <string> FtpList(string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false, string searchRegEx = ".*")
        {
            System.Net.FtpWebRequest request = FtpRequest(
                ftpUrl: ftpUrl,
                ftpPath: ftpPath,
                ftpUsername: ftpUsername,
                ftpPassword: ftpPassword,
                ftpMethod: System.Net.WebRequestMethods.Ftp.ListDirectory,
                usePassive: usePassive
                );

            using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        List <string> lst_strFiles = new List <string>();
                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            if (Regex.Match(line, searchRegEx).Success)
                            {
                                lst_strFiles.Add(line);
                            }
                        }
                        return(lst_strFiles);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public static System.Net.FtpWebResponse FtpDownload(string localFilePath, string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false)
        {
            System.Net.FtpWebRequest request = FtpRequest(
                ftpUrl: ftpUrl,
                ftpPath: ftpPath,
                ftpUsername: ftpUsername,
                ftpPassword: ftpPassword,
                ftpMethod: System.Net.WebRequestMethods.Ftp.DownloadFile,
                usePassive: usePassive
                );

            using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        using (StreamWriter destination = new StreamWriter(localFilePath))
                        {
                            destination.Write(reader.ReadToEnd());
                            destination.Flush();
                        }
                    }
                }
                return(response);
            }
        }
Exemplo n.º 4
0
        public static void FtpUpload(string ftpPath, string user, string pwd, string inputFile)
        {
            //string ftpPath = "ftp://ftp.test.com/home/myindex.txt";
            //string user = "******";
            //string pwd = "ftppwd";
            //string inputFile = "index.txt";

            // WebRequest.Create로 Http,Ftp,File Request 객체를 모두 생성할 수 있다.
            System.Net.FtpWebRequest req = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpPath);
            // FTP 업로드한다는 것을 표시
            req.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            // 쓰기 권한이 있는 FTP 사용자 로그인 지정
            req.Credentials = new System.Net.NetworkCredential(user, pwd);

            // 입력파일을 바이트 배열로 읽음
            byte[] data;
            using (StreamReader reader = new StreamReader(inputFile))
            {
                data = Encoding.UTF8.GetBytes(reader.ReadToEnd());
            }

            // RequestStream에 데이타를 쓴다
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }

            // FTP Upload 실행
            using (System.Net.FtpWebResponse resp = (System.Net.FtpWebResponse)req.GetResponse())
            {
                // FTP 결과 상태 출력
                Console.WriteLine("Upload: {0}", resp.StatusDescription);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// FTP下载
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="remotepath">远程路径</param>
        /// <param name="localpath">本地路径</param>
        public bool FtpDownload(string userName, string password, string remotepath, string localpath)
        {
            bool bRet    = true;
            var  request = System.Net.WebRequest.Create(remotepath) as System.Net.FtpWebRequest;

            request.Method      = System.Net.WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new System.Net.NetworkCredential(userName, password);
            request.KeepAlive   = false;
            request.UseBinary   = true;

            System.Net.FtpWebResponse response  = null;
            System.IO.Stream          resStream = null;
            System.IO.FileStream      outStream = null;
            try
            {
                response  = request.GetResponse() as System.Net.FtpWebResponse;
                resStream = response.GetResponseStream();

                outStream = new System.IO.FileStream(localpath, System.IO.FileMode.Create);

                byte[] tmpBuf     = new byte[2048];
                int    nReadCount = resStream.Read(tmpBuf, 0, tmpBuf.Length);
                while (nReadCount > 0)
                {
                    outStream.Write(tmpBuf, 0, nReadCount);
                    nReadCount = resStream.Read(tmpBuf, 0, tmpBuf.Length);
                }
                tmpBuf = null;
            }
            catch (Exception e)
            {
                bRet = false;
                System.Console.WriteLine("FtpDownload Exception: " + e.Message);
                Settings.RuntimeLog.Severe("FtpDownload Exception: " + e.ToString());
            }
            finally
            {
                if (outStream != null)
                {
                    outStream.Flush();
                    outStream.Close();
                    outStream.Dispose();
                    outStream = null;
                }
                if (resStream != null)
                {
                    resStream.Close();
                    resStream.Dispose();
                    resStream = null;
                }
                if (response != null)
                {
                    response.Close();
                    response.Dispose();
                    response = null;
                }
            }
            return(bRet);
        }
        internal FtpWebResponse(System.Net.FtpWebResponse webResponse)
            : base(webResponse)
        {
            if (webResponse == null)
                throw new ArgumentNullException("webResponse");

            _webResponse = webResponse;
        }
Exemplo n.º 7
0
        internal FtpWebResponse(System.Net.FtpWebResponse webResponse)
            : base(webResponse)
        {
            if (webResponse == null)
            {
                throw new ArgumentNullException("webResponse");
            }

            _webResponse = webResponse;
        }
Exemplo n.º 8
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="downFile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public Boolean download(string url, string downFile, string username, string password)
        {
            Boolean ret = true;

            try
            {
                //ダウンロードするファイルのURI
                Uri u = new Uri(url);

                //FtpWebRequestの作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);
                //ログインユーザー名とパスワードを設定
                ftpReq.Credentials = new System.Net.NetworkCredential(username, password);
                //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")を設定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                //要求の完了後に接続を閉じる
                ftpReq.KeepAlive = false;
                //ASCIIモードで転送する
                ftpReq.UseBinary = true;
                //PASSIVEモードを無効にする
                ftpReq.UsePassive = false;

                //FtpWebResponseを取得
                System.Net.FtpWebResponse ftpRes =
                    (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //ファイルをダウンロードするためのStreamを取得
                System.IO.Stream resStrm = ftpRes.GetResponseStream();
                //ダウンロードしたファイルを書き込むためのFileStreamを作成
                System.IO.FileStream fs = new System.IO.FileStream(
                    downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                //ダウンロードしたデータを書き込む
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = resStrm.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                    fs.Write(buffer, 0, readSize);
                }
                fs.Close();
                resStrm.Close();

                //閉じる
                ftpRes.Close();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                ret = false;
            }
            return(ret);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="upFile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public Boolean uploadFile(string url, string upFile, string username, string password)
        {
            Boolean ret = true;

            try
            {
                //アップロード先のURI
                Uri u = new Uri(url);

                //FtpWebRequestの作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);
                //ログインユーザー名とパスワードを設定
                ftpReq.Credentials = new System.Net.NetworkCredential(username, password);
                //MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
                //要求の完了後に接続を閉じる
                ftpReq.KeepAlive = false;
                //ASCIIモードで転送する
                ftpReq.UseBinary = true;
                //PASVモードを無効にする
                ftpReq.UsePassive = false;

                //ファイルをアップロードするためのStreamを取得
                System.IO.Stream reqStrm = ftpReq.GetRequestStream();
                //アップロードするファイルを開く
                System.IO.FileStream fs = new System.IO.FileStream(
                    upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                //アップロードStreamに書き込む
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = fs.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                    reqStrm.Write(buffer, 0, readSize);
                }
                fs.Close();
                reqStrm.Close();

                //FtpWebResponseを取得
                System.Net.FtpWebResponse ftpRes =
                    (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //閉じる
                ftpRes.Close();
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return(ret);
        }
Exemplo n.º 10
0
Arquivo: Lib.cs Projeto: radtek/MMRDS
        public List <string> GetManifestFileList()
        {
            List <string> result = new List <string>();

            // Get the object used to communicate with the server.
            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(System.Configuration.ConfigurationManager.AppSettings["ftp_site"] + "/m");
            request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["ftp_user_id"], System.Configuration.ConfigurationManager.AppSettings["ftp_password"]);

            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();

            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream);


            string line = reader.ReadLine();

            while (!string.IsNullOrEmpty(line))
            {
                if (line.StartsWith("-"))
                {
                    int start_index = line.LastIndexOf(' ');
                    result.Add(line.Substring(start_index).Trim());
                }
                line = reader.ReadLine();
            }

            /*
             * drwxrwxrwx   1 user     group           0 Apr 12 11:10 .
             * drwxrwxrwx   1 user     group           0 Apr 12 11:10 ..
             * drwxrwxrwx   1 user     group           0 Apr 12 10:42 Epi_Info_7-1-5
             * -rw-rw-rw-   1 user     group       10193 Apr 12 11:10 release-7.1.5.txt
             *
             */


            // Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);



            reader.Close();
            response.Close();

            return(result);
        }
Exemplo n.º 11
0
        /// <summary>
        /// エラーファイルをサーバにアップロードする
        /// </summary>
        /// <param name="strErrLogPath"></param>
        private void ErrMsgUpload(string strErrLogPath)
        {
            try
            {
                string upFile = strErrLogPath;

                Uri u = new Uri("ftp://aaa" + Path.GetFileName(strErrLogPath));

                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);

                ftpReq.Credentials = new System.Net.NetworkCredential("aaaa", "aaaa");
                ftpReq.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpReq.KeepAlive   = false;
                ftpReq.UseBinary   = false;
                ftpReq.UsePassive  = false;

                System.IO.Stream reqStrm = ftpReq.GetRequestStream();

                using (System.IO.FileStream fs = new System.IO.FileStream(
                           upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    byte[] buffer = new byte[1024];
                    while (true)
                    {
                        int readSize = fs.Read(buffer, 0, buffer.Length);
                        if (readSize == 0)
                        {
                            break;
                        }
                        reqStrm.Write(buffer, 0, readSize);
                    }
                    fs.Close();
                }
                reqStrm.Close();

                System.Net.FtpWebResponse ftpRes =
                    (System.Net.FtpWebResponse)ftpReq.GetResponse();

                Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);

                ftpRes.Close();
            }
            catch (System.Exception)
            {
            }
        }
        private bool UploadFile(string ftpPath, string user, string password, FilePath filePath)
        {
            _log.Verbose($"Creating webrequest for {ftpPath}");

            if (!(System.Net.WebRequest.Create(ftpPath) is System.Net.FtpWebRequest ftpUpload))
            {
                throw new InvalidOperationException("Failed to create WebRequest for path {ftpPath}");
            }

            // originally this displayed the password. Removed so it isn't exposed.
            _log.Verbose($"Using credentials user : {user}, password: *******");
            ftpUpload.Credentials = new System.Net.NetworkCredential(user, password);
            _log.Verbose("Setting KeepAlive:false, UseBinary : true");
            ftpUpload.KeepAlive = false;
            ftpUpload.UseBinary = true;

            ftpUpload.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            using (System.IO.Stream
                   sourceStream = _fileSystem.GetFile(filePath).OpenRead(),
                   uploadStream = ftpUpload.GetRequestStream())
            {
                sourceStream.CopyTo(uploadStream);
                uploadStream.Close();
            }

            System.Net.FtpWebResponse uploadResponse = null;
            try
            {
                uploadResponse = (System.Net.FtpWebResponse)ftpUpload.GetResponse();
                var uploadResponseStatus = (uploadResponse.StatusDescription ?? string.Empty).Trim().ToUpper();
                if (!ValidFtpCreateStatuses.Any(x => uploadResponseStatus.IndexOf(x, StringComparison.OrdinalIgnoreCase) > -1))
                {
                    throw new InvalidOperationException(
                              $"Failed to upload file. Returned status {uploadResponseStatus}");
                }

                return(true);
            }
            finally
            {
                uploadResponse?.Close();
            }
        }
Exemplo n.º 13
0
 public static bool FtpDelete(string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false)
 {
     System.Net.FtpWebRequest request = FtpRequest(
         ftpUrl: ftpUrl,
         ftpPath: ftpPath,
         ftpUsername: ftpUsername,
         ftpPassword: ftpPassword,
         ftpMethod: System.Net.WebRequestMethods.Ftp.DeleteFile,
         usePassive: usePassive
         );
     try
     {
         using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse())
         {
             return(response.StatusCode == System.Net.FtpStatusCode.FileActionOK);
         }
     }
     catch (System.Net.WebException)
     {
         return(false);
     }
 }
Exemplo n.º 14
0
Arquivo: Lib.cs Projeto: radtek/MMRDS
        public string GetTextFileContent(string file_name)
        {
            string result = null;

            // Get the object used to communicate with the server.
            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(System.Configuration.ConfigurationManager.AppSettings["ftp_site"] + "/m/" + file_name);
            request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["ftp_user_id"], System.Configuration.ConfigurationManager.AppSettings["ftp_password"]);

            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();

            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream);


            result = reader.ReadToEnd();

            reader.Close();
            response.Close();

            return(result);
        }
Exemplo n.º 15
0
        string err_msg_str;     // error発生時の内容

        /**
         * @brief       OneFile ftp download
         * @param[in]   string  name    login name
         * @param[in]   string  pass    password
         * @param[in]   string  uri     DownloadするFileの URI 例"ftp://localhost/test_e.exe"
         * @param[in]   string  local_path     :DownloadしたFileの保存先 例"C:\\test_e.exe"
         * @return      bool    true:ok  false:error
         */
        public bool FtpOneFileDown(string name, string pass, string uri, string local_path)
        {
            Uri    uri_obj      = new Uri(uri);
            string downFilePath = local_path;

            err_msg_str = "no info.";

            // FtpWebRequestの作成
            System.Net.FtpWebRequest ftp_req = (System.Net.FtpWebRequest)
                                               System.Net.WebRequest.Create(uri_obj);

            // ログインユーザー名とパスワードを設定
            ftp_req.Credentials = new System.Net.NetworkCredential(name, pass);

            // MethodにWebRequestMethods.Ftp.DownloadFile("RETR")を設定
            ftp_req.Method     = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp_req.KeepAlive  = false; // 要求の完了後に接続を閉じる
            ftp_req.UseBinary  = false; // Binaryモードで転送する
            ftp_req.UsePassive = true;  // PASSIVEモードを有効にする

            bool ok_f = true;

            System.Net.FtpWebResponse ftp_res  = null;
            System.IO.Stream          res_strm = null;
            try
            {
                // FtpWebResponseを取得
                ftp_res = (System.Net.FtpWebResponse)ftp_req.GetResponse();

                // ファイルをダウンロードするためのStreamを取得
                res_strm = ftp_res.GetResponseStream();
            }
            catch (System.Net.WebException e_msg)
            {
                ok_f        = false;
                err_msg_str = e_msg.Message;

                if (ftp_res != null)
                {
                    ftp_res.Close();
                }
                if (res_strm != null)
                {
                    res_strm.Close();
                }
            }

            if (ok_f == true)
            {
                // ダウンロードしたファイルを書き込むためのFileStreamを作成
                System.IO.FileStream fs = null;
                fs = new System.IO.FileStream(downFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                try
                {
                    // ダウンロードしたデータを書き込む
                    int    size   = 1024;
                    byte[] buffer = new byte[size];
                    while (true)
                    {
                        int readSize = res_strm.Read(buffer, 0, buffer.Length);
                        if (readSize == 0)
                        {
                            break;
                        }
                        fs.Write(buffer, 0, readSize);
                    }

                    // FTPサーバーから送信されたステータスを表示
                    //Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
                }
                catch (System.IO.IOException ie)
                {
                    Console.WriteLine("", ie.Message);
                }
                finally {
                    if (fs != null)
                    {
                        fs.Close();
                    }

                    if (res_strm != null)
                    {
                        res_strm.Close();
                    }

                    if (ftp_res != null)
                    {
                        ftp_res.Close();
                    }
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void Exec(Model.Prestashop.PsProductAttachment PsProductAttachment)
        {
            try
            {
                //<YH> 21/08/2012
                string DirAttachment = Global.GetConfig().Folders.RootAttachment;

                Model.Local.ArticleRepository ArticleRepository = new Model.Local.ArticleRepository();
                if (ArticleRepository.ExistPre_Id(Convert.ToInt32(PsProductAttachment.IDProduct)))
                {
                    Model.Local.Article Article = ArticleRepository.ReadPre_Id(Convert.ToInt32(PsProductAttachment.IDProduct));
                    Model.Local.AttachmentRepository AttachmentRepository = new Model.Local.AttachmentRepository();
                    if (AttachmentRepository.ExistPre_IdArt_Id(Convert.ToInt32(PsProductAttachment.IDAttachment), Article.Art_Id) == false)
                    {
                        Model.Prestashop.PsAttachmentRepository     PsAttachmentRepository     = new Model.Prestashop.PsAttachmentRepository();
                        Model.Prestashop.PsAttachment               PsAttachment               = PsAttachmentRepository.ReadAttachment(PsProductAttachment.IDAttachment);
                        Model.Prestashop.PsAttachmentLangRepository PsAttachmentLangRepository = new Model.Prestashop.PsAttachmentLangRepository();
                        if (PsAttachmentLangRepository.ExistAttachmentLang(PsAttachment.IDAttachment, Core.Global.Lang))
                        {
                            Model.Prestashop.PsAttachmentLang PsAttachmentLang = PsAttachmentLangRepository.ReadAttachmentLang(PsAttachment.IDAttachment, Core.Global.Lang);
                            Model.Local.Attachment            Attachment       = new Model.Local.Attachment()
                            {
                                Att_FileName    = PsAttachment.FileName,
                                Att_Description = PsAttachmentLang.Description,
                                Att_Mime        = PsAttachment.Mime,
                                Att_Name        = PsAttachmentLang.Name,
                                Att_File        = this.ReadFile(DirAttachment, PsAttachment.File),
                                Pre_Id          = Convert.ToInt32(PsAttachment.IDAttachment),
                                Art_Id          = Article.Art_Id
                            };
                            AttachmentRepository.Add(Attachment);

                            String FTP      = Core.Global.GetConfig().ConfigFTPIP;
                            String User     = Core.Global.GetConfig().ConfigFTPUser;
                            String Password = Core.Global.GetConfig().ConfigFTPPassword;

                            // <JG> 21/05/2013 correction recherche fichier sur le ftp
                            string ftpfullpath           = FTP + "/download/" + PsAttachment.File;
                            System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                            ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                            ftp.UseBinary   = true;
                            ftp.UsePassive  = true;
                            ftp.KeepAlive   = false;
                            ftp.EnableSsl   = Core.Global.GetConfig().ConfigFTPSSL;

                            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse();
                            Stream reader = response.GetResponseStream();

                            MemoryStream memStream      = new MemoryStream();
                            byte[]       buffer         = new byte[1024];
                            byte[]       downloadedData = new byte[0];
                            while (true)
                            {
                                int bytesRead = reader.Read(buffer, 0, buffer.Length);
                                if (bytesRead != 0)
                                {
                                    memStream.Write(buffer, 0, bytesRead);
                                }
                                else
                                {
                                    break;
                                }
                                downloadedData = memStream.ToArray();
                            }

                            if (downloadedData != null && downloadedData.Length != 0)
                            {
                                FileStream newFile = new FileStream(DirAttachment + Attachment.Att_File, FileMode.Create);
                                newFile.Write(downloadedData, 0, downloadedData.Length);
                                newFile.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Error.SendMailError(ex.ToString());
            }
        }
        public Boolean Exec(String PathImg, Int32 ArticleSend, int position, int Declination)
        {
            Boolean result         = false;
            Int32   IdArticleImage = 0;

            try
            {
                String extension = Path.GetExtension(PathImg);
                String FileName  = Path.GetFileName(PathImg);

                Model.Local.ArticleImageRepository ArticleImageRepository = new Model.Local.ArticleImageRepository();

                if (!ArticleImageRepository.ExistArticleFile(ArticleSend, FileName))
                {
                    Model.Local.ArticleRepository ArticleRepository = new Model.Local.ArticleRepository();
                    Model.Local.Article           Article           = ArticleRepository.ReadArticle(ArticleSend);
                    Model.Local.ArticleImage      ArticleImage      = new Model.Local.ArticleImage()
                    {
                        Art_Id            = Article.Art_Id,
                        ImaArt_Name       = Article.Art_Name,
                        ImaArt_Image      = "",
                        ImaArt_DateAdd    = DateTime.Now,
                        ImaArt_SourceFile = FileName
                    };
                    ArticleImage.ImaArt_Position = this.ReadNextPosition(Article, position);
                    ArticleImage.ImaArt_Default  = !(new Model.Local.ArticleImageRepository().ExistArticleDefault(Article.Art_Id, true));
                    ArticleImageRepository.Add(ArticleImage);
                    ArticleImage.ImaArt_Image = String.Format("{0}" + extension, ArticleImage.ImaArt_Id);
                    ArticleImageRepository.Save();
                    IdArticleImage = ArticleImage.ImaArt_Id;

                    string uri = PathImg.Replace("File:///", "").Replace("file:///", "").Replace("File://", "\\\\").Replace("file://", "\\\\").Replace("/", "\\");

                    System.IO.File.Copy(uri, ArticleImage.TempFileName);

                    Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository();
                    List <Model.Prestashop.PsImageType>    ListPsImageType       = PsImageTypeRepository.ListProduct(1);

                    System.Drawing.Image img = System.Drawing.Image.FromFile(ArticleImage.TempFileName);

                    foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType)
                    {
                        Core.Img.resizeImage(img, Convert.ToInt32(PsImageType.Width), Convert.ToInt32(PsImageType.Height),
                                             ArticleImage.FileName(PsImageType.Name));
                    }

                    Core.Img.resizeImage(img, Core.Global.GetConfig().ConfigImageMiniatureWidth, Core.Global.GetConfig().ConfigImageMiniatureHeight,
                                         ArticleImage.SmallFileName);

                    img.Dispose();

                    // <JG> 28/10/2015 ajout attribution gamme/images
                    if (Declination != 0)
                    {
                        if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMonoGamme ||
                            ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMultiGammes)
                        {
                            Model.Local.AttributeArticleRepository AttributeArticleRepository = new Model.Local.AttributeArticleRepository();
                            if (AttributeArticleRepository.Exist(Declination))
                            {
                                Model.Local.AttributeArticleImageRepository AttributeArticleImageRepository = new Model.Local.AttributeArticleImageRepository();
                                if (!AttributeArticleImageRepository.ExistAttributeArticleImage(Declination, ArticleImage.ImaArt_Id))
                                {
                                    AttributeArticleImageRepository.Add(new Model.Local.AttributeArticleImage()
                                    {
                                        AttArt_Id = Declination,
                                        ImaArt_Id = ArticleImage.ImaArt_Id,
                                    });
                                }
                            }
                        }
                        else if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleComposition)
                        {
                            Model.Local.CompositionArticleRepository CompositionArticleRepository = new Model.Local.CompositionArticleRepository();
                            if (CompositionArticleRepository.Exist(Declination))
                            {
                                Model.Local.CompositionArticleImageRepository CompositionArticleImageRepository = new Model.Local.CompositionArticleImageRepository();
                                if (!CompositionArticleImageRepository.ExistCompositionArticleImage(Declination, ArticleImage.ImaArt_Id))
                                {
                                    CompositionArticleImageRepository.Add(new Model.Local.CompositionArticleImage()
                                    {
                                        ComArt_Id = Declination,
                                        ImaArt_Id = ArticleImage.ImaArt_Id,
                                    });
                                }
                            }
                        }
                    }

                    result = true;
                }
                else if (Core.Global.GetConfig().ImportImageReplaceFiles)
                {
                    FileInfo importfile = new FileInfo(PathImg);
                    Model.Local.ArticleImage ArticleImage = ArticleImageRepository.ReadArticleFile(ArticleSend, FileName);
                    FileInfo existfile = new FileInfo(ArticleImage.TempFileName);
                    if ((ArticleImage.ImaArt_DateAdd == null || importfile.LastWriteTime > ArticleImage.ImaArt_DateAdd) ||
                        importfile.Length != existfile.Length)
                    {
                        try
                        {
                            // import nouveau fichier
                            string uri = PathImg.Replace("File:///", "").Replace("file:///", "").Replace("File://", "\\\\").Replace("file://", "\\\\").Replace("/", "\\");
                            System.IO.File.Copy(uri, ArticleImage.TempFileName, true);

                            Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository();
                            List <Model.Prestashop.PsImageType>    ListPsImageType       = PsImageTypeRepository.ListProduct(1);

                            System.Drawing.Image img = System.Drawing.Image.FromFile(ArticleImage.TempFileName);

                            foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType)
                            {
                                Core.Img.resizeImage(img, Convert.ToInt32(PsImageType.Width), Convert.ToInt32(PsImageType.Height),
                                                     ArticleImage.FileName(PsImageType.Name));
                            }

                            Core.Img.resizeImage(img, Core.Global.GetConfig().ConfigImageMiniatureWidth, Core.Global.GetConfig().ConfigImageMiniatureHeight,
                                                 ArticleImage.SmallFileName);
                            Model.Prestashop.PsImageRepository PsImageRepository = new Model.Prestashop.PsImageRepository();

                            if (ArticleImage.Pre_Id != null && PsImageRepository.ExistImage((uint)ArticleImage.Pre_Id))
                            {
                                String FTP      = Core.Global.GetConfig().ConfigFTPIP;
                                String User     = Core.Global.GetConfig().ConfigFTPUser;
                                String Password = Core.Global.GetConfig().ConfigFTPPassword;

                                Model.Prestashop.PsImage PsImage = PsImageRepository.ReadImage((uint)ArticleImage.Pre_Id);

                                string ftpPath = "/img/p/";
                                switch (Core.Global.GetConfig().ConfigImageStorageMode)
                                {
                                case Core.Parametres.ImageStorageMode.old_system:
                                    #region old_system
                                    // no action on path
                                    break;
                                    #endregion

                                case Core.Parametres.ImageStorageMode.new_system:
                                default:
                                    #region new_system

                                    //System.Net.FtpWebRequest ftp_folder = null;

                                    foreach (char directory in PsImage.IDImage.ToString())
                                    {
                                        ftpPath += directory + "/";

                                        #region MyRegion
                                        try
                                        {
                                            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FTP + ftpPath);

                                            request.Credentials = new System.Net.NetworkCredential(User, Password);
                                            request.UsePassive  = true;
                                            request.UseBinary   = true;
                                            request.KeepAlive   = false;

                                            request.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory;

                                            System.Net.FtpWebResponse makeDirectoryResponse = (System.Net.FtpWebResponse)request.GetResponse();
                                        }
                                        catch     //Exception ex
                                        {
                                            //System.Windows.MessageBox.Show(ex.ToString());
                                        }
                                        #endregion
                                    }
                                    break;
                                    #endregion
                                }

                                #region Upload des images
                                extension = ArticleImage.GetExtension;
                                if (System.IO.File.Exists(ArticleImage.TempFileName))
                                {
                                    string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system)
                                        ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + ".jpg"
                                        : FTP + ftpPath + PsImage.IDImage + ".jpg";

                                    System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                                    ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                                    //userid and password for the ftp server to given

                                    ftp.UseBinary  = true;
                                    ftp.UsePassive = true;
                                    ftp.EnableSsl  = Core.Global.GetConfig().ConfigFTPSSL;
                                    ftp.Method     = System.Net.WebRequestMethods.Ftp.UploadFile;
                                    System.IO.FileStream fs = System.IO.File.OpenRead(ArticleImage.TempFileName);
                                    byte[] buffer           = new byte[fs.Length];
                                    fs.Read(buffer, 0, buffer.Length);
                                    fs.Close();
                                    System.IO.Stream ftpstream = ftp.GetRequestStream();
                                    ftpstream.Write(buffer, 0, buffer.Length);
                                    ftpstream.Close();
                                    ftp.Abort();
                                }


                                foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType)
                                {
                                    String localfile = ArticleImage.FileName(PsImageType.Name);
                                    if (System.IO.File.Exists(localfile))
                                    {
                                        string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system)
                                            ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + "-" + PsImageType.Name + ".jpg"
                                            : FTP + ftpPath + PsImage.IDImage + "-" + PsImageType.Name + ".jpg";

                                        System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                                        ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                                        //userid and password for the ftp server to given

                                        ftp.UseBinary  = true;
                                        ftp.UsePassive = true;
                                        ftp.EnableSsl  = Core.Global.GetConfig().ConfigFTPSSL;
                                        ftp.Method     = System.Net.WebRequestMethods.Ftp.UploadFile;
                                        System.IO.FileStream fs = System.IO.File.OpenRead(localfile);
                                        byte[] buffer           = new byte[fs.Length];
                                        fs.Read(buffer, 0, buffer.Length);
                                        fs.Close();
                                        System.IO.Stream ftpstream = ftp.GetRequestStream();
                                        ftpstream.Write(buffer, 0, buffer.Length);
                                        ftpstream.Close();
                                        ftp.Abort();
                                    }
                                }
                                #endregion
                            }

                            ArticleImage.ImaArt_DateAdd = DateTime.Now;
                            ArticleImageRepository.Save();

                            // <JG> 28/10/2015 ajout attribution gamme/images
                            if (Declination != 0)
                            {
                                if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMonoGamme ||
                                    ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMultiGammes)
                                {
                                    Model.Local.AttributeArticleRepository AttributeArticleRepository = new Model.Local.AttributeArticleRepository();
                                    if (AttributeArticleRepository.Exist(Declination))
                                    {
                                        Model.Local.AttributeArticleImageRepository AttributeArticleImageRepository = new Model.Local.AttributeArticleImageRepository();
                                        if (!AttributeArticleImageRepository.ExistAttributeArticleImage(Declination, ArticleImage.ImaArt_Id))
                                        {
                                            AttributeArticleImageRepository.Add(new Model.Local.AttributeArticleImage()
                                            {
                                                AttArt_Id = Declination,
                                                ImaArt_Id = ArticleImage.ImaArt_Id,
                                            });
                                        }

                                        // réaffectation côté PrestaShop
                                        Model.Local.AttributeArticle AttributeArticle = AttributeArticleRepository.Read(Declination);
                                        if (AttributeArticle.Pre_Id != null &&
                                            AttributeArticle.Pre_Id != 0)
                                        {
                                            Model.Prestashop.PsProductAttributeImageRepository PsProductAttributeImageRepository = new Model.Prestashop.PsProductAttributeImageRepository();
                                            if (PsProductAttributeImageRepository.ExistProductAttributeImage((UInt32)AttributeArticle.Pre_Id, (UInt32)ArticleImage.Pre_Id) == false)
                                            {
                                                PsProductAttributeImageRepository.Add(new Model.Prestashop.PsProductAttributeImage()
                                                {
                                                    IDImage            = (UInt32)ArticleImage.Pre_Id,
                                                    IDProductAttribute = (UInt32)AttributeArticle.Pre_Id,
                                                });
                                            }
                                        }
                                    }
                                }
                                else if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleComposition)
                                {
                                    Model.Local.CompositionArticleRepository CompositionArticleRepository = new Model.Local.CompositionArticleRepository();
                                    if (CompositionArticleRepository.Exist(Declination))
                                    {
                                        Model.Local.CompositionArticleImageRepository CompositionArticleImageRepository = new Model.Local.CompositionArticleImageRepository();
                                        if (!CompositionArticleImageRepository.ExistCompositionArticleImage(Declination, ArticleImage.ImaArt_Id))
                                        {
                                            CompositionArticleImageRepository.Add(new Model.Local.CompositionArticleImage()
                                            {
                                                ComArt_Id = Declination,
                                                ImaArt_Id = ArticleImage.ImaArt_Id,
                                            });
                                        }

                                        // réaffectation côté PrestaShop
                                        Model.Local.CompositionArticle CompositionArticle = CompositionArticleRepository.Read(Declination);
                                        if (CompositionArticle.Pre_Id != null &&
                                            CompositionArticle.Pre_Id != 0)
                                        {
                                            Model.Prestashop.PsProductAttributeImageRepository PsProductAttributeImageRepository = new Model.Prestashop.PsProductAttributeImageRepository();
                                            if (PsProductAttributeImageRepository.ExistProductAttributeImage((UInt32)CompositionArticle.Pre_Id, (UInt32)ArticleImage.Pre_Id) == false)
                                            {
                                                PsProductAttributeImageRepository.Add(new Model.Prestashop.PsProductAttributeImage()
                                                {
                                                    IDImage            = (UInt32)ArticleImage.Pre_Id,
                                                    IDProductAttribute = (UInt32)CompositionArticle.Pre_Id,
                                                });
                                            }
                                        }
                                    }
                                }
                            }

                            result = true;

                            logs.Add("II30- Remplacement de l'image " + ArticleImage.ImaArt_SourceFile + " en position " + ArticleImage.ImaArt_Position + " pour l'article " + ArticleImage.Article.Art_Ref);
                        }
                        catch (Exception ex)
                        {
                            Core.Error.SendMailError(ex.ToString());
                            logs.Add("II39- Erreur lors du remplacement de l'image " + ArticleImage.ImaArt_SourceFile + " en position " + ArticleImage.ImaArt_Position + " pour l'article " + ArticleImage.Article.Art_Ref);
                            logs.Add(ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Error.SendMailError(ex.ToString());
                if (ex.ToString().Contains("System.UnauthorizedAccessException") && IdArticleImage != 0)
                {
                    Model.Local.ArticleImageRepository ArticleImageRepository = new Model.Local.ArticleImageRepository();
                    ArticleImageRepository.Delete(ArticleImageRepository.ReadArticleImage(IdArticleImage));
                }
            }
            return(result);
        }
Exemplo n.º 18
0
        public void Sync(int IdArticle)
        {
            this.Semaphore.WaitOne();

            try
            {
                Model.Sage.F_ARTICLEMEDIARepository F_ARTICLEMEDIARepository = new Model.Sage.F_ARTICLEMEDIARepository();
                Model.Local.ArticleRepository       ArticleRepository        = new Model.Local.ArticleRepository();
                Model.Local.Article Article = new Model.Local.Article();
                if (ArticleRepository.ExistArticle(IdArticle))
                {
                    Article = ArticleRepository.ReadArticle(IdArticle);

                    // <JG> 24/03/2015 ajout option suppression auto
                    if (Core.Global.GetConfig().ImportMediaAutoDeleteAttachment)
                    {
                        Model.Local.AttachmentRepository AttachmentRepository = new Model.Local.AttachmentRepository();
                        if (AttachmentRepository.ExistArticle(IdArticle))
                        {
                            List <Model.Local.Attachment> ListArticle = AttachmentRepository.ListArticle(IdArticle);
                            ListArticle = ListArticle.Where(at => at.Sag_Id != null).ToList();

                            foreach (Model.Local.Attachment Attachment in ListArticle)
                            {
                                if (!F_ARTICLEMEDIARepository.Exist(Attachment.Sag_Id.Value))
                                {
                                    if (System.IO.File.Exists(System.IO.Path.Combine(Core.Global.GetConfig().Folders.RootAttachment, Attachment.Att_File)))
                                    {
                                        File.Delete(System.IO.Path.Combine(Core.Global.GetConfig().Folders.RootAttachment, Attachment.Att_File));
                                    }

                                    if (Attachment.Pre_Id != null && Attachment.Pre_Id > 0)
                                    {
                                        // Suppression de l'occurence du document sur prestashop
                                        Model.Prestashop.PsAttachmentRepository        psAttachmentRepository        = new Model.Prestashop.PsAttachmentRepository();
                                        Model.Prestashop.PsAttachmentLangRepository    psAttachmentLangRepository    = new Model.Prestashop.PsAttachmentLangRepository();
                                        Model.Prestashop.PsProductAttachmentRepository psProductAttachmentRepository = new Model.Prestashop.PsProductAttachmentRepository();

                                        Model.Prestashop.PsAttachment psAttachment = psAttachmentRepository.ReadAttachment(Convert.ToUInt32(Attachment.Pre_Id.Value));

                                        string distant_file = string.Empty;
                                        if (psAttachment != null)
                                        {
                                            distant_file = psAttachment.File;
                                            psProductAttachmentRepository.Delete(psProductAttachmentRepository.ListAttachment(psAttachment.IDAttachment));
                                            psAttachmentLangRepository.Delete(psAttachmentLangRepository.ListAttachment(psAttachment.IDAttachment));
                                            psAttachmentRepository.Delete(psAttachment);
                                        }

                                        if (Core.Global.GetConfig().ConfigFTPActive)
                                        {
                                            String FTP      = Core.Global.GetConfig().ConfigFTPIP;
                                            String User     = Core.Global.GetConfig().ConfigFTPUser;
                                            String Password = Core.Global.GetConfig().ConfigFTPPassword;

                                            string ftpfullpath = FTP + "/download/" + distant_file;

                                            if (Core.Ftp.ExistFile(ftpfullpath, User, Password))
                                            {
                                                try
                                                {
                                                    System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                                                    request.Credentials = new System.Net.NetworkCredential(User, Password);
                                                    request.Method      = System.Net.WebRequestMethods.Ftp.DeleteFile;
                                                    request.UseBinary   = true;
                                                    request.UsePassive  = true;
                                                    request.KeepAlive   = false;

                                                    System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();
                                                    response.Close();
                                                }
                                                catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); }
                                            }
                                        }
                                    }

                                    AttachmentRepository.Delete(Attachment);
                                }
                            }
                        }
                    }

                    if (F_ARTICLEMEDIARepository.ExistReference(Article.Art_Ref))
                    {
                        foreach (Model.Sage.F_ARTICLEMEDIA F_ARTICLEMEDIA in F_ARTICLEMEDIARepository.ListReference(Article.Art_Ref))
                        {
                            String File = (System.IO.File.Exists(F_ARTICLEMEDIA.ME_Fichier))
                                        ? F_ARTICLEMEDIA.ME_Fichier
                                        : Path.Combine(DirDoc, F_ARTICLEMEDIA.ME_Fichier.Substring(2));
                            if (System.IO.File.Exists(File))
                            {
                                string extension = Path.GetExtension(File).ToLower();
                                string filename  = Path.GetFileNameWithoutExtension(File);
                                Model.Local.MediaAssignmentRuleRepository MediaAssignmentRuleRepository = new Model.Local.MediaAssignmentRuleRepository();
                                List <Model.Local.MediaAssignmentRule>    list = MediaAssignmentRuleRepository.List();
                                if (list.Count(r => filename.EndsWith(r.SuffixText)) > 0)
                                {
                                    foreach (Model.Local.MediaAssignmentRule mediarule in list.Where(r => filename.EndsWith(r.SuffixText)))
                                    {
                                        if (filename.EndsWith(mediarule.SuffixText))
                                        {
                                            switch (mediarule.Rule)
                                            {
                                            case (short)Core.Parametres.MediaRule.AsAttachment:
                                                Core.ImportSage.ImportArticleDocument Sync = new Core.ImportSage.ImportArticleDocument();
                                                Sync.Exec(File, Article.Art_Id, (!string.IsNullOrEmpty(mediarule.AssignName) ? mediarule.AssignName : F_ARTICLEMEDIA.ME_Commentaire), null, F_ARTICLEMEDIA.cbMarq);
                                                break;

                                            case (short)Core.Parametres.MediaRule.AsPicture:
                                                if (Core.Img.imageExtensions.Contains(extension))
                                                {
                                                    int position, AttributeArticle;
                                                    Core.Global.SearchReference(filename, out position, out AttributeArticle);
                                                    Core.ImportSage.ImportArticleImage ImportImage = new Core.ImportSage.ImportArticleImage();
                                                    ImportImage.Exec(File, Article.Art_Id, position, AttributeArticle);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if (Core.Img.imageExtensions.Contains(extension))
                                    {
                                        if (Core.Global.GetConfig().ImportMediaIncludePictures)
                                        {
                                            int position, AttributeArticle;
                                            Core.Global.SearchReference(filename, out position, out AttributeArticle);
                                            Core.ImportSage.ImportArticleImage ImportImage = new Core.ImportSage.ImportArticleImage();
                                            ImportImage.Exec(File, Article.Art_Id, position, AttributeArticle);
                                        }
                                    }
                                    else
                                    {
                                        Core.ImportSage.ImportArticleDocument Sync = new Core.ImportSage.ImportArticleDocument();
                                        Sync.Exec(File, Article.Art_Id, F_ARTICLEMEDIA.ME_Commentaire, null, F_ARTICLEMEDIA.cbMarq);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Error.SendMailError("[IM] " + ex.ToString());
            }
            lock (this)
            {
                this.CurrentCount += 1;
            }
            this.ReportProgress(this.CurrentCount * 100 / this.ListCount);
            this.Semaphore.Release();
        }