예제 #1
0
    public RemoteFileInfo DownloadFile(DownloadRequest request)
    {
        RemoteFileInfo result = new RemoteFileInfo();
        try
        {
            // get some info about the input file
             string filePath = System.IO.Path.Combine(@"c:\Uploadfiles", request.FileName);
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); 

            // check if exists
            if (!fileInfo.Exists) throw new System.IO.FileNotFoundException("File not found", request.FileName);

            // open stream
            System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            // return result

            result.FileName = request.FileName;
            result.Length = fileInfo.Length;
            result.FileByteStream = stream;
        }
        catch (Exception ex)
        {

        }
        return result;

     }
예제 #2
0
        public void UploadFile(RemoteFileInfo request)
        {
            try
            {
                FileGonnaGo objFileUpload = new FileGonnaGo();
                if (objFileUpload.impersonateValidUser())
                {
                    FileStream targetStream = null;
                    Stream sourceStream = request.FileByteStream;
                    string uploadFolder = objFileServerImpersonation.FileServerPath();
                    string filePath = Path.Combine(uploadFolder, request.FileName);

                    using (targetStream = new FileStream(filePath, FileMode.Create,
                                      FileAccess.Write, FileShare.None))
                    {

                        const int bufferLen = 21474833;
                        byte[] buffer = new byte[bufferLen];
                        int count = 0;
                        while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                        {
                            targetStream.Write(buffer, 0, count);
                        }
                        targetStream.Close();
                        sourceStream.Close();
                    }
                    objFileUpload.undoImpersonation();
                }
            }
            catch (Exception ex)
            {
                WCFFILESERVER.FileService.LogException(string.Empty, ex);
                throw;
            }
        }
예제 #3
0
		public void BeginDownload(RemoteFileInfo fileInfo, string destPath)
		{
			try
			{
				var localFileInfo = new FileInfo(destPath);
				if (localFileInfo.Exists)
				{
					if (Sha1VerifyFile(destPath, fileInfo.Sha1Hash))
					{
						var newEvt = new AsyncCompletedEventArgs(null, false, null);
						DownloadFileCompleted(this, newEvt);
						return; //already have the file with correct contents on disk
					}
				}
			}
			catch (Exception ex)
			{
				var newEvt = new AsyncCompletedEventArgs(ex, false, null);
				DownloadFileCompleted(this, newEvt);
				return; //something failed when trying to hash file
			}

			if (_wc != null)
			{
				_wc.CancelAsync();
				_wc.Dispose();
				_wc = null;
			}

			_wc = new CustomWebClient(Timeout);
			_wc.DownloadProgressChanged += (sender, evt) => { DownloadProgressChanged(sender, evt); };
			_wc.DownloadFileCompleted += (sender, evt) =>
			{
				using (var wc = (WebClient) sender)
				{
					if (evt.Cancelled || evt.Error != null)
					{
						DownloadFileCompleted(sender, evt);
						return;
					}

					try
					{
						if (!Sha1VerifyFile(destPath, fileInfo.Sha1Hash))
							throw new Exception("Hash mismatch after download");
					}
					catch (Exception ex)
					{
						var newEvt = new AsyncCompletedEventArgs(ex, false, evt.UserState);
						DownloadFileCompleted(sender, newEvt);
						return;
					}

					DownloadFileCompleted(sender, evt);
				}
				_wc = null;
			};

			_wc.DownloadFileAsync(new Uri(fileInfo.Url), destPath);
		}
        public Stream CreateStream(RemoteFileInfo remoteFileInfo)
        {
            if (remoteFileInfo == null) throw new ArgumentNullException("remoteFileInfo");

            LocalFileInfo localFileInfo = m_LocalFileAllocator.AllocateFile(remoteFileInfo.FileName, remoteFileInfo.FileSize);
            return new FileStream(localFileInfo.FileName, FileMode.Open, FileAccess.Write);
        }
        public void UploadFile(RemoteFileInfo request)
        {
            // kill target file, if already exists
            string filePath = Path.Combine(Constants.GetCurrentDirectoryPath, Constants.DB_NAME);
            if (File.Exists(filePath)) File.Delete(filePath);

            const int chunkSize = 2048;
            var buffer = new byte[chunkSize];

            using (var writeStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
            {
                do
                {
                    // read bytes from input stream
                    int bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize);
                    if (bytesRead == 0) break;

                    // write bytes to output stream
                    writeStream.Write(buffer, 0, bytesRead);
                } while (true);

                writeStream.Close();
            }

            if (DatabaseChanged != null)
            {
                DatabaseChanged.Invoke(null, null);
            }
        }
 public override List<CalculatedFileSegment> GetCalculatedSegments(
     int segmentCount, 
     RemoteFileInfo remoteFileInfo, 
     long calculatedSegmentSize, 
     long residueBytes)
 {
     return base.GetCalculatedSegments(segmentCount, remoteFileInfo, calculatedSegmentSize, residueBytes);
 }
 public override long CalculateResidueBytes(int segmentCount, RemoteFileInfo remoteFileInfo, long calculatedSegmentSize)
 {
     if (remoteFileInfo != null)
     {
         return remoteFileInfo.FileSize - (calculatedSegmentSize * segmentCount);
     }
     else
     {
         return 0;
     }
 }
        public RemoteFileInfo GetRemoteFileInfo(DownloadFileInfo file)
        {
            RemoteFileInfo remoteFileInfo = new RemoteFileInfo();
            WebRequest webRequest = m_WebRequestManager.GetWebRequest(file);
            webRequest.Method = "HEAD";

            HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
            remoteFileInfo.LastModified = httpWebResponse.LastModified;
            remoteFileInfo.MimeType = httpWebResponse.ContentType;
            remoteFileInfo.FileSize = httpWebResponse.ContentLength;
            remoteFileInfo.AcceptRanges = string.Compare(httpWebResponse.Headers["Accept-Ranges"], "bytes", StringComparison.OrdinalIgnoreCase) == 0;

            return remoteFileInfo;
        }
예제 #9
0
        public void SaveAll()
        {
            foreach (EntryBlock entry in spData.Children)
            {
                if (entry.isModified)
                {
                    byte[] encrypted = CryptoLibrary.encrypt28147cfb(currentUser.MasterKey, entry.Source.Serialize());
                    IFileTransfer clientUpload = new FileTransferClient();
                    RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();

                    using (MemoryStream stream = new MemoryStream(encrypted))
                    {
                        uploadRequestInfo.FileName = entry.Source.FileName;
                        uploadRequestInfo.Length = encrypted.Length;
                        uploadRequestInfo.FileByteStream = stream;
                        clientUpload.UploadFile(uploadRequestInfo);
                    }
                }
            }
        }
        public RemoteFileInfo GetRemoteFileInfo(DownloadFileInfo file)
        {
            RemoteFileInfo remoteFileInfo = new RemoteFileInfo();
            remoteFileInfo.AcceptRanges = true;

            FtpWebRequest request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);
            request.Method = WebRequestMethods.Ftp.GetFileSize;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                remoteFileInfo.FileSize = response.ContentLength;
            }

            request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                remoteFileInfo.LastModified = response.LastModified;
            }

            return remoteFileInfo;
        }
        public RemoteFileInfo DownloadFile(DownloadRequest request)
        {
            // get some info about the input file
            string filePath = Path.Combine(Constants.GetCurrentDirectoryPath,Constants.DB_NAME);
            var fileInfo = new FileInfo(filePath);

            // check if exists
            if (!fileInfo.Exists) throw new FileNotFoundException("File not found", Constants.DB_NAME);

            // open stream
            var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            // return result
            var result = new RemoteFileInfo
                             {
                                 FileName = Constants.DB_NAME,
                                 Length = fileInfo.Length,
                                 FileByteStream = stream
                             };
            return result;

            // after returning to the client download starts. Stream remains open and on server and the client reads it, although the execution of this method is completed.
        }
예제 #12
0
    public void UploadFile(RemoteFileInfo request)
    {
        FileStream targetStream = null;
        Stream sourceStream =  request.FileByteStream;

        string uploadFolder = @"C:\upload\";
         string filePath = Path.Combine(uploadFolder, request.FileName); 

        using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            //read from the input stream in 6K chunks
            //and save to output stream
            const int bufferLen = 65000; 
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
            {
                targetStream.Write(buffer, 0, count);
            }
            targetStream.Close();
            sourceStream.Close();
        }

    }
예제 #13
0
    string IVO_Upload.UploadFile(RemoteFileInfo request)
    {
        string _uploadFolder = "PATH_TO_SAVE_FILE";
        string filePath      = Path.Combine(_uploadFolder, request.FileName);

        using (targetStream = new FileStream(filePath, FileMode.Create,
                                             FileAccess.Write, FileShare.None))
        {
            //read from the input stream in 65000 byte chunks

            const int bufferLen = 65000;
            byte[]    buffer    = new byte[bufferLen];
            int       count     = 0;
            while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
            {
                // save to output stream
                targetStream.Write(buffer, 0, count);
            }

            targetStream.Close();
            sourceStream.Close();
        }
        return("details");                            // return whatever you need to here, or change the return type to whatever you need
    }
예제 #14
0
 public void UploadFile(RemoteFileInfo request)
 {
     throw new NotImplementedException();
 }
 public DownloadTaskFinishedEventMessage(IDownloadTask downloadTask, Stream downloadStream, RemoteFileInfo remoteFileInfo)
 {
     DownloadTask = downloadTask;
     RemoteFileInfo = remoteFileInfo;
     DownloadStream = downloadStream;
 }
예제 #16
0
        /// <summary>
        /// Transfiere un archivo desde el servidor al dispositivo.
        /// </summary>
        /// <param name="fileName">
        /// El nombre del archivo a transferrir
        /// </param>
        public static void TransferFile(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException(
                          global::PresentationLayer.GeneralResources.FileNameNullArgument);
            }

            LastSyncDataAccess syncDataAccess = new LastSyncDataAccess();

            // Crear el servicio de transferencia
            FileTransferServiceClient fileTransfer = new
                                                     FileTransferServiceClient(BaseForm.ServerBinding,
                                                                               new EndpointAddress(UtnEmall.Client.SmartClientLayer.Connection.ServerUri + "FileTransferService"));

            // Cargar la información de sincronización
            Collection <LastSyncEntity> results = syncDataAccess.LoadWhere("entityName", fileName.Substring(fileName.LastIndexOf(@"\", StringComparison.Ordinal) + 1), false, OperatorType.Equal);

            DownloadRequest request = new DownloadRequest();

            request.FileName = Path.GetFileName(fileName);

            if (results.Count > 0)
            {
                request.FileDateTime = results[0].LastTimestamp.Ticks.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                request.FileDateTime = DateTime.MinValue.Ticks.ToString(CultureInfo.InvariantCulture);
            }

            if (!File.Exists(Path.Combine(Utilities.AppPath, fileName)))
            {
                request.FileDateTime = DateTime.MinValue.Ticks.ToString(CultureInfo.InvariantCulture);
            }

            // Realizar la transferencia
            RemoteFileInfo returnInfo = null;

            try
            {
                returnInfo = fileTransfer.DownloadFile(request, UtnEmall.Client.SmartClientLayer.Connection.Session);
            }
            catch (TargetInvocationException)
            {
                BaseForm.ShowErrorMessage(
                    global::PresentationLayer.GeneralResources.TargetInvocationExceptionMessage,
                    global::PresentationLayer.GeneralResources.ErrorTitle);
                return;
            }
            catch (CommunicationException)
            {
                BaseForm.ShowErrorMessage(
                    global::PresentationLayer.GeneralResources.CommunicationException,
                    global::PresentationLayer.GeneralResources.ErrorTitle);
                return;
            }
            FileStream writer = null;

            if (returnInfo != null)
            {
                fileName = Path.Combine(Utilities.AppPath, fileName);
                // Guardar el archivo a disco
                try
                {
                    writer = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                    writer.Write(returnInfo.FileByteStream, 0, returnInfo.FileByteStream.Length);

                    // Guardar la información para futuras sincronizaciones
                    LastSyncEntity fileSync = new LastSyncEntity();
                    fileSync.EntityName    = returnInfo.FileName;
                    fileSync.LastTimestamp = new DateTime(Convert.ToInt64(returnInfo.FileDateTime, CultureInfo.InvariantCulture));
                    if (File.Exists(fileName) && results.Count > 0)
                    {
                        fileSync.Id      = results[0].Id;
                        fileSync.IsNew   = false;
                        fileSync.Changed = true;
                    }
                    syncDataAccess.Save(fileSync);
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
            }
        }
예제 #17
0
        public TResult <bool> UploadRedLinesAddiotionalFiles(string filename, System.IO.Stream stream)
        {
            System.Diagnostics.Debug.Assert(false);
            try
            {
                string user        = System.Web.HttpContext.Current.Request.Headers["user"];
                string project     = System.Web.HttpContext.Current.Request.Headers["projectname"];
                string layer       = System.Web.HttpContext.Current.Request.Headers["layer"];
                string uid         = System.Web.HttpContext.Current.Request.Headers["owner"];
                string description = System.Web.HttpContext.Current.Request.Headers["description"];
                string extension   = System.Web.HttpContext.Current.Request.Headers["extension"];

                LogHandler.WriteLog("Service.cs: UploadRedLinesAddiotionalFiles.  : Starting" + filename, EventLogEntryType.Information);
                //var parser = new HttpMultipartParser.MultipartFormDataParser(stream);
                var parser = new HttpMultipartParser.StreamingMultipartFormDataParser(stream);
                parser.ParameterHandler += parameter => { };
                // Write the part of the file we've recieved to a file stream. (Or do something else)

                filename = filename + "." + extension;
                LogHandler.WriteLog("Service.cs: UploadRedLinesAddiotionalFiles.  : Creating File " + filename, EventLogEntryType.Information);
                var write = File.OpenWrite("c:\\temp\\" + filename);


                //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                IServiceContract m_ComosAPIService = GetComosAPI();


                parser.FileHandler += (name, fileName, type, disposition, buffer, bytes) =>
                {
                    LogHandler.WriteLog("   Service.cs: UploadRedLinesAddiotionalFiles.  : Write block to File " + filename, EventLogEntryType.Information);
                    write.Write(buffer, 0, bytes);
                };
                parser.StreamClosedHandler += () =>
                {
                    LogHandler.WriteLog("   Service.cs: UploadRedLinesAddiotionalFiles.  :  File stream closed" + filename, EventLogEntryType.Information);
                    // Do things when my input stream is closed
                    write.Flush();
                    write.Close();
                    write.Dispose();

                    using (var reader = System.IO.File.OpenRead("c:\\temp\\" + filename))
                    {
                        RemoteFileInfo fileInfo = new RemoteFileInfo()
                        {
                            FileByteStream = reader,
                            Project        = project,
                            User           = user,
                            Owner          = uid,
                            Workinglayer   = layer,
                            FileName       = filename,
                            Extension      = extension,
                            Description    = description,
                        };
                        m_ComosAPIService.CreateRedLinesAndAditionalDocuments(fileInfo);
                    }
                };
                parser.Run();
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog("Service.cs: UploadRedLinesAddiotionalFiles.  : Exception = " + ex.Message, EventLogEntryType.Error);

                return(new TResult <bool>()
                {
                    Status = false,
                    Message = ex.Message,
                    data = false
                });
            }
            //return null;
            return(new TResult <bool>()
            {
                data = true,
                Status = true,
            });
        }
예제 #18
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="RemoteAddress">远程服务地址,需要从client中获取</param>
        /// <param name="filePath">本地保存路径,不带文件名</param>
        /// <param name="fileName">需要下载的文件名(远程)</param>
        void backgroundDownloadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                FileTransferInfo fileTranserInfo = e.Argument as FileTransferInfo;
                var fileManger = Common.ServiceBroker.FindService <IFileTransferService>(fileTranserInfo.remoteAddress); //创建WCF带来

                LogText("Start");

                // kill target file, if already exists
                string localFilePath = System.IO.Path.Combine(fileTranserInfo.localPath, fileTranserInfo.fileName);
                if (System.IO.File.Exists(localFilePath))
                {
                    System.IO.File.Delete(localFilePath);
                }

                // get stream from server
                DownloadRequest downloadRequest = new DownloadRequest();
                downloadRequest.FilePath = fileTranserInfo.serverPath;
                downloadRequest.FileName = fileTranserInfo.fileName;

                RemoteFileInfo downloadFileInfo = fileManger.DownloadFile(downloadRequest);
                long           length           = downloadFileInfo.Length;

                // write server stream to disk
                using (System.IO.FileStream writeStream = new System.IO.FileStream(localFilePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
                {
                    byte[] buffer;
                    //获取所用块压缩流,并组装
                    while (fileManger.ReadNextBuffer())
                    {
                        // read bytes from input stream
                        buffer = fileManger.GetCurrentBuffer();

                        // write bytes to output stream
                        writeStream.Write(buffer, 0, buffer.Length);

                        // report progress from time to time
                        int Value = (int)(writeStream.Position * 100 / length);

                        (sender as BackgroundWorker).ReportProgress(Value);
                        if (this.backgroundDownloadWorker.CancellationPending)
                        {
                            writeStream.Close();
                            return;
                        }
                    }


                    // report end of progress
                    LogText("Done!");

                    writeStream.Close();
                }
            }
            catch (System.Exception ex)
            {
                LogText("Exception : " + ex.Message);
                if (ex.InnerException != null)
                {
                    LogText("Inner Exception : " + ex.InnerException.Message);
                }
            }
        }
예제 #19
0
		public static void DownloadWithStatusDots(RemoteFileInfo fileInfo, string destPath, string initialStatus,
			StatusChangeString statusCb, StatusDownloadComplete finishCb)
		{
			using (var downloadingEvt = new ManualResetEvent(false))
			{
				string updateInfoString = initialStatus.Replace("...", String.Empty);
				statusCb(updateInfoString);

				var wc = new HashWebClient();
				wc.DownloadFileCompleted += (source, evt) =>
				{
					if (evt.Cancelled)
						statusCb("Async operation cancelled");
					else if (evt.Error != null)
						statusCb(evt.Error.Message);
					else
					{
						try
						{
							if (finishCb != null)
								finishCb(wc, fileInfo, destPath);
						}
						catch (Exception ex)
						{
							statusCb(ex.Message);
						}
					}
					downloadingEvt.Set();
				};
				wc.BeginDownload(fileInfo, destPath);

				int numDots = 0;
				uint loops = 0;
				while (downloadingEvt.WaitOne(10) == false)
				{
					if (loops >= 10)
					{
						numDots = (numDots + 1)%3;
						statusCb(updateInfoString + new String('.', numDots));
						loops = 0;
					}

					loops++;
				}
				if (wc != null)
				{
					wc.Dispose();
					wc = null;
				}
			}
		}
예제 #20
0
 public Stream CreateStream(RemoteFileInfo remoteFileInfo)
 {
     return(new MemoryStream());
 }
예제 #21
0
        public static int Main(string[] args)
        {
            //connectToDb();
            Console.WriteLine("Let's reorganize some files!");

            try
            {
                // Setup session
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ConfigurationManager.AppSettings["hostName"],
                    UserName = ConfigurationManager.AppSettings["userName"],
                    Password = ConfigurationManager.AppSettings["password"],
                    SshHostKeyFingerprint = ConfigurationManager.AppSettings["sshHostKeyFingerprint"]
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);
                    Console.WriteLine("Connected to session.");
                    // TODO: make source path editable
                    String path = "/home/cetus/shared/HARP Deployment and Recovery Files";
                    Console.WriteLine("Source path is {0}", path);
                    RemoteDirectoryInfo   directory   = session.ListDirectory(path);
                    List <RemoteFileInfo> sourceFiles = new List <RemoteFileInfo>(); // to hold file names that will be sorted
                    foreach (RemoteFileInfo fileInfo in directory.Files)
                    {
                        if (!(Regex.IsMatch(fileInfo.Name, @"^\.")) && !(Regex.IsMatch(fileInfo.Name, @"^\d")) && fileInfo.IsDirectory)
                        {
                            sourceFiles.Add(fileInfo);
                        }
                    }
                    Console.WriteLine("Files found, processing and sorting.");

                    // Sort files alphabetically
                    sourceFiles.Sort(delegate(RemoteFileInfo x, RemoteFileInfo y)
                    {
                        if (x.Name == null && y.Name == null)
                        {
                            return(0);
                        }
                        else if (x.Name == null)
                        {
                            return(-1);
                        }
                        else if (y.Name == null)
                        {
                            return(1);
                        }
                        else
                        {
                            return(y.Name.CompareTo(x.Name));
                        }
                    });

                    // Destination path of where the directories holding the targets willbe temporarily held until transferred back to session
                    String destPath = "C:/Users/Harp/Desktop/temp";
                    // TODO: make destination path editable
                    Console.WriteLine("Destination path is {0}", destPath);
                    FileTransferManager fileTransfer = new FileTransferManager(path, destPath, session);
                    Boolean             doneTargets  = false;
                    while (!doneTargets)
                    {
                        Console.WriteLine("Create new target? (Y/N)");
                        String response = Console.ReadLine();
                        switch (response)
                        {
                        case "Y":
                            fileTransfer.createNewTarget();
                            break;

                        case "N":
                            doneTargets = true;
                            break;

                        default:
                            break;
                        }
                    }
                    Boolean done = false;
                    int     i    = 0;
                    while (!done)
                    {
                        Console.WriteLine("[E]xit [Y]es [Any key to continue]");
                        RemoteFileInfo aSourceFile = sourceFiles[i];
                        Console.WriteLine("Would you like to organize {0}(Y/N)?", aSourceFile.Name);
                        String answer = Console.ReadLine();
                        switch (answer)
                        {
                        case "Y":
                            fileTransfer.setCurrentTransferSrc(aSourceFile);     // set the path to the current source
                            fileTransfer.checkDestinationDir();                  // set path to destination of transfer
                            fileTransfer.setTargetSrcPaths();                    // set the paths of the targets
                            fileTransfer.configureTargetRules();                 // configure target rules
                            fileTransfer.transferTargets();                      // transfer the target files
                            break;

                        case "N":
                            break;

                        case "E":
                            done = true;
                            break;

                        default:
                            continue;
                        }
                        i++;
                    }
                    return(0);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error: {0}", e);
                return(1);
            }
        }
        public static bool InternalDownload(BackgroundWorker backgroundWorker, string conversionStringTemplate,
                                            string videoFile, string targetFile, string targetTmpFile,
                                            out long resultSize)
        {
            bool   flag   = false;
            long   num    = 0L;
            Stream stream = null;
            string item   = ApplicationSettings.Instance.UseIndirectConversion ? targetTmpFile : targetFile;

            try
            {
                RemoteFileInfo remoteResource = HttpUtility.GetRemoteResource(new ResourceLocation(videoFile),
                                                                              out stream);
                backgroundWorker.ReportProgress(0, 0x7fffffff);
                FileGarbageCollector.Instance.Add(item);
                long ticks = DateTime.Now.Ticks;
                backgroundWorker.ReportProgress(0, "Downloading");
                using (Stream stream2 = new FileStream(item, FileMode.Create))
                {
                    int count = 0;
                    do
                    {
                        Application.DoEvents();
                        if (backgroundWorker.CancellationPending)
                        {
                            resultSize = num;
                            return(true);
                        }
                        var buffer = new byte[0x4000];
                        count = stream.Read(buffer, 0, 0x4000);
                        if (count > 0)
                        {
                            stream2.Write(buffer, 0, count);
                            num += count;
                            long num4 = (num * 0x7fffffffL) / remoteResource.FileSize;
                            long num5 = DateTime.Now.Ticks - ticks;
                            if (num5 > 0L)
                            {
                                backgroundWorker.ReportProgress((num4 <= 0x7fffffffL) ? ((int)num4) : 0x7fffffff,
                                                                ((num * 0x989680L) / num5) / 0x400L);
                            }
                            else
                            {
                                backgroundWorker.ReportProgress((num4 <= 0x7fffffffL) ? ((int)num4) : 0x7fffffff, null);
                            }
                        }
                    } while (count > 0);
                }
                resultSize = num;
                FileGarbageCollector.Instance.Remove(item);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                backgroundWorker.ReportProgress(0x7fffffff, Messages.DownloadCompleted);
            }
            if ((conversionStringTemplate != null) && ApplicationSettings.Instance.UseIndirectConversion)
            {
                FileGarbageCollector.Instance.Add(item);
                string str2 = item + ".tmp";
                FileGarbageCollector.Instance.Add(str2);
                string arguments = string.Format(conversionStringTemplate, item, str2);
                var    info2     = new ProcessStartInfo("ffmpeg.exe", arguments)
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    WorkingDirectory       = Path.GetDirectoryName(Application.StartupPath),
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true
                };
                var process = new Process
                {
                    StartInfo = info2
                };
                int userState = 0;
                FileGarbageCollector.Instance.Add(targetFile);
                try
                {
                    backgroundWorker.ReportProgress(0, "Converting");
                    process.Start();
                    long         num1            = DateTime.Now.Ticks;
                    StreamReader standardError   = process.StandardError;
                    int          percentProgress = 0;
                    do
                    {
                        Application.DoEvents();
                        string str = standardError.ReadLine();
                        Application.DoEvents();
                        if (str.Contains("Duration: "))
                        {
                            TimeSpan span;
                            if (TimeSpan.TryParse(TextUtil.JustAfter(str, "Duration: ", ","), out span))
                            {
                                userState = (int)span.TotalSeconds;
                                backgroundWorker.ReportProgress(0, userState);
                            }
                        }
                        else
                        {
                            int num8;
                            if ((str.Contains("size=") && str.Contains("time=")) &&
                                int.TryParse(TextUtil.JustAfter(str, "time=", "."), out num8))
                            {
                                //percentProgress = (num8 <= this.progressIndicator.Maximum) ? num8 : this.progressIndicator.Maximum;
                            }
                        }
                        backgroundWorker.ReportProgress(percentProgress, userState);
                        if (backgroundWorker.CancellationPending)
                        {
                            process.Kill();
                            process.Close();
                            process.Dispose();
                            flag = true;
                        }
                    } while (!standardError.EndOfStream);
                    process.WaitForExit();
                    if (!backgroundWorker.CancellationPending)
                    {
                        int exitCode = process.ExitCode;
                    }
                    else
                    {
                        flag = true;
                    }
                    File.Move(str2, targetFile);
                    FileGarbageCollector.Instance.Remove(targetFile);
                }
                catch (Exception exception)
                {
                    try
                    {
                        process.Kill();
                    }
                    catch
                    {
                    }
                    try
                    {
                        process.Close();
                    }
                    catch
                    {
                    }
                    try
                    {
                        process.Dispose();
                    }
                    catch
                    {
                    }
                    string message = exception.Message;
                }
            }
            resultSize = num / 0x400L;
            return(flag);
        }
예제 #23
0
        //code principal backgroundworker
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //modpack que l'on shouaite lancer
            pak = (ModPacks)e.Argument;

            //ClientVersion: version du modpack côté client
            //SrvVersion: version du modpack sur le serveur
            string ClientVersion, SrvVersion;

            //path: chemin relatif du modpack (par rapport au dossier instances)
            string Path = pak.Path;

            //InstancePath: chemin absolu du modpack
            string InstancePath = InstancesPath() + pak.Path;

            //contenu du fichier version.txt
            string data;

            this.Dispatcher.Invoke(() =>
            {
                PB_Progress.IsIndeterminate = true;
            });

            //récupère la version du modpack côté client, si elle existe. sinon met -1
            if (File.Exists(InstancePath + "\\version.txt"))
            {
                data = File.ReadAllText(InstancePath + "\\version.txt");
                var isNumeric = int.TryParse(data, out int n);
                if (isNumeric)
                {
                    ClientVersion = data;
                }
                else
                {
                    ClientVersion = "-1";
                }
            }
            else
            {
                ClientVersion = "-1";
            }

            if (!InternetAccess && pak.Version == "-1")
            {
                MessageBox.Show("impossible de lancer le modpack car ce dernier n'est pas complet.");
                Debug2("impossible de lancer le modpack car ce dernier n'est pas complet.");
                error = true;
                return; //dans le cas ou internet n'est pas accessible et que le internet n'est pas dispo, on quite la fonction.
            }

            SrvVersion = pak.Version;

            this.Dispatcher.Invoke(() =>
            {
                PB_Progress.IsIndeterminate = false;
            });

            //si la version serveur et client sont identique, on quite la fonction pour lancer le jeu.
            if (ClientVersion == SrvVersion)
            {
                return; //quite la fonction
            }


            if (InternetAccess)
            {
                try
                {
                    Debug2("Connection SFTP");
                    using (Session session = new Session()) //note: il n'y a pas besoin de demander explicitement de fermer la connection car la sorti de using le fait automatiquement
                    {
                        //event que winscp déclenche lorsqu'il y a du progret dans le téléchargement
                        session.FileTransferProgress += Session_FileTransferProgress;

                        //Connection
                        session.Open(sessionOptions);

                        Debug2("Téléchargement modpack");

                        if (pak.Folders != null)
                        {
                            ct    = 0;
                            ctmax = pak.Folders.Length;
                            foreach (JValue a in pak.Folders)
                            {
                                string i;
                                i = a.ToString();
                                Debug2("Début téléchargement dossier: from [" + InstanceSrvPath + Path + "/" + i + "] to [" + InstancePath + "\\" + i.Replace("/", "\\") + "]");
                                if (!Directory.Exists(InstancePath + "\\" + i.Replace("/", "\\")))
                                {
                                    Directory.CreateDirectory(InstancePath + "\\" + i.Replace("/", "\\"));
                                }
                                session.SynchronizeDirectories(SynchronizationMode.Local, InstancePath + "\\" + i.Replace("/", "\\") + "\\", InstanceSrvPath + Path + "/" + i + "/", true, true);
                                ct++;
                            }
                        }
                        else
                        {
                            Debug2("pas de dossier définie en MAJ");
                        }

                        if (pak.Files != null)
                        {
                            ct    = 0;
                            ctmax = pak.Files.Length;
                            foreach (JValue a in pak.Files)
                            {
                                string i;
                                i = a.ToString();
                                Debug2("Début téléchargement fichier: from [" + InstanceSrvPath + Path + "/" + i + "] to [" + InstancePath + "\\" + i.Replace("/", "\\") + "]");
                                if (session.FileExists(InstanceSrvPath + Path + "/" + i))
                                {
                                    RemoteFileInfo fichier = session.GetFileInfo(InstanceSrvPath + Path + "/" + i);
                                    if (fichier.LastWriteTime > File.GetLastWriteTime(InstancePath + "\\" + i.Replace("/", "\\")))
                                    {
                                        session.GetFiles(InstanceSrvPath + Path + "/" + i, InstancePath + "\\" + i.Replace("/", "\\"));
                                    }
                                    else
                                    {
                                        Debug2("skipped (version local plus récente ou version serveur inchangé)");
                                    }
                                }
                                else
                                {
                                    Debug2("fichier absent coté serveur (" + i + ")");
                                }
                                ct++;
                            }
                        }
                        else
                        {
                            Debug2("pas de fichier définie en MAJ");
                        }

                        File.WriteAllText(InstancePath + "\\version.txt", pak.Version);
                    }
                }
                catch (Exception f)
                {
                    MessageBox.Show("Erreur lors du téléchargement des fichiers \n" + f.ToString());
                    Debug2("Erreur lors du téléchargement des fichiers \n" + f.ToString());
                    error = true;
                }
            }
            else
            {
                if (!File.Exists(InstancePath + "\\run.bat"))
                {
                    MessageBox.Show("pas de fichier executable pour le modpack");
                    Debug2("pas de fichier executable pour le modpack (run.bat not found at " + InstancePath + "\\run.bat" + ")");
                    error = true;
                }
            }
        }
예제 #24
0
 public void UploadFiles(RemoteFileInfo request)
 {
     FileUploader.Upload(request);
 }
예제 #25
0
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            IFileTransfer proxy = new FileTransferClient();
            RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();

            Entry entry = new Entry(entrys, "Name", "", "");
            byte[] bEntry = entry.Serialize();

            string path = proxy.AddNewFile(currentUser.UserName, bEntry);
            if (path == null || path == "")
            {
                return;
            }

            entrys.Deserialize(path, bEntry);
            byte[] encrypted = CryptoLibrary.encrypt28147cfb(currentUser.MasterKey, entry.Serialize());

            using (MemoryStream stream = new MemoryStream(encrypted))
            {
                uploadRequestInfo.FileName = path;
                uploadRequestInfo.Length = encrypted.Length;
                uploadRequestInfo.FileByteStream = stream;
                proxy.UploadFile(uploadRequestInfo);
            }
        }
예제 #26
0
 public FtpFileSystemItem AddChild(RemoteFileInfo inf)
 {
     return(AddChild(new FtpFileSystemItem(inf)));
 }
 public DownloadTaskFinishedEventMessage(IDownloadTask downloadTask, Stream downloadStream, RemoteFileInfo remoteFileInfo)
 {
     DownloadTask   = downloadTask;
     RemoteFileInfo = remoteFileInfo;
     DownloadStream = downloadStream;
 }
예제 #28
0
        private void addFileButton_Click(object sender, EventArgs e)
        {
            if (mComplexKey != null)
            {
                string unencryptedFilepath = "";
                var    fileDialog          = new OpenFileDialog();
                fileDialog.Title = "Выбор файла";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    unencryptedFilepath = fileDialog.FileName;
                    var server = new NavigatorIServiceClient();
                    RemoteFileInfo
                           uploadRequestInfo = new RemoteFileInfo();
                    string encryptedFilename = AppDomain.CurrentDomain.BaseDirectory + "\\" +
                                               unencryptedFilepath.Substring(unencryptedFilepath.LastIndexOf('\\') + 1);
                    Crypto.AES_Encrypt(unencryptedFilepath, encryptedFilename, mComplexKey);

                    using (System.IO.FileStream streamEncrypted =
                               new System.IO.FileStream(encryptedFilename,
                                                        System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        FileInfo fiUnencrypted = new FileInfo(unencryptedFilepath);
                        uploadRequestInfo.mMetaFile            = new FilesystemObject();
                        uploadRequestInfo.mMetaFile.mIsDirFlag = false;
                        uploadRequestInfo.mMetaFile.mFilepath  = mCurrDirectoryData.currPath + "\\" + fiUnencrypted.Name;
                        uploadRequestInfo.mMetaFile.mFilesize  = (int)fiUnencrypted.Length;
                        // Subject control info
                        uploadRequestInfo.mMetaFile.mUid          = mUserID;
                        uploadRequestInfo.mMetaFile.mGid          = -1;
                        uploadRequestInfo.mMetaFile.mAccessBitset =
                            OWNER_MASK | GROUP_MASK;

                        uploadRequestInfo.mFileByteStream = streamEncrypted;


                        OperationResult result       = new OperationResult();
                        int             resultFileId = -1;
                        resultFileId = server.AddFile(uploadRequestInfo.mMetaFile,
                                                      uploadRequestInfo.mFileByteStream, out result);
                        if (result != null && result.mErrCode == 0)
                        {
                            var resp = server.GetListOfData(mUserID, mCurrDirectoryData.currPath);
                            if (resp != null && resp.mResult.mErrCode == 0)
                            {
                                RefreshListView(resp);
                            }
                            else if (resp != null)
                            {
                                MessageBox.Show(resp.mResult.mErrMessage);
                            }
                        }
                    }

                    FileInfo fi2 = new FileInfo(encryptedFilename);
                    fi2.Delete();
                    server.Close();
                }
            }
            else   // choose key or generate new
            {
                MessageBox.Show("Не выбран ключ шифрования!");
                if (setKey())
                {
                    addFileButton_Click(sender, e);
                }
                else
                {
                    return;
                }
            }
        }
예제 #29
0
        void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region cheking



                if (ofd.FileName == null || ofd.FileName == "")
                {
                    System.Windows.MessageBox.Show("Browse the File to Upload");
                    txtUpload.Focus();
                    return;
                }
                if (cmbAssembly.SelectedItem == null)
                {
                    System.Windows.MessageBox.Show("Select the Assembly File");
                    cmbAssembly.Focus();
                    return;
                }
                if (cmbClass.SelectedItem == null)
                {
                    System.Windows.MessageBox.Show("Select the Class Name");
                    cmbClass.Focus();
                    return;
                }
                if (txtModule.Text == "" || txtModule.Text == null)
                {
                    System.Windows.MessageBox.Show("Enter Module Name");
                    txtModule.Focus();
                    return;
                }

                if (!new ClsModuleLogic().ModuleExists(txtModule.Text))
                {
                    System.Windows.MessageBox.Show("Specify another module name");
                    txtModule.Focus();
                    return;
                }

                if (!IsVersionValid())
                {
                    System.Windows.MessageBox.Show("Enter Valid Version Number");
                    txtVersion.Focus();
                    return;
                }

                #endregion

                try
                {
                    DirectoryInfo diZip = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Zip Files");

                    File.Copy(ofd.FileName, diZip.FullName + "\\" + ofd.SafeFileName);


                    DirectoryInfo diModule         = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Modules");
                    VMukti.ZipUnzip.Zip.FastZip fz = new VMukti.ZipUnzip.Zip.FastZip();
                    if (!Directory.Exists(diModule.FullName + "\\" + ofd.SafeFileName.Split('.')[0]))
                    {
                        fz.ExtractZip(diZip.FullName + "\\" + ofd.SafeFileName, diModule.FullName, null);
                    }


                    //    Upload the Zip file To bs

                    System.IO.FileStream stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    RemoteFileInfo rfiUpload = new RemoteFileInfo();
                    rfiUpload.FileName          = ofd.SafeFileName;
                    rfiUpload.FolderNameToStore = "";
                    rfiUpload.FileByteStream    = stream;
                    rfiUpload.Length            = stream.Length;
                    clientHttpChannelFileTransfer.svcHTTPFileTransferServiceUploadFile(rfiUpload);
                    stream.Flush();
                    stream.Close();
                    FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    rfiUpload.FileByteStream = fs;
                    clientHttpChannelFileTransfer.svcHTTPFileTransferServiceUploadFileToInstallationDirectory(rfiUpload);
                    fs.Flush();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show("The Zip File is already uploaded please select another File");
                    VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "btnSubmit_Click()", "Controls\\CtlUploadModule.xaml.cs");
                    return;
                }

                ClsModuleLogic cml = new ClsModuleLogic();
                TextRange      tr  = new TextRange(rtbDescription.Document.ContentStart, rtbDescription.Document.ContentEnd);


                #region Creating byte array of imagefile
                List <byte[]> ImageByte = new List <byte[]>();

                if (!string.IsNullOrEmpty(txtModuleImage.Text))
                {
                    byte[] b = SetImage(txtModuleImage.Text);
                    if (b != null)
                    {
                        ImageByte.Add(b);
                    }
                    else
                    {
                        b = SetImage(AppDomain.CurrentDomain.BaseDirectory + "\\Skins\\Images\\Help.png");
                        if (b != null)
                        {
                            ImageByte.Add(b);
                        }
                    }
                }
                else
                {
                    byte[] b = SetImage(AppDomain.CurrentDomain.BaseDirectory + "\\Skins\\Images\\Help.png");
                    if (b != null)
                    {
                        ImageByte.Add(b);
                    }
                }
                #endregion

                int intModId = -1;

                intModId = cml.AddModule(-1, txtModule.Text, txtVersion.Text, tr.Text, ((ComboBoxItem)cmbAssembly.SelectedItem).Content.ToString(), ((ComboBoxItem)cmbClass.SelectedItem).Content.ToString(), txtZip.Text, 1, ckbCollaborate.IsChecked.Value, ckbAuthentication.IsChecked.Value, ImageByte[0]);

                if (intModId == -1)
                {
                    System.Windows.MessageBox.Show("Report this error to your administrator");
                    return;
                }
                ClsPermissionLogic cpl = new ClsPermissionLogic();

                foreach (object chk in grid1.Children)
                {
                    if (chk.GetType() == typeof(System.Windows.Controls.CheckBox) && ((System.Windows.Controls.CheckBox)chk).Tag != null)
                    {
                        int      i             = 0;
                        string[] strPermission = (((System.Windows.Controls.CheckBox)chk).Tag).ToString().Split(',');

                        for (i = 0; i < objModulePermissions.Count; i++)
                        {
                            if (objModulePermissions[i].PermissionName == strPermission[0])
                            {
                                break;
                            }
                        }
                        if (i == objModulePermissions.Count)
                        {
                            objModulePermissions.Add(new clsModulePermission(intModId, cpl.Add_Permission(-1, intModId, strPermission[0], int.Parse(strPermission[1])), strPermission[0], int.Parse(strPermission[1])));
                        }

                        if (((System.Windows.Controls.CheckBox)chk).IsChecked == true)
                        {
                            for (int j = 0; j < objModulePermissions.Count; j++)
                            {
                                if (objModulePermissions[j].PermissionName == strPermission[0])
                                {
                                    cpl.Add_ModulePermission(objModulePermissions[j].PermissionID, int.Parse(strPermission[2]));
                                    ((System.Windows.Controls.CheckBox)chk).IsChecked = false;

                                    break;
                                }
                            }
                        }
                    }
                }

                System.Windows.MessageBox.Show("Module Uploaded");

                txtUpload.Clear();
                txtZip.Clear();
                cmbAssembly.Items.Clear();
                cmbClass.Items.Clear();
                txtModule.Clear();
                txtVersion.Clear();
                ckbCollaborate.IsChecked = false;
                rtbDescription.SelectAll();
                rtbDescription.Selection.Text = "";
                ckbAuthentication.IsChecked   = false;
                txtModuleImage.Text           = "";

                if (grid1.Children.Count > 0)
                {
                    grid1.Children.Clear();
                }

                objModulePermissions.Clear();
            }
            catch (Exception ex)
            {
                VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "btnSubmit_Click()--1", "Controls\\CtlUploadModule.xaml.cs");
            }
        }
 public Stream CreateStream(RemoteFileInfo remoteFileInfo)
 {
     return new MemoryStream();
 }
 public override long CalculateSegmentSize(int segmentCount, RemoteFileInfo remoteFileInfo)
 {
     return base.CalculateSegmentSize(segmentCount, remoteFileInfo);
 }
예제 #32
0
        private void VerifyFiles()
        {
            while (true)
            {
                IndexedRemoteFileInfo indexedFileInfo;

                if (stopped)
                {
                    break;
                }

                lock (locker)
                {
                    indexedFileInfo = filesToCheck[0];
                }

                RemoteFileInfo fileInfo = indexedFileInfo.FileInfo;

                bool checkFileHash = true;

                if (fileInfo.Compressed)
                {
                    try
                    {
                        CompressionHelper.DecompressFile(downloadDirectory + fileInfo.GetFilePathWithCompression(),
                                                         downloadDirectory + fileInfo.FilePath);
                        File.Delete(downloadDirectory + fileInfo.GetFilePathWithCompression());
                    }
                    catch (Exception ex)
                    {
                        // The SevenZip compressor doesn't define what exceptions
                        // it might throw, so we'll just catch them all

                        UpdaterLogger.Log("Decompressing file " + fileInfo.FilePath + " failed! Message: " + ex.Message);
                        VerificationFailed?.Invoke(this, new IndexEventArgs(indexedFileInfo.Index));
                        queueReady    = false;
                        checkFileHash = false;
                    }
                }

                if (checkFileHash)
                {
                    if (!HashHelper.FileHashMatches(downloadDirectory + fileInfo.FilePath, fileInfo.UncompressedHash))
                    {
                        UpdaterLogger.Log("File " + fileInfo.FilePath + " failed verification!");
                        VerificationFailed?.Invoke(this, new IndexEventArgs(indexedFileInfo.Index));
                        queueReady = false;
                    }
                    else
                    {
                        UpdaterLogger.Log("File " + fileInfo.FilePath + " passed verification.");
                    }
                }

                bool waitingForWork = false;

                lock (locker)
                {
                    filesToCheck.RemoveAt(0);

                    waitingForWork = filesToCheck.Count == 0;

                    waitHandle.Reset();

                    if (queueReady && waitingForWork)
                    {
                        Completed?.Invoke(this, EventArgs.Empty);
                        break;
                    }

                    //if (stopped)
                    //{
                    //    filesToCheck.Clear();
                    //    break;
                    //}
                }

                if (waitingForWork)
                {
                    waitHandle.WaitOne();
                }
            }

            lock (locker)
            {
                waitHandle.Dispose();
                waitHandle = null;
            }

            // We could also dispose of verifierTask, but it sounds like we don't need to bother
            // https://blogs.msdn.microsoft.com/pfxteam/2012/03/25/do-i-need-to-dispose-of-tasks/
            // In case we'd still want to do it, it'd be safest for this class to have a function
            // for disposing the task (maybe this class could implement IDisposable), and the
            // user of this class would then call it
        }
 public override List<CalculatedFileSegment> GetSegments(int segmentCount, RemoteFileInfo remoteFileInfo)
 {
     return base.GetSegments(segmentCount, remoteFileInfo);
 }
        /// <summary>
        /// Starts downloading an update.
        /// </summary>
        /// <param name="buildPath">The local build path.</param>
        /// <param name="downloadDirectory">The download directory.</param>
        /// <param name="filesToDownload">A list of files to download.</param>
        /// <param name="updateMirror">The update mirror to use.</param>
        public UpdateDownloadResult DownloadUpdates(string buildPath, string downloadDirectory,
                                                    List <RemoteFileInfo> filesToDownload, UpdateMirror updateMirror)
        {
            if (filesToDownload.Count == 0)
            {
                return(new UpdateDownloadResult(UpdateDownloadResultType.COMPLETED));
            }

            cancelled = false;

            this.filesToDownload   = filesToDownload;
            this.downloadDirectory = downloadDirectory;
            this.updateMirror      = updateMirror;

            foreach (var fileInfo in filesToDownload)
            {
                totalUpdateSize += fileInfo.GetDownloadSize();
            }

            verifierWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

            verifier = new Verifier(downloadDirectory);
            verifier.VerificationFailed += Verifier_VerificationFailed;
            verifier.Completed          += Verifier_Completed;

            webClient = new WebClient()
            {
                CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore),
                Encoding    = Encoding.GetEncoding(1252)
            };
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;

            fileIndexesToDownload = new List <int>();
            for (int i = 0; i < filesToDownload.Count; i++)
            {
                fileIndexesToDownload.Add(i);
            }
            fileIndexesToDownload.Reverse();
            fileIndexErrorCounts = new int[filesToDownload.Count];

            while (true)
            {
                int fileIndex;

                lock (fileListLocker)
                {
                    // If we have downloaded all files and the verifier has
                    // succesfully verified them, the list of file indexes to
                    // download has no entries -> we don't have any work left
                    if (fileIndexesToDownload.Count == 0)
                    {
                        break;
                    }

                    fileIndex = fileIndexesToDownload[fileIndexesToDownload.Count - 1];
                    currentlyDownloadedFile = filesToDownload[fileIndex];

                    if (fileIndexErrorCounts[fileIndex] > MAX_ERROR_COUNT)
                    {
                        return(CleanUpAndReturnResult(UpdateDownloadResultType.FAILED,
                                                      "Failed to download file " + currentlyDownloadedFile.FilePath));
                    }
                }

                Task downloadTask = null;

                try
                {
                    // By both checking for cancellation and starting a new download
                    // task in the same lock block that's also used in Cancel() we're
                    // making sure that a call to Cancel() will take effect right
                    // away - either we're executing the code above meaning we'll
                    // check for cancellation soon, or we're waiting for a download to
                    // finish - and Cancel() cancels the download operation in case
                    // one is going on
                    lock (cancellationLocker)
                    {
                        if (cancelled)
                        {
                            return(CleanUpAndReturnResult(UpdateDownloadResultType.CANCELLED));
                        }

                        string fileSavePath = downloadDirectory + currentlyDownloadedFile.GetFilePathWithCompression();

                        Directory.CreateDirectory(Path.GetDirectoryName(fileSavePath));

                        downloadTask = webClient.DownloadFileTaskAsync(
                            new Uri(updateMirror.URL + currentlyDownloadedFile.GetFilePathWithCompression().Replace('\\', '/')),
                            fileSavePath);
                    }

                    downloadTask.Wait();
                    downloadTask.Dispose();

                    lock (downloadedBytesLocker)
                        downloadedBytes += currentlyDownloadedFile.GetDownloadSize();

                    verifier.VerifyFile(new IndexedRemoteFileInfo(currentlyDownloadedFile, fileIndex));
                }
                catch (AggregateException ex)
                {
                    downloadTask.Dispose();

                    if (cancelled)
                    {
                        return(CleanUpAndReturnResult(UpdateDownloadResultType.CANCELLED));
                    }

                    UpdaterLogger.Log("Exception while downloading file " +
                                      currentlyDownloadedFile.FilePath);

                    LogInnerExceptionRecursive(ex);

                    lock (fileListLocker)
                    {
                        fileIndexErrorCounts[fileIndex]++;
                    }

                    continue;
                }

                bool waitingForVerifier = false;

                lock (fileListLocker)
                {
                    // Remove the downloaded file from the download queue
                    fileIndexesToDownload.Remove(fileIndex);

                    waitingForVerifier = fileIndexesToDownload.Count == 0;
                }

                if (waitingForVerifier)
                {
                    // We have downloaded all the files, wait for the verifier
                    // to finish verifying them
                    verifier.SetQueueReady();
                    verifierWaitHandle.WaitOne();
                }
            }

            return(CleanUpAndReturnResult(UpdateDownloadResultType.COMPLETED));
        }
예제 #35
0
        void backgroundUploadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                FileTransferInfo fileTranserInfo = e.Argument as FileTransferInfo;
                var fileManger = Common.ServiceBroker.FindService <IFileTransferService>(fileTranserInfo.remoteAddress); //创建WCF带来

                string localPath = fileTranserInfo.localPath;

                if (fileTranserInfo.fileTransferType == FileTransferType.uploadDir)
                {
                }
                else if (fileTranserInfo.fileTransferType == FileTransferType.uploadFile)
                {
                    string     fileName = fileTranserInfo.fileName;
                    int        maxSiz   = 1024 * 10;                                            //设置每次传10k
                    FileStream stream   = System.IO.File.OpenRead(localPath + "\\" + fileName); //读取本地文件

                    RemoteFileInfo fileUpload = new RemoteFileInfo();
                    fileUpload.Path = fileTranserInfo.serverPath;
                    fileUpload.Name = fileName;

                    RemoteFileInfo file = fileManger.GetFile(fileUpload);   //更加文件名,查询服务中是否存在该文件
                    file.Name   = fileName;
                    file.Length = stream.Length;
                    if (file.Length == file.Offset) //如果文件的长度等于文件的偏移量,说明文件已经上传完成
                    {
                        Result = file.FileFullPath;
                        return;
                    }
                    else
                    {
                        while (file.Length != file.Offset)                                                                        //循环的读取文件,上传,直到文件的长度等于文件的偏移量
                        {
                            file.Data       = new byte[file.Length - file.Offset <= maxSiz ? file.Length - file.Offset : maxSiz]; //设置传递的数据的大小
                            stream.Position = file.Offset;                                                                        //设置本地文件数据的读取位置
                            stream.Read(file.Data, 0, file.Data.Length);                                                          //把数据写入到file.Data中
                            file = fileManger.UploadFile(file);                                                                   //上传

                            e.Result = file.Offset;
                            (sender as BackgroundWorker).ReportProgress((int)(((double)file.Offset / (double)((long)file.Length)) * 100), file.Offset);
                            if (this.backgroundUploadWorker.CancellationPending)
                            {
                                stream.Close();
                                Result = "用户取消上传!";
                                return;
                            }
                        }
                        Result = file.FileFullPath;
                    }
                    stream.Close();
                }
            }
            catch (System.Exception ex)
            {
                LogText("Exception : " + ex.Message);
                if (ex.InnerException != null)
                {
                    LogText("Inner Exception : " + ex.InnerException.Message);
                }
            }
        }
예제 #36
0
 UploadFileResponse IStreamService.UploadFile(RemoteFileInfo request)
 {
     return(base.Channel.UploadFile(request));
 }
예제 #37
0
 internal void uploadFile(RemoteFileInfo request)
 {
     Channel.uploadFile(request);
 }
예제 #38
0
        private async Task SynchronizeAsync(CancellationToken cancellationToken)
        {
            // The semaphore acts like queue.
            using (await _sempahore.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                var synchronizationStarted = false;
                var succeeded = false;
                var requiresReloadLocalData = false;

                try
                {
                    if (!_settingsProvider.GetSetting(SettingsDefinitions.SyncDataWithCloud))
                    {
                        return;
                    }

                    string targetterProviderName = _settingsProvider.GetSetting(SettingsDefinitions.RemoteStorageProviderName);
                    IRemoteStorageProvider remoteStorageProvider = _remoteStorageProviders.SingleOrDefault(m => string.Equals(m.Metadata.ProviderName, targetterProviderName, StringComparison.Ordinal))?.Value;

                    if (remoteStorageProvider == null)
                    {
                        return;
                    }

                    if (!CoreHelper.IsInternetAccess())
                    {
                        return;
                    }

                    SynchronizationStarted?.Invoke(this, EventArgs.Empty);
                    synchronizationStarted = true;

                    if (!await remoteStorageProvider.SignInAsync(interactive: false, cancellationToken).ConfigureAwait(false))
                    {
                        // If fails to authenticate, disables synchronization and sign out.
                        _settingsProvider.SetSetting(SettingsDefinitions.SyncDataWithCloud, false);
                        await remoteStorageProvider.SignOutAsync().ConfigureAwait(false);

                        // TODO: Add a log to notify to let the user know it signed out and he should re-authenticate.

                        // returning here will still trigger the Finally block.
                        return;
                    }

                    // Retrieve the list of online files.
                    IReadOnlyList <RemoteFileInfo> roamingFiles =
                        await remoteStorageProvider.GetFilesAsync(Constants.DataFileCountLimit, cancellationToken).ConfigureAwait(false);

                    RemoteFileInfo roamingUserDataBundleFile = roamingFiles.FirstOrDefault(file
                                                                                           => string.Equals(Path.GetFileName(file.FullPath), Constants.UserDataBundleFileName, StringComparison.Ordinal));

                    IEnumerable <RemoteFileInfo> allOtherRoamingFiles = roamingFiles.Where(file
                                                                                           => !string.Equals(Path.GetFileName(file.FullPath), Constants.UserDataBundleFileName, StringComparison.Ordinal));

                    // Retrieve the list of local files.
                    var localUserDataFolder = await CoreHelper.GetOrCreateUserDataStorageFolderAsync().ConfigureAwait(false);

                    StorageFile localUserDataBundleFile = await localUserDataFolder.TryGetItemAsync(Constants.UserDataBundleFileName) as StorageFile;

                    IEnumerable <StorageFile> allOtherLocalFiles = (await localUserDataFolder.GetFilesAsync())
                                                                   .Where(file => !string.Equals(file.Name, Constants.UserDataBundleFileName, StringComparison.Ordinal));

                    if (localUserDataBundleFile == null && roamingUserDataBundleFile == RemoteFileInfo.Empty)
                    {
                        // Nothing locally and remotely?

                        succeeded = true;
                        return;
                    }

                    if (localUserDataBundleFile == null ||
                        (roamingUserDataBundleFile != RemoteFileInfo.Empty &&
                         roamingUserDataBundleFile.CreatedDateTime.ToUniversalTime()
                         > (await localUserDataBundleFile.GetBasicPropertiesAsync()).DateModified.ToUniversalTime()))
                    {
                        // If there is no local user data file, or that the file on the server is more recent than the local one,
                        // then we want to merge by taking the version from the server.

                        await DownloadRoamingDataFromServerAsync(
                            remoteStorageProvider,
                            allOtherRoamingFiles,
                            allOtherLocalFiles,
                            cancellationToken).ConfigureAwait(false);

                        // The local file changed, since we downloaded the one from the server, so let's indicate
                        // that we want to reload (and merge) the local data.
                        requiresReloadLocalData = true;
                    }
                    else
                    {
                        // Else, then it means the local file is more recent than the one on the server,
                        // or that there is simply no file on the server,
                        // so we want to merge by taking the version from the local file.

                        await UploadLocalDataToServerAsync(
                            remoteStorageProvider,
                            localUserDataBundleFile,
                            allOtherRoamingFiles,
                            allOtherLocalFiles,
                            cancellationToken).ConfigureAwait(false);
                    }

                    succeeded = true;
                }
                catch (OperationCanceledException)
                {
                    _logger.LogEvent(SynchronizeCanceledEvent, "The synchronization with the cloud has been canceled.");
                }
                catch (Exception ex)
                {
                    _logger.LogFault(SynchronizeFaultEvent, "Failed to synchronize the data with the cloud.", ex);
                }
                finally
                {
                    if (synchronizationStarted)
                    {
                        RaiseSynchronizationCompleted(succeeded, requiresReloadLocalData);
                    }
                }
            }
        }
        public SchedaLibroView(string addr, string username, Libro libro)
        {
            InitializeComponent();

            _addr     = addr;
            _username = username;
            _libro    = libro;

            _schedaLibro   = new SchedaLibro(_libro, addr, username);
            _laMiaLibreria = new LaMiaLibreria(_username, _addr);

            textBoxTitoloLibro.Text = _libro.Titolo;
            textBoxAutoreLibro.Text = _libro.Autore;
            textBoxAnnoLibro.Text   = _libro.Anno.ToString();
            textBoxGenereLibro.Text = _libro.Gen.ToString();

            if (_libro.FilePath == null)
            {
            }
            else
            {
                _schedaLibro.DownloadCopertina();
                pictureBoxCopertina.SizeMode = PictureBoxSizeMode.StretchImage;

                if (!File.Exists("C:\\Users\\mmart\\Desktop\\Download\\" + _libro.FilePath))
                {
                    try
                    {
                        BasicHttpBinding myBinding = new BasicHttpBinding();
                        myBinding.MaxReceivedMessageSize = 2147483647;
                        myBinding.MaxBufferSize          = 2147483647;
                        EndpointAddress          myEndpoint       = new EndpointAddress(_addr);
                        ChannelFactory <IUtente> myChannelFactory = new ChannelFactory <IUtente>(myBinding, myEndpoint);
                        // Create a channel.
                        IUtente         client      = myChannelFactory.CreateChannel();
                        DownloadRequest requestData = new DownloadRequest();

                        RemoteFileInfo fileInfo = new RemoteFileInfo();
                        requestData.FileName = _libro.FilePath;

                        try
                        {
                            fileInfo = client.DownloadFile(requestData);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                        Console.ReadLine();

                        string pathNew        = @"C:\Users\mmart\Desktop\Download\" + _libro.FilePath;
                        int    numBytesToRead = (int)fileInfo.Length;
                        byte[] buffer         = new byte[483647];
                        byte[] bytes          = new byte[numBytesToRead];
                        int    bytesRead      = 0;

                        while (numBytesToRead > 0)
                        {
                            // Read may return anything from 0 to numBytesToRead.
                            int n = fileInfo.FileByteStream.Read(buffer, bytesRead, buffer.Length);

                            // Break when the end of the file is reached.
                            if (n == 0)
                            {
                                break;
                            }
                            Array.Copy(buffer, 0, bytes, bytesRead, n);
                            bytesRead      += n;
                            numBytesToRead -= n;
                        }
                        numBytesToRead = bytes.Length;

                        // Write the byte array to the other FileStream.
                        using (FileStream fsNew = new FileStream(pathNew, FileMode.Create, FileAccess.Write))
                        {
                            fsNew.Write(bytes, 0, numBytesToRead);
                        }

                        ((IClientChannel)client).Close();
                    }
                    catch
                    {
                    }
                }

                pictureBoxCopertina.Image = Image.FromFile("C:\\Users\\mmart\\Desktop\\Download\\" + _libro.FilePath);
            }
        }
예제 #40
0
 public Handle(RemoteFileInfo fileInfo)
 {
     FileInfo = fileInfo;
 }
예제 #41
0
        private void btnLoad_Click(object sender, EventArgs ev)
        {
            try
            {
                hydrobaseADO ado = new hydrobaseADO();
                string       zipfile;
                string       destdir;

                if ((MainWindow.username != null) && (MainWindow.pass != null))
                {
                    frmEdit frmedit = new frmEdit();
                    ado.CloseDataBase(frmedit.set);
                    ado.RemoveTableFromDataGrid(frmedit.grid);
                    //frmedit.IsMdiChild = true;
                    frmedit.MdiParent = Program.Mainwnd;
                    frmedit.Show();

                    frmedit.set = new DataSet();

                    //  frmMain.grid = new DataGridView();
                    // MessageBox.Show(Program.client.LoadTable(BaseClass.recordtag, MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text));
                    if (Program.client.IsTableEncrypted(MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text) == false)
                    {
                        RemoteFileInfo zfile = Program.client.LoadTableAsFile(BaseClass.recordtag,
                                                                              MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text);

                        if (zfile != null)
                        {
                            zipfile = Path.Combine(Program.TempPath, zfile.FileName);
                            byte[] str = zfile.FileByteStream;
                            util.ByteToFile(zipfile, str);
                            FastZip z = new FastZip();
                            destdir = Path.Combine(Program.TempPath, Path.GetFileNameWithoutExtension(zfile.FileName));
                            if (!Directory.Exists(destdir))
                            {
                                Directory.CreateDirectory(destdir);
                            }
                            z.ExtractZip(zipfile, destdir, null);
                            string[] files = Directory.GetFiles(destdir);
                            if (files != null)
                            {
                                frmedit.set.ReadXml(files[0]);
                            }
                        }



                        //  frmedit.set.ReadXml(util.StringToStream());



                        //frmedit.set.ReadXml(util.StringToStream(Program.client.LoadTable(BaseClass.recordtag, MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text)));
                        // MessageBox.Show(Program.client.LoadTable(BaseClass.recordtag, MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text));
                    }
                    else
                    {
                        if (MainWindow.passphrase != null)
                        {
                            frmedit.set.ReadXml(util.StringToStream(Program.client.Decrypt(BaseClass.tabletag, BaseClass.recordtag, MainWindow.username, lstDbs.Text, lsttables.Text, MainWindow.pass, Cryptography.CryptograhyAlgorithm.rijdael.ToString().ToString(), Cryptography.HashingAlogrithm.SHA384.ToString().ToString(), MainWindow.passphrase)));
                        }
                        else
                        {
                            MainWindow.passphrase = Microsoft.VisualBasic.Interaction.InputBox("Type your passphrase");
                            if (MainWindow.passphrase != null)
                            {
                                frmedit.set.ReadXml(util.StringToStream(Program.client.Decrypt(BaseClass.tabletag, BaseClass.recordtag, MainWindow.username, lstDbs.Text, lsttables.Text, MainWindow.pass, Cryptography.CryptograhyAlgorithm.rijdael.ToString().ToString(), Cryptography.HashingAlogrithm.SHA384.ToString().ToString(), MainWindow.passphrase)));
                            }
                        }
                    }
                    // MessageBox.Show(Program.client.LoadTable(BaseClass.recordtag,MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text));

                    if (frmedit.set.Tables.Count > 0)
                    {
                        frmedit.grid.DataSource = frmedit.set;
                        frmedit.grid.DataMember = frmedit.set.Tables[frmedit.set.Tables.Count - 1].TableName;
                        ado.ConnectEventstoDataGrid(frmedit.grid);
                        ado.ConnectEventstoDataTable(frmedit.set.Tables[0]);
                        frmedit.Text      = frmedit.grid.DataMember;
                        frmedit.dbname    = lstDbs.Text;
                        frmedit.tablename = lsttables.Text;
                        frmedit.Text      = String.Format("{0}\\{1}", frmedit.dbname, frmedit.tablename);
                    }
                }
                else
                {
                    Login log = new Login();
                    log.Show();
                    frmEdit frmedit = new frmEdit();
                    frmedit.MdiParent = Program.Mainwnd;
                    // frmedit.IsMdiChild = true;
                    frmedit.set = new DataSet();
                    frmedit.set.ReadXml(util.StringToStream(Program.client.LoadTable(BaseClass.recordtag, MainWindow.username, MainWindow.pass, lstDbs.Text, lsttables.Text)));

                    frmedit.grid.DataSource = frmedit.set;
                    frmedit.grid.DataMember = frmedit.set.Tables[frmedit.set.Tables.Count - 1].TableName;
                    frmedit.Text            = frmedit.grid.DataMember;
                    frmedit.dbname          = lstDbs.Text;
                    frmedit.tablename       = lsttables.Text;
                    frmedit.Text            = String.Format("{0}\\{1}", frmedit.dbname, frmedit.tablename);
                    ado.ConnectEventstoDataGrid(frmedit.grid);
                    ado.ConnectEventstoDataTable(frmedit.set.Tables[0]);
                }

                this.Close();
            }
            catch (Exception e)
            {
                Program.errorreport(e);
                MessageBox.Show(e.ToString());
                this.Close();
            }
        }
예제 #42
0
        int DownloadAndExtractZipFile()
        {
            str = CRMName;
            str = str + "_CRM";

            //Retrives the Assembly of the Zip file.
            Assembly ass = Assembly.GetEntryAssembly();

            #region Downloading ZipFile

            //Set the Variable.
            filename = str + ".zip";

            //string strModPath = "";


            #region Download Zip File using WCF FileTranserService

            //Download file using WCF FileTransferService


            try
            {
                //Create object of the HTTP Client.
                BasicHttpClient bhcFts = new BasicHttpClient();

                //Open Client.
                clientHttpFileTransfer = (IHTTPFileTransferService)bhcFts.OpenClient <IHTTPFileTransferService>("http://" + VMuktiInfo.BootStrapIPs[0] + ":80/VMukti/HttpFileTransferService");

                //Join the network.
                clientHttpFileTransfer.svcHTTPFileTransferServiceJoin();

                //Create request to download File from Bootstrap.
                DownloadRequest request = new DownloadRequest();

                //Providing the information of the file that needs to download.
                RemoteFileInfo rfi = new RemoteFileInfo();
                request.FileName = filename;
                request.FolderWhereFileIsStored = "CRMs";

                //Calling the WCF Function for downloading the File.
                rfi = clientHttpFileTransfer.svcHTTPFileTransferServiceDownloadFile(request);


                //Checking for Directory Existence.
                //if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"CRMs")))
                if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"CRMs")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("VMukti.Presentation.exe", @"CRMs"));
                }

                destination = ass.Location.Replace("VMukti.Presentation.exe", @"CRMs");

                //Checking for File Existance.
                if (File.Exists((destination + "\\" + filename)))
                {
                    File.Delete((destination + "\\" + filename));
                }

                filePath = destination + "\\" + filename;

                System.IO.Stream inputStream = rfi.FileByteStream;


                using (System.IO.FileStream writeStream = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
                {
                    int    chunkSize = 2048;
                    byte[] buffer    = new byte[chunkSize];

                    do
                    {
                        // read bytes from input stream
                        int bytesRead = inputStream.Read(buffer, 0, chunkSize);
                        if (bytesRead == 0)
                        {
                            break;
                        }

                        // write bytes to output stream
                        writeStream.Write(buffer, 0, bytesRead);
                    } while (true);

                    writeStream.Close();
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Download Zip: " + ex.Message);
                VMuktiHelper.ExceptionHandler(ex, "DownloadAndExtractZipFile()", "CtlCRMContainer.xaml.cs");
                if (ex.InnerException != null)
                {
                    //MessageBox.Show("Download Zip Inner Exception: " + ex.InnerException.Message);
                    VMuktiHelper.ExceptionHandler(ex, "DownloadAndExtractZipFile()", "CtlCRMContainer.xaml.cs");
                }
            }

            #endregion

            #region Downloading using Web Client --------Commented
            //try
            //{
            //    Uri u = new Uri("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti/CRMs/" + filename);
            //    if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"CRMs")))
            //    {
            //        Directory.CreateDirectory(ass.Location.Replace("VMukti.Presentation.exe", @"CRMs"));
            //    }
            //    destination = ass.Location.Replace("VMukti.Presentation.exe", @"CRMs");
            //    if (!File.Exists(destination + "\\" + filename))
            //    {
            //        WebClient wc = new WebClient();
            //        try
            //        {
            //            wc.DownloadFile(u, destination + "\\" + filename);
            //        }
            //        catch (Exception exp)
            //        {
            //            MessageBox.Show(exp.Message);
            //        }
            //    }
            //}
            //catch (Exception exp)
            //{
            //    MessageBox.Show("Down Load Error - " + exp.Message);
            //}
            #endregion

            #endregion

            #region Extracting

            //Code for Extracting the .zip file.
            try
            {
                //Checking for the Existance of the Directory.

                if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"CRMModules")))
                {
                    Directory.CreateDirectory(ass.Location.Replace("VMukti.Presentation.exe", @"CRMModules"));
                }
                str = CRMName;
                str = str + "_CRM";
                Assembly ass2 = Assembly.GetEntryAssembly();
                strModPath = ass2.Location.Replace("VMukti.Presentation.exe", @"CRMModules");

                VMukti.ZipUnzip.Zip.FastZip fz = new VMukti.ZipUnzip.Zip.FastZip();
                //ICSharpCode.SharpZipLib.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();

                //FastZip fz = new FastZip();
                //if (!Directory.Exists(strModPath + "\\" + filename.Split('.')[0]))
                //{
                try
                {
                    //Extracting the zip file.
                    fz.ExtractZip(destination + "\\" + filename, strModPath + "\\" + str, null);
                }
                catch (Exception exp)
                {
                    //MessageBox.Show(exp.Message + " First Desgine Required CRM Using CRMDesginer");
                    VMuktiHelper.ExceptionHandler(exp, "DownloadAndExtractZipFile()", "CtlCRMContainer.xaml.cs");
                }
                // }
            }
            catch (Exception exp)
            {
                VMuktiHelper.ExceptionHandler(exp, "DownloadAndExtractZipFile(Outer)", "CtlCRMContainer.xaml.cs");
                return(-1);
            }

            #endregion
            return(0);
        }
예제 #43
0
 public void UploadFiles(RemoteFileInfo request)
 {
     base.Channel.UploadFiles(request);
 }
 public Stream CreateStream(RemoteFileInfo remoteFileInfo)
 {
     return new TestOutputStream(File.ReadAllBytes(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\images", "087dc7cf14c97_1.jpg")));
 }
예제 #45
0
 public Stream CreateStream(RemoteFileInfo remoteFileInfo)
 {
     return(new TestOutputStream(File.ReadAllBytes(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\images", "087dc7cf14c97_1.jpg"))));
 }
예제 #46
0
        /// <summary>
        /// Gathers a list of files that do not exist or are outdated in the
        /// build directory.
        /// </summary>
        public List <FileEntry> GetOutdatedFileList()
        {
            string targetDirectory = Environment.CurrentDirectory +
                                     Path.DirectorySeparatorChar + BuildDirectory;

            // If the build directory doesn't exist, we need to process all the files
            if (!Directory.Exists(targetDirectory))
            {
                return(new List <FileEntry>(FileEntries));
            }

            if (targetDirectory[targetDirectory.Length - 1] != Path.DirectorySeparatorChar)
            {
                targetDirectory = targetDirectory + Path.DirectorySeparatorChar;
            }

            RemoteBuildInfo remoteBuildInfo = new RemoteBuildInfo();

            if (File.Exists(targetDirectory + BuildHandler.REMOTE_BUILD_INFO_FILE))
            {
                remoteBuildInfo.Parse(targetDirectory + BuildHandler.REMOTE_BUILD_INFO_FILE);
            }

            List <FileEntry> outdatedList = new List <FileEntry>();

            foreach (FileEntry file in FileEntries)
            {
                string filePath         = targetDirectory + file.FilePath;
                string originalFilePath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + file.FilePath;

                if (file.Compressed)
                {
                    // Compressed files have an additional file extension
                    filePath = filePath + RemoteFileInfo.COMPRESSED_FILE_EXTENSION;
                }

                if (!File.Exists(filePath))
                {
                    // If the file doesn't exist in the build, we obviously need
                    // to process it
                    outdatedList.Add(file);
                    continue;
                }

                if (file.Compressed)
                {
                    // If the file is compressed, check if the uncompressed hash
                    // in RemoteVersion matches the hash of the original (uncompressed) file
                    // If not (or there is no record of the file in RemoteVersion), we need
                    // to process the file

                    RemoteFileInfo existingFileInfo = remoteBuildInfo.FileInfos.Find(
                        f => f.FilePath == file.FilePath);

                    if (existingFileInfo == null ||
                        !HashHelper.ByteArraysMatch(existingFileInfo.UncompressedHash,
                                                    HashHelper.ComputeHashForFile(originalFilePath)))
                    {
                        outdatedList.Add(file);
                    }
                }
                else
                {
                    // For uncompressed files we can just compare its hash
                    // to the original file's hash directly

                    if (!HashHelper.ByteArraysMatch(HashHelper.ComputeHashForFile(filePath),
                                                    HashHelper.ComputeHashForFile(originalFilePath)))
                    {
                        outdatedList.Add(file);
                    }
                }
            }

            return(outdatedList);
        }
예제 #47
0
 System.Threading.Tasks.Task <UploadFileResponse> IStreamService.UploadFileAsync(RemoteFileInfo request)
 {
     return(base.Channel.UploadFileAsync(request));
 }
예제 #48
0
        private byte[] GetFile(IFileTransfer host, string fileName)
        {
            RemoteFileInfo fileInfo = new RemoteFileInfo();

            byte[] file = new byte[0];

            try
            {
                DownloadRequest requestData = new DownloadRequest();

                requestData.FileName = fileName;

                fileInfo = host.DownloadFile(requestData);

                using (MemoryStream stream = new MemoryStream())
                {
                    fileInfo.FileByteStream.CopyTo(stream);
                    file = stream.ToArray();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
            finally
            {
                fileInfo.FileByteStream.Close();
            }

            return file;
        }