public DataManagementWrapper(int concurrency, string clientRequestId)
        {
            TransferOptions options = new TransferOptions()
            {
                ParallelOperations = concurrency
            };

            if (!Environment.Is64BitProcess && options.MaximumCacheSize > Maximum32bitCacheSize)
            {
                options.MaximumCacheSize = Maximum32bitCacheSize;
            }

            this.manager = new TransferManager(options);
        }
 public Options Map(TransferOptions transferOptions)
 {
     if (transferOptions == null)
     {
         return null;
     }
     return new Options
     {
         AnnouncerName = transferOptions.AnnouncerName,
         Description = transferOptions.Description,
         FontSize = transferOptions.FontSize,
         OptionsId = transferOptions.OptionsId,
         ReadingSpeed = transferOptions.ReadingSpeed,
         EntityState = transferOptions.EntityState
     };
 }
Example #3
0
 /// <summary>
 /// Writes to an I2C device.
 /// </summary>
 /// <typeparam name="T">The type of data to transfer in buffer.</typeparam>
 /// <param name="deviceAddress">The address of the device to write to.</param>
 /// <param name="sizeToTransfer">The size, in bytes, to transfer.</param>
 /// <param name="buffer">The buffer to write from.</param>
 /// <param name="sizeTransferred">The size, in bytes, that were transferred.</param>
 /// <param name="options">The options to transfer with.</param>
 /// <returns>The status after calling this method.</returns>
 public FtdiStatus Write(byte deviceAddress, uint sizeToTransfer, IntPtr buffer, out uint sizeTransferred, TransferOptions options)
 {
     return(NativeMethods.I2C_DeviceWrite(handle, deviceAddress, sizeToTransfer, buffer, out sizeTransferred, options));
 }
Example #4
0
        public static bool Send_FTP_WMS(string file_origen, string file_destino, string wcd)
        {
            bool exito = false;

            try
            {
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol   = Protocol.Sftp,
                    HostName   = DatosGenerales.UrlFtp,  //"172.24.20.183"
                    UserName   = DatosGenerales.UserFtp, //"retailc"
                    Password   = DatosGenerales.PassFtp, //"1wiAwNRa"
                    PortNumber = 22,
                    GiveUpSecurityAndAcceptAnySshHostKey = true
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    //str.WriteLine("**************** CONECTADO CON EXITO AL FTP " + DateTime.Now);
                    //str.WriteLine("INICIO SUBIDA DE ACHIVO " + NombreArchivo + " AL SFTP " + DateTime.Now);
                    //string nombreAchivoRuta = NombreArchivo + DateTime.Now.ToString("yyyyMMdd") + ".mnt";
                    //string nombreArchivoCompleto = fileTXTc; // "\\\\200.1.1.40\\appl\\pos\\interfaces\\" + nombreAchivoRuta;

                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.FilePermissions   = null; // This is default
                    transferOptions.PreserveTimestamp = false;
                    transferOptions.TransferMode      = TransferMode.Binary;
                    TransferOperationResult transferResult;

                    transferResult = session.PutFiles(file_origen, "/data/730/" + wcd + "/input/" + Path.GetFileName(file_destino), false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    //if (transferResult.IsSuccess == true) exito = true;
                    exito = transferResult.IsSuccess;

                    // Print results
                    //if (exito)
                    //{
                    //    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    //    {
                    //        //varFinal = nombreAchivoRuta + "°" + subido + "°" + "CORRECTAMENTE SUBIDO" + transfer.FileName + " " + DateTime.Now + "°" + "1";
                    //        str.WriteLine("ARCHIVO FUE CARGADO OK: " + transfer.FileName + " " + DateTime.Now);
                    //        //exito = true;
                    //    }
                    //}
                }
            }

            catch (Exception ex)
            {
                //varFinal = string.Empty + "°" + string.Empty + "°" + "[ERROR] NO SE PUDO CARGAR EL DOCUMENTO " + NombreArchivo + " " + DateTime.Now + "°" + "0";
                //str.WriteLine("ERROR AL SUBIR ARCHIVO: " + fileTXTc + " " + e.Message + " " + DateTime.Now);
                LogUtil.Graba_Log("PRESC", "ERROR AL SUBIR FTP: " + ex.Message, true, "");
            }


            return(exito);
        }
 public DownloadRequestState()
 {
     request = null;
     options = null;
     isCancelled = false;
 }
 private string GetSerializedItem72(Item sourceItem, bool recurse, TransferOptions transferOptions)
 {
     var options = ItemSerializerOptions.GetDefaultOptions();
     options.AllowDefaultValues = transferOptions.HasFlag(TransferOptions.AllowDefaultValues);
     options.AllowStandardValues = transferOptions.HasFlag(TransferOptions.AllowStandardValues);
     options.ProcessChildren = recurse;
     return sourceItem.GetOuterXml(options);
 }
Example #7
0
        /// <summary> 
        /// Downloads audio from the robot  
        /// </summary> 
        /// <param name="sender"> object that called the method </param> 
        /// <param name="e"> any additional arguments </param> 
        void bgWorker_DoWork(object sender, DoWorkEventArgs e) 
        { 
            // Setup session options 
            SessionOptions sessionOptions = new SessionOptions 
            { 
                Protocol = Protocol.Sftp, 
                HostName = ipString, 
                UserName = "******", 
                Password = "******", 
                SshHostKeyFingerprint = "ssh-rsa 20487c:48:34:e3:c0:7a:92:8e:2f:95:79:0e:12:69:79:e7", 
            }; 
 
            using (Session session = new Session()) 
            { 
                // tell library path to the winSCP executable 
                session.ExecutablePath = System.IO.Directory.GetCurrentDirectory() 
+ "\\winSCPexe.exe"; 
       
                // Connect 
                session.Open(sessionOptions); 
 
                //Set up transfer 
                TransferOptions transferOptions = new TransferOptions(); 
                transferOptions.TransferMode = TransferMode.Binary; 
 
                // generate a file based on date and time 
                string time = Convert.ToString(DateTime.UtcNow.ToFileTime()); 
 
                string destination = "C:\\NAOserver\\" + "NAO_Audio_" + time + ".ogg"; 
 
                // download files 
                TransferOperationResult transferResult; 
                transferResult = session.GetFiles("/home/nao/temp.ogg", 
@destination, true, transferOptions); 
 
                // Throw on any error 
                transferResult.Check(); 
            } 
        } 
Example #8
0
 public DownloadRequestState()
 {
     request = null;
     options = null;
 }
Example #9
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest  webRequest    = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                    uploadOptions          = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server   = args[1];
                    uploadOptions.FileKey  = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params   = args[5];

                    bool trustAll = false;
                    bool.TryParse(args[6], out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id      = args[9];
                    uploadOptions.Method  = args[10];

                    uploadOptions.Cookies    = args[11];
                    uploadOptions.CallbackId = callbackId = args[12];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest             = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
                webRequest.Method      = uploadOptions.Method;
                var cookies       = (uploadOptions.Cookies ?? "").Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                var cookiesHeader = "";
                if (cookies.Length > 0)
                {
                    foreach (var c in cookies)
                    {
                        var cookie = (c ?? "").Split(new[] { ';' }, StringSplitOptions.None);
                        if (cookie.Length >= 4)
                        {
                            //if (webRequest.CookieContainer == null)
                            //{
                            //    webRequest.CookieContainer = new CookieContainer();
                            //}
                            //var cookieItem = new Cookie(cookie[0], cookie[1], cookie[2], cookie[3]);
                            //cookieItem.Expires = new DateTime(2100, 1, 1);
                            //webRequest.CookieContainer.Add(serverUri, cookieItem);
                            cookiesHeader = (string.IsNullOrEmpty(cookiesHeader) ? "" : "; ")
                                            + cookie[0] + "=" + cookie[1];
                        }
                    }
                }
                if (!string.IsNullOrEmpty(cookiesHeader))
                {
                    webRequest.Headers["Cookie"] = cookiesHeader;
                }

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(uploadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                DownloadRequestState reqState = new DownloadRequestState();
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                InProcDownloads[uploadOptions.Id] = reqState;

                webRequest.BeginGetRequestStream(uploadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
            }
        }
Example #10
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest  webRequest    = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                    uploadOptions          = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server   = args[1];
                    uploadOptions.FileKey  = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params   = args[5];

                    bool trustAll = false;
                    bool.TryParse(args[6], out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id      = args[9];
                    uploadOptions.Method  = args[10];

                    uploadOptions.CallbackId = callbackId = args[11];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest             = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
                webRequest.Method      = uploadOptions.Method;

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(uploadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                DownloadRequestState reqState = new DownloadRequestState();
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                InProcDownloads[uploadOptions.Id] = reqState;

                webRequest.BeginGetRequestStream(uploadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
            }
        }
Example #11
0
        public void UploadFile(TransferRecord record)
        {
            var defaultLocalPath  = _cfg.LocalPath;
            var defaultRemotePath = _cfg.RemotePath;

            TransferOptions transferOptions = new TransferOptions();

            transferOptions.TransferMode = TransferMode.Automatic;
            //switch (_cfg.ProtocolType)
            //{
            //    case FtpType.SFTP:
            //        //恢復續傳
            //        transferOptions.ResumeSupport.State = TransferResumeSupportState.On;
            //        break;
            //    case FtpType.FTP:
            //        //no way...
            //        break;
            //}
            //傳輸速度(KB/s)
            if (!(_cfg.SpeedLimit == 0))
            {
                transferOptions.SpeedLimit = _cfg.SpeedLimit;
            }

            Stopwatch sw = new Stopwatch();

            string filePath       = Path.Combine(defaultLocalPath, record.FileName);
            string remoteFilePath = Path.Combine(defaultRemotePath, record.FileName);

            // 嘗試次數
            record.ProcessTimes++;
            record.LocalFilePath  = filePath;
            record.RemoteFilePath = remoteFilePath;
            record.Status         = "20";

            Console.WriteLine($"檔名:{record.FileName}");
            Console.WriteLine($"本機路徑:{record.LocalFilePath}");
            Console.WriteLine($"遠端路徑:{record.RemoteFilePath}");

            log.Info($"檔名:{record.FileName}");
            log.Info($"本機路徑:{record.LocalFilePath}");
            log.Info($"遠端路徑:{record.RemoteFilePath}");

            //file exist or not
            if (File.Exists(filePath))
            {
                //上傳前驗證碼檢查
                record.GetFileSHA256();
                if (!record.ComparisonHash())
                {
                    record.Done         = false;
                    record.ErrorCode    = "SHA";
                    record.Status       = "21";
                    record.ErrorMessage = "檔案上傳失敗,訊息:檔案SHA256驗證碼失敗";
                    log.Error($"[失敗]{record.ErrorMessage}");
                    Console.WriteLine($"[失敗]{record.ErrorMessage}");
                    return;
                }

                log.Info("開始上傳");
                Console.WriteLine("開始上傳");
                sw.Start();
                var transferResult = _session.PutFiles(filePath, defaultRemotePath, false, transferOptions);
                sw.Stop();
                record.TransferElapsed = sw.Elapsed;

                //Throw the first failure in the list
                transferResult.Check();
                //檔案長度(位元組)
                record.TransferFileSize = _session.GetFileInfo(remoteFilePath).Length;
                record.CalAveRate();
                log.Info($"檔案大小(位元組):{record.TransferFileSize.ToString("#,#")}");
                log.Info($"均速(kB/s):{record.TransferSpeed.ToString("#,#")}");
                Console.WriteLine($"檔案大小(位元組):{record.TransferFileSize.ToString("#,#")}");
                Console.WriteLine($"均速(kB/s):{record.TransferSpeed.ToString("#,#")}");

                if (transferResult.IsSuccess)
                {
                    record.Done   = true;
                    record.Status = "30";
                    log.Info("[完成]");
                    Console.WriteLine("[完成]");
                }
                else
                {
                    record.Done      = false;
                    record.ErrorCode = "UpLoad";
                    record.Status    = "21";

                    var error = transferResult.Transfers.FirstOrDefault();
                    if (error != null)
                    {
                        record.ErrorMessage = $"檔案上傳失敗,訊息:{ error.Error.Message}";
                        log.Error($"[失敗]{record.ErrorMessage}");
                        Console.WriteLine($"[失敗]{record.ErrorMessage}");
                    }
                }
            }
            else
            {
                record.Done         = false;
                record.Status       = "21";
                record.ErrorMessage = $"檔案上傳失敗,訊息:檔案不存在";
                log.Error($"[失敗]{record.ErrorMessage}");
                Console.WriteLine($"[失敗]{record.ErrorMessage}");
            }
        }
Example #12
0
        /// <summary>下載</summary>
        /// <param name="record"></param>
        public void DownloadFile(TransferRecord record)
        {
            var defaultLocalPath  = _cfg.LocalPath;
            var defaultRemotePath = _cfg.RemotePath;

            TransferOptions transferOptions = new TransferOptions();

            transferOptions.TransferMode = TransferMode.Automatic;
            //恢復續傳
            transferOptions.OverwriteMode = OverwriteMode.Resume;

            //傳輸速度(kb/s)
            if (!(_cfg.SpeedLimit == 0))
            {
                transferOptions.SpeedLimit = _cfg.SpeedLimit;
            }

            Stopwatch sw = new Stopwatch();

            string filePath      = Path.Combine(defaultRemotePath, record.FileName);
            string localFilePath = Path.Combine(defaultLocalPath, record.FileName);

            // 嘗試次數
            record.ProcessTimes++;
            record.LocalFilePath  = localFilePath;
            record.RemoteFilePath = filePath;
            record.Status         = "40";

            log.Info($"檔名:{record.FileName}");
            log.Info($"本機路徑:{record.LocalFilePath}");
            log.Info($"遠端路徑:{record.RemoteFilePath}");

            if (_session.FileExists(filePath))
            {
                //取得檔案長度(位元組)
                record.TransferFileSize = _session.GetFileInfo(filePath).Length;
                log.Info("開始下載");
                sw.Start();
                var transferResult = _session.GetFiles(filePath, defaultLocalPath, false, transferOptions);
                sw.Stop();
                record.TransferElapsed = sw.Elapsed;

                /*
                 * transferResult.IsSuccess:Is true, if .failures is empty collection
                 * If there's a failure, the transferResult.Check() throws.
                 */
                transferResult.Check();
                record.CalAveRate();
                log.Info($"檔案大小(位元組):{record.TransferFileSize.ToString("#,#")}");
                log.Info($"均速(kB/s):{record.TransferSpeed.ToString("#,#")}");

                if (transferResult.IsSuccess)
                {
                    //下載後驗證碼檢查
                    record.GetFileSHA256();
                    if (record.ComparisonHash())
                    {
                        record.Done   = true;
                        record.Status = "50";
                        log.Info("[完成]");
                    }
                    else
                    {
                        record.Done         = false;
                        record.ErrorCode    = "SHA";
                        record.Status       = "41";
                        record.ErrorMessage = $"檔案下載失敗,訊息:檔案SHA256驗證碼失敗";
                        log.Error($"[失敗]{record.ErrorMessage}");
                        if (File.Exists(localFilePath))
                        {
                            File.Delete(localFilePath);
                        }
                    }
                }
                else
                {
                    // 加入錯誤訊息
                    record.Done      = false;
                    record.ErrorCode = "DownLoad";
                    record.Status    = "41";

                    var error = transferResult.Transfers.FirstOrDefault();
                    if (error != null)
                    {
                        record.ErrorMessage = $"檔案下載失敗,訊息:{ error.Error.Message}";
                        log.Error($"[失敗]{record.ErrorMessage}");
                    }
                }
            }
            else
            {
                record.Done         = false;
                record.Status       = "41";
                record.ErrorMessage = $"檔案下載失敗,訊息:檔案不存在";
                log.Error($"[失敗]{record.ErrorMessage}");
            }
        }
        internal void TransferEventArgs_Instantiates_With_The_Given_Data(TransferDirection direction, string username, string filename, int token, TransferOptions options)
        {
            var dl = new Transfer(direction, username, filename, token, options);
            var d  = new TransferEventArgs(dl);

            Assert.Equal(direction, d.Direction);
            Assert.Equal(0, d.AverageSpeed);
            Assert.Equal(0, d.BytesTransferred);
            Assert.Equal(0, d.BytesRemaining);
            Assert.Equal(default(TimeSpan), d.ElapsedTime);
            Assert.Equal(default(TimeSpan), d.RemainingTime);
            Assert.Null(d.StartTime);
            Assert.Null(d.EndTime);
            Assert.Null(d.IPAddress);
            Assert.Equal(0, d.PercentComplete);
            Assert.Null(d.Port);
            Assert.Equal(dl.RemoteToken, d.RemoteToken);
            Assert.Equal(0, d.Size);
            Assert.Equal(dl.Username, d.Username);
            Assert.Equal(dl.Filename, d.Filename);
            Assert.Equal(dl.Token, d.Token);
            Assert.Equal(dl.State, d.State);
            Assert.Equal(options, d.Options);
            Assert.Equal(dl.Data, d.Data);
        }
Example #14
0
        private void SendFilesFromDirectory(string frompath, string topath, int num_files)
        {
            SessionOptions          sessionOptions;
            Session                 session;
            TransferOperationResult transferResult;
            TransferOptions         transferOptions;

            // Get List of files in a directory recursively

            Console.Write("FromPath " + frompath + " topath " + topath);

            foreach (string d in Directory.GetDirectories(frompath))
            {
                foreach (string f in Directory.GetFiles(d))
                {
                    this.Invoke(new Action <string>(progressLabel_ChangeText), "Sending " + f);

                    Console.Write("\nUploading " + f + " -> " + topath + f.Replace(@"c:\temp\data\", "").Replace(@"\", "/") + "\n");

                    try
                    {
                        // Setup session options
                        sessionOptions = new SessionOptions
                        {
                            Protocol   = Protocol.Ftp,
                            HostName   = ipBox.Text,
                            PortNumber = Convert.ToInt32(portBox.Text),
                            UserName   = "******",
                            Password   = ""
                        };

                        using (session = new Session())
                        {
                            session.FileTransferProgress += SessionFileTransferProgress;

                            session.Timeout = new TimeSpan(0, 3, 30);

                            // Connect
                            session.Open(sessionOptions);

                            transferOptions = new TransferOptions();
                            transferOptions.TransferMode = TransferMode.Binary;

                            transferResult = session.PutFiles(f, topath + f.Replace(@"c:\temp\data\", "").Replace(@"\", "/"), true, transferOptions);
                            // Throw on any error
                            transferResult.Check();

                            this.Invoke(new Action <string>(statusLabel_ChangeText), "Installing...");

                            // Print results
                            foreach (TransferEventArgs transfer in transferResult.Transfers)
                            {
                                Console.WriteLine("\nUpload of {0} succeeded", transfer.FileName);
                                this.Invoke(new Action <int>(numberFilesUploaded_Change), getNumberFilesUploaded() + 1);
                                this.Invoke(new Action <int>(progressBar1_ChangeValue), (100 / number_files_to_upload) * files_uploaded);
                            }

                            session.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: {0}", ex);
                        Console.WriteLine("Error: {0}", ex);
                        this.Invoke(new Action <string>(statusLabel_ChangeText), @"ERROR");
                        this.Invoke(new Action <int>(progressBar1_ChangeValue), 0);
                        this.Invoke(new Action <bool>(button2_ChangeState), true);
                        this.Invoke(new Action <string>(progressLabel_ChangeText), @"");
                        MessageBox.Show(ex.Message, "error");
                    }
                }
                SendFilesFromDirectory(d, topath, number_files_to_upload);
            }
        }
Example #15
0
        private void Install()
        {
            SessionOptions          sessionOptions;
            Session                 session;
            TransferOperationResult transferResult;
            TransferOptions         transferOptions;

            // CREATE VPK
            this.Invoke(new Action <string>(statusLabel_ChangeText), @"Creating .vpk...");
            this.Invoke(new Action <bool>(button2_ChangeState), false);
            this.Invoke(new Action <bool>(button1_ChangeState), false);

            using (var archive = ZipArchive.Create())
            {
                archive.AddAllFromDirectory(@"C:\temp\install");
                archive.SaveTo(@"C:\\temp\\installer.vpk", CompressionType.None);
            }

            this.Invoke(new Action <string>(statusLabel_ChangeText), @"VPK Created");
            this.Invoke(new Action <int>(progressBar1_ChangeValue), 25);

            System.Threading.Thread.Sleep(1000);

            // TRANSFER VPK

            this.Invoke(new Action <string>(statusLabel_ChangeText), @"Connecting...");
            try
            {
                // Setup session options
                sessionOptions = new SessionOptions
                {
                    Protocol   = Protocol.Ftp,
                    HostName   = ipBox.Text,
                    PortNumber = Convert.ToInt32(portBox.Text),
                    UserName   = "******",
                    Password   = ""
                };

                using (session = new Session())
                {
                    session.FileTransferProgress += SessionFileTransferProgress;

                    // Connect
                    session.Open(sessionOptions);
                    session.Timeout = TimeSpan.FromSeconds(120000);

                    // Show Log
                    //var t = new Thread(new ThreadStart(this.ShowLog));
                    //t.Start();

                    this.Invoke(new Action <string>(statusLabel_ChangeText), @"Connected");
                    // Upload files
                    transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    this.Invoke(new Action <string>(statusLabel_ChangeText), @"Copying Installer...");
                    transferResult = session.PutFiles(@"c:\temp\installer.vpk", "ux0:/VPKs/", true, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }
                    this.Invoke(new Action <int>(progressBar1_ChangeValue), 50);

                    this.Invoke(new Action <string>(statusLabel_ChangeText), @"Installing VPK...");

                    // Auto-install VPK
                    Console.Write("\n PROMOTING INSTALLER.VPK! \n");
                    session.ExecuteCommand("PROM ux0:/VPKs/installer.vpk");


                    session.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex);
                this.Invoke(new Action <string>(statusLabel_ChangeText), @"ERROR");
                this.Invoke(new Action <int>(progressBar1_ChangeValue), 0);
                this.Invoke(new Action <bool>(button2_ChangeState), true);
                this.Invoke(new Action <string>(progressLabel_ChangeText), @"");
                this.Invoke(new Action <bool>(button1_ChangeState), true);
                MessageBox.Show(ex.Message, "error");
            }

            // UPLOAD DATA
            try
            {
                // Setup session options
                sessionOptions = new SessionOptions
                {
                    Protocol   = Protocol.Ftp,
                    HostName   = ipBox.Text,
                    PortNumber = Convert.ToInt32(portBox.Text),
                    UserName   = "******",
                    Password   = ""
                };

                using (session = new Session())
                {
                    session.FileTransferProgress += SessionFileTransferProgress;
                    session.Open(sessionOptions);
                    bool vpkinstalled = false;

                    while (!vpkinstalled)
                    {
                        if (session.FileExists("ux0:/app/" + param.TitleID + "/eboot.bin"))
                        {
                            vpkinstalled = true;
                        }
                    }

                    Console.Write("\n VPK Installed \n");

                    session.RemoveFiles("ux0:/VPKs/installer.vpk");

                    if (Directory.Exists("C:\\temp\\install"))
                    {
                        Console.Write("\nTemp install directory deleted");
                        Directory.Delete(@"C:/temp/install", true);
                    }

                    session.Close();
                }
            }
            catch (Exception ex)
            {
                Console.Write("\n ERROR UPLOADING DATA \n");
                Console.WriteLine("Error: {0}", ex);
                this.Invoke(new Action <string>(statusLabel_ChangeText), @"ERROR");
                this.Invoke(new Action <int>(progressBar1_ChangeValue), 0);
                this.Invoke(new Action <bool>(button2_ChangeState), true);
                this.Invoke(new Action <string>(progressLabel_ChangeText), @"");
                this.Invoke(new Action <bool>(button1_ChangeState), true);
                MessageBox.Show(ex.Message, "error");
            }

            string apppath = "/ux0:/app/" + param.TitleID + "/";

            this.Invoke(new Action <int>(numberFilesUploaded_Change), 0);
            this.Invoke(new Action <int>(numberFilestoUpload_Change), 0);

            this.Invoke(new Action <int>(progressBar1_ChangeValue), 0);

            CountNumberFilesInPath(@"c:\temp\");
            SendFilesFromDirectory(@"c:\temp\", apppath, number_files_to_upload);

            MessageBox.Show(param.Title + " installed successfully.", "Congrats!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Invoke(new Action <int>(progressBar1_ChangeValue), 100);
            this.Invoke(new Action <string>(statusLabel_ChangeText), @"Completed");
            this.Invoke(new Action <bool>(button2_ChangeState), true);
            this.Invoke(new Action <bool>(button1_ChangeState), true);

            // Clean temp directory
            Directory.Delete(@"C:/temp", true);

            this.Invoke(new Action <string>(progressLabel_ChangeText), @"");
        }
Example #16
0
        /// <summary>
        /// Writes to an I2C device.
        /// </summary>
        /// <typeparam name="T">The type of data to transfer in buffer.</typeparam>
        /// <param name="deviceAddress">The address of the device to write to.</param>
        /// <param name="sizeToTransfer">The size, in bytes, to transfer.</param>
        /// <param name="buffer">The buffer to write from.</param>
        /// <param name="sizeTransferred">The size, in bytes, that were transferred.</param>
        /// <param name="options">The options to transfer with.</param>
        /// <returns>The status after calling this method.</returns>
        public FtdiStatus Write <T>(byte deviceAddress, uint sizeToTransfer, T[,] buffer, out uint sizeTransferred, TransferOptions options)
            where T : struct
        {
            GCHandle   handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            FtdiStatus status = Write(deviceAddress, sizeToTransfer, handle.AddrOfPinnedObject(), out sizeTransferred, options);

            handle.Free();

            return(status);
        }
        public void sync(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest webRequest = null;
            string callbackId;

            try
            {
                // options.src, options.type, options.headers, options.id
                string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);

                downloadOptions = new TransferOptions();
                downloadOptions.Url = optionStrings[0];

                downloadOptions.Id = optionStrings[1];

                downloadOptions.FilePath = "content_sync/downloads/" + downloadOptions.Id;

                if (String.Equals(optionStrings[2], "replace"))
                {
                    downloadOptions.Type = Replace;
                }
                else
                {
                    downloadOptions.Type = Merge;
                }

                downloadOptions.Headers = optionStrings[3];

                bool copyCordovaAssets = false;
                bool.TryParse(optionStrings[4], out copyCordovaAssets);
                downloadOptions.CopyCordovaAssets = copyCordovaAssets;

                bool copyRootApp = false;
                bool.TryParse(optionStrings[5], out copyRootApp);
                downloadOptions.CopyRootApp = copyRootApp;

                downloadOptions.Timeout = Convert.ToInt32(optionStrings[6]);

                bool trustAll = false;
                bool.TryParse(optionStrings[7], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Manifest = optionStrings[8];

                downloadOptions.CallbackId = callbackId = optionStrings[optionStrings.Length-1];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // not sure if we still need this
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Create, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int bytesRead = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    string result = "{ \"localPath\": \"" + downloadOptions.FilePath + "\" , \"Id\" : \"" + downloadOptions.Id + "\"}";
                    if (result != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, 0), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                      new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                      new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new SyncProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Example #18
0
 public DownloadRequestState()
 {
     request     = null;
     options     = null;
     isCancelled = false;
 }
Example #19
0
        /// <summary>
        /// Cmdlet begin processing
        /// </summary>
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            TransferOptions opts = new TransferOptions();
            opts.ParallelOperations = GetCmdletConcurrency();
            opts.ClientRequestIdPrefix = CmdletOperationContext.ClientRequestId;
            
            transferManager = new TransferManager(opts);
        }
Example #20
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;
            string          callbackId;

            try
            {
                // source, target, trustAllHosts, this._id, headers
                string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);

                downloadOptions          = new TransferOptions();
                downloadOptions.Url      = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id         = optionStrings[3];
                downloadOptions.Headers    = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", "");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri      = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int  bytesRead  = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int    BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
                    if (entry != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    // eat it
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId   = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Example #21
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest webRequest = null;
            string callbackId;

            try
            {
                string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);

                downloadOptions = new TransferOptions();
                downloadOptions.Url = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2],out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id = optionStrings[3];
                downloadOptions.Headers = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];

            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
            }
            //catch (WebException webEx)
            //{

            //}
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
            }
        }
Example #22
0
        /// <summary>
        /// Checks whether all local settings are correct and parses the filepath string to a string array
        /// Note the web service connection is not checked here
        /// </summary>
        private static void setup()
        {
            //Hide console window
            window = GetConsoleWindow();
            ShowWindow(window, 0);

            //session to the server
            if (Properties.Settings.Default.BackupHostKeyFingerprint.Length == 0)
            {
                sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = Properties.Settings.Default.BackupHostName,
                    UserName = Properties.Settings.Default.BackUpUserName,
                    Password = Properties.Settings.Default.BackUpPassword,
                    GiveUpSecurityAndAcceptAnySshHostKey = true
                };
            }
            else
            {
                sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = Properties.Settings.Default.BackupHostName,
                    UserName = Properties.Settings.Default.BackUpUserName,
                    Password = Properties.Settings.Default.BackUpPassword,
                    SshHostKeyFingerprint = Properties.Settings.Default.BackupHostKeyFingerprint
                };
            }

            //runpath
            if (!Directory.Exists(Properties.Settings.Default.RunPath))
            {
                throw new ArgumentException(
                          "invallid RunPath" + Properties.Settings.Default.RunPath + " does not exist");
            }
            Directory.CreateDirectory(Path.Combine(Properties.Settings.Default.RunPath, "backUpManager"));
            if (!File.Exists(Path.Combine(Properties.Settings.Default.RunPath, "backUpManager", "logs.csv")))
            {
                using (Session session = new Session())
                {
                    // Connect
                    session.Open(Program.sessionOptions);

                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    //if no file structure exists obtain it from the server
                    if (session.FileExists(Properties.Settings.Default.BackUpPath + "/logs.csv"))
                    {
                        session.GetFiles(
                            Properties.Settings.Default.BackUpPath + "/logs.csv",
                            Path.Combine(Properties.Settings.Default.RunPath, "backUpManager", "logs.csv"),
                            false,
                            transferOptions).Check();
                    }
                    session.Close();
                }
            }


            // all roots of the backup sources
            //split string in strings at ,
            sourcePaths = Properties.Settings.Default.SourcePath.Split(',');
            //remove leading and ending spaces and check if all paths exist
            for (int i = 0; i < sourcePaths.Length; i++)
            {
                sourcePaths[i] = sourcePaths[i].TrimStart(' ');
                sourcePaths[i] = sourcePaths[i].TrimEnd(' ');
                if (!Directory.Exists(sourcePaths[i]))
                {
                    throw new ArgumentException("Directory " + sourcePaths[i] + " not found");
                }
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            //If no internet connection is available terminate program
            int Desc;

            if (!InternetGetConnectedState(out Desc, 0))
            {
                return;
            }

            //set up basic settings
            setup();
            folderManager = new FolderManager(Path.Combine(Properties.Settings.Default.RunPath, "backUpManager"));

            //start connection with server
            try
            {
                // session to server for backups
                using (Session session = new Session())
                    using (StreamWriter streamWriter = new StreamWriter(Path.Combine(Properties.Settings.Default.RunPath, "backUpManager", "logs.csv"), true))
                    {
                        // Connect
                        session.Open(sessionOptions);

                        // Upload files
                        TransferOptions transferOptions = new TransferOptions();
                        transferOptions.TransferMode = TransferMode.Binary;
                        TransferOperationResult transferResult;

                        //foreach root of the sourcePaths
                        foreach (string path in sourcePaths)
                        {
                            foreach (Tuple <Actions, string> change in folderManager.UpdateFileStructure(path))
                            {
                                switch (change.Item1)
                                {
                                case Actions.new_directory:
                                    Console.WriteLine(change.Item1 + " : " + Properties.Settings.Default.BackUpPath + change.Item2.Replace('\\', '/'));
                                    session.CreateDirectory(Properties.Settings.Default.BackUpPath + change.Item2.Replace('\\', '/'));

                                    break;

                                case Actions.removed_directory:
                                case Actions.removed_file:
                                    Console.WriteLine(change.Item1 + " : " + Properties.Settings.Default.BackUpPath + change.Item2.Replace('\\', '/'));
                                    session.RemoveFiles(Properties.Settings.Default.BackUpPath + change.Item2.Replace('\\', '/'));
                                    break;

                                case Actions.new_file:
                                case Actions.updated_file:

                                    Console.WriteLine(change.Item1 + " : ");

                                    //upload file
                                    string fullLocalPath = Path.Combine(
                                        Path.GetDirectoryName(Path.GetDirectoryName(path)), change.Item2);
                                    string fullRemotePath =
                                        Properties.Settings.Default.BackUpPath +
                                        change.Item2.Replace('\\', '/');

                                    Debug.WriteLine("   fullLocalPath " + fullLocalPath);
                                    Debug.WriteLine("   fullRemotePath " + fullRemotePath);

                                    //send file to server
                                    transferResult = session.PutFiles(
                                        fullLocalPath,
                                        fullRemotePath,
                                        false,
                                        transferOptions);
                                    // Throw on any error
                                    transferResult.Check();
                                    break;
                                }

                                // if the action was successful write to log
                                streamWriter.WriteLine(
                                    string.Format("{0};{1};{2}", DateTime.Now, change.Item1, change.Item2));
                            }
                        }
                        folderManager.saveChanges();
                        streamWriter.Close();

                        //backup filstructure to server
                        transferResult = session.PutFiles(
                            Path.Combine(Properties.Settings.Default.RunPath, "backUpManager", "logs.csv"),
                            Properties.Settings.Default.BackUpPath + "fileStructures.txt",
                            false,
                            transferOptions);
                        transferResult.Check();

                        //backup log to server
                        transferResult = session.PutFiles(
                            Path.Combine(Properties.Settings.Default.RunPath, "backUpManager", "logs.csv"),
                            Properties.Settings.Default.BackUpPath + "logs.csv",
                            false,
                            transferOptions);
                        transferResult.Check();
                    }
            }
            catch (Exception e)
            {
                ShowWindow(window, 5);
                Console.WriteLine("An exception occured: ");
                Console.WriteLine("   " + e.ToString());
                Console.WriteLine("Backup failed press any key to continue.");
                Console.ReadKey();
            }
        }
Example #24
0
    public static string FtpSend(string file, ProfileMessage message)
    {
        string Result = string.Empty;

        try
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                HostName   = message.FTPServer.Trim(),
                PortNumber = int.Parse(message.FTPPort),
                UserName   = message.FTPUser.Trim(),
                Password   = message.FTPUser.Trim()
            };
            if (message.FTPSsl)
            {
                sessionOptions.Protocol = Protocol.Sftp;
            }
            else
            {
                sessionOptions.Protocol = Protocol.Ftp;
            }
            //try
            //{
            TransferOperationResult tr;
            using (Session session = new Session())
            {
                session.Open(sessionOptions);
                if (session.Opened)
                {
                    //NodeResources.AddText(edLog, string.Format("{0:g} ", DateTime.Now) + " Connected to " + custProfile[0].P_server + ". Sending file  :" + xmlfile + Environment.NewLine + " TO " + sessionOptions.HostName + "/" + custProfile[0].P_path + "/" + Path.GetFileName(xmlfile));
                    TransferOptions tOptions = new TransferOptions();
                    tOptions.OverwriteMode       = OverwriteMode.Overwrite;
                    tOptions.ResumeSupport.State = TransferResumeSupportState.Off;

                    if (string.IsNullOrEmpty(message.P_path))
                    {
                        message.P_path = "";
                    }
                    else
                    {
                        message.P_path = message.P_path + "/";
                    }
                    tr = session.PutFiles(file, "/" + message.P_path + Path.GetFileName(file), true, tOptions);
                    //NodeResources.AddText(edLog, string.Format("{0:g} ", DateTime.Now) + " Results: ");
                    if (tr.IsSuccess)
                    {
                        Result = "File Sent Ok";
                        try
                        {
                            File.Delete(file);
                        }
                        catch (Exception ex)
                        {
                            Result = "File Sent Ok. Delete Error: " + ex.Message;
                        }
                    }
                    else
                    {
                        Result = "Failed: Transfer Result is invalid: ";
                    }
                }
                else
                {
                }
            }
        }
        catch (Exception ex)
        {
            Result = "Failed: " + ex.GetType().Name + " " + ex.Message;
        }

        return(Result);
    }
Example #25
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest webRequest = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
                    uploadOptions = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server = args[1];
                    uploadOptions.FileKey = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params = args[5];

                    bool trustAll = false;
                    bool.TryParse(args[6],out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id = args[9];
                    uploadOptions.Method = args[10];

                    uploadOptions.CallbackId = callbackId = args[11];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
                webRequest.Method = uploadOptions.Method;

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                DownloadRequestState reqState = new DownloadRequestState();
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                InProcDownloads[uploadOptions.Id] = reqState;

                webRequest.BeginGetRequestStream(uploadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId);
            }
        }
 public static Task <TransferResponse> ConsultativeTransferAsync(this Modality m, Conversation conversation, TransferOptions options)
 {
     return(Task.Factory.FromAsync(m.BeginConsultativeTransfer, result =>
     {
         ModalityState state;
         IList <string> prop;
         m.EndConsultativeTransfer(out state, out prop, result);
         return new TransferResponse {
             TargetState = state, ContextProperties = prop
         };
     }, conversation, options, null));
 }
Example #27
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest webRequest = null;
            string callbackId;

            try
            {
                // source, target, trustAllHosts, this._id, headers
                string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);

                downloadOptions = new TransferOptions();
                downloadOptions.Url = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2],out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id = optionStrings[3];
                downloadOptions.Headers = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int bytesRead = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
                    if (entry != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                      new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    // eat it
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Example #28
0
        private static void FTPExcelFiles(string databaseServerName)
        {
            try
            {
                string serverCorePath     = "";
                string fileName           = "";
                string values_environment = ConfigurationManager.AppSettings.Get("Environment");
                String SshPrivateKeyPath  = ConfigurationManager.AppSettings.Get("SshPrivateKeyPath");
                String winSCP_Path        = ConfigurationManager.AppSettings.Get("winscp_Path");

                if (values_environment == "DEV")
                {
                    fileName = ConfigurationManager.AppSettings.Get("DevFilename");
                }

                if (values_environment == "PROD")
                {
                    fileName = ConfigurationManager.AppSettings.Get("ProdFilename");
                }

                if (values_environment == "TEST")
                {
                    fileName = ConfigurationManager.AppSettings.Get("TestFilename");
                }

                //* IDHS Dev:
                if (databaseServerName.Equals(Constants.SQL_SERVER_620_21_NAME))
                {
                    serverCorePath = Constants.SFTPTestCorePath;
                }
                //* IDHS Test:
                else if (databaseServerName.Equals(Constants.SQL_SERVER_634_01_NAME))
                {
                    serverCorePath = Constants.SFTPTestCorePath;
                }
                //* IDHS Prod:
                else if (databaseServerName.Equals(Constants.SQL_SERVER_611_03_NAME))
                {
                    serverCorePath = Constants.SFTPProdCorePath;
                }
                else
                {
                    AppLog.GetAppLog().Log("Wrong database server name: " + databaseServerName);
                    AppLog.GetAppLog().HasError = true;
                    throw new Exception("Wrong database server name: " + databaseServerName);
                }


                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = Constants.SFTPHostName,
                    UserName = Constants.SFTPUserName,
                    Password = Constants.SFTPPassword,
                    SshHostKeyFingerprint = Constants.SFTPSshHostKeyFingerprint,
                    PortNumber            = Constants.SFTPPortNumber,
                    PrivateKeyPassphrase  = Constants.PrivateKeyPassphrase,
                    //SshPrivateKeyPath key file to connecto to sftp host server
                    SshPrivateKeyPath = SshPrivateKeyPath
                };

                AppLog.GetAppLog().Log("Done SFTP session options setting.");
                using (Session session = new Session())
                {
                    //* Connect
                    try
                    {
                        session.ExecutablePath = winSCP_Path;
                        session.Open(sessionOptions);
                    }
                    catch (Exception e)
                    {
                        AppLog.GetAppLog().Log("Could not open WinSCP ln 51 on program.cs " + e.Message);
                        throw new Exception(e.Message);
                    }

                    AppLog.GetAppLog().Log("Open SFTP Session...");

                    //* Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode      = TransferMode.Binary;
                    transferOptions.FilePermissions   = null;
                    transferOptions.PreserveTimestamp = false;

                    //** Upload core XML files:
                    TransferOperationResult coreTransferResult;
                    //coreTransferResult = session.PutFiles(sourceFilePath + @"CSSD_Core_*", serverCorePath, false, transferOptions);
                    coreTransferResult = session.PutFiles(fileName, serverCorePath, false, transferOptions);
                    //* Throw on any error
                    coreTransferResult.Check();
                    //* Log core results
                    bool coreFilesExisting = false;
                    foreach (TransferEventArgs transfer in coreTransferResult.Transfers)
                    {
                        coreFilesExisting = true;
                        AppLog.GetAppLog().Log("Upload file succeeded: " + transfer.FileName);
                    }
                    if (coreFilesExisting)
                    {
                        //coreTransferResult = session.PutFiles(sourceFilePath + Constants.SFTPFlagFile, serverCorePath, false, transferOptions);
                        coreTransferResult = session.PutFiles(fileName, serverCorePath, false, transferOptions);
                        AppLog.GetAppLog().Log("Uploaded file to vendor's SFTP host.");
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.GetAppLog().Log("Error: occurred in SFTP xml files.");
                AppLog.GetAppLog().Log(ex.ToString());
                AppLog.GetAppLog().HasError = true;
                throw ex;
            }

            AppLog.GetAppLog().Log("SFTP Process is done.");
        }