예제 #1
0
        static Globals()
        {
            fileTransferManager = new FileTransferManager();
            LogAPI.WebServiceLog.Debug("FileTransferManager created");

            AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
        }
예제 #2
0
 private void _transfer_Ready(Client client)
 {
     _fileTransferManager = new FileTransferManager(client, Program.Configuration.MaxBufferSize);
     _fileTransferManager.UpdateTransfer += _fileTransferManager_UpdateTransfer;
     Text   += $" - Encryption: {client.CryptoServiceAlgorithm}";
     Visible = true;
 }
예제 #3
0
        private void Server_NewClient(Server server, Client client)
        {
            new Thread(() =>
            {
                if (client.Protocol == Protocol.FFTSI)
                {
                    // Handle events on the new client
                    client.Disconnected   += Client_Disconnected1;
                    client.PacketReceived += Client_PacketReceived1;

                    // Create file explorer session
                    Explorer explorer = new Explorer(client, Program.Configuration.ProtectedDirectories.ToArray());

                    // Start receiving data
                    client.Connect(Program.Configuration.MaxBufferSize);

                    UpdateStatus($"Connected - {client}");

                    icnMain.ShowBalloonTip(5000, "FastFileTransfer", $"New inbound connection from {client.IP}:{client.Port}", ToolTipIcon.Info);
                }
                else
                {
                    // Transfer socket connection
                    FileTransferManager ftm = new FileTransferManager(client, Program.Configuration.MaxBufferSize);
                    client.Connect(Program.Configuration.MaxBufferSize);
                }
            }).Start();
        }
        public IFileSender Create()
        {
            IModel channel = _connectionManager.GetChannel();

            var transferManager = new FileTransferManager(_serializationAssistantFactory.Create(), channel, Queues.Files);
            var fileSender = new FileSender(transferManager, _harvesterName);

            return fileSender;
        }
예제 #5
0
        private void button2_Click(object sender, EventArgs e)
        {
            FileTransferManager  transfer = new FileTransferManager();
            FileTransferResponse success  = transfer.GetFile("App.config.transform");

            FileDescription[] descs = transfer.GetServerFilesInfoFromTempFolder();
            foreach (var item in descs)
            {
                listBox1.Items.Add(item.Name + " " + (item.SizeBytes / 1000000) + "Mb");
            }
        }
예제 #6
0
        static async Task Main(string[] args)
        {
            //You can use the command 'fsutil file createnew c:\Test1\file1.txt 131457280' to create a file with 125MB (Needs to be executed under administrator privileges).
            //Or this script to create multiple files:
            //For ($i=0; $i -lt 200; $i++) { cmd.exe / c("C:\WINDOWS\system32\fsutil file createnew c:\Test1\file" + $i + ".txt 1457280") }

            var source      = @"C:\Test1\";
            var destination = @"C:\Test2\";

            await FileTransferManager.CopyWithProgressAsync(source, destination, Progress, false, true, 500);
        }
예제 #7
0
파일: Core.cs 프로젝트: slicol/meshwork
        public Core(ISettings settings, IPlatform platform)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (platform == null)
            {
                throw new ArgumentNullException(nameof(platform));
            }

            Settings = settings;
            Platform = platform;

            KeyManager keyManager = new KeyManager(settings);

            rsaProvider = new RSACryptoServiceProvider();
            rsaProvider.ImportParameters(keyManager.EncryptionParameters);
            nodeID = Common.Utils.SHA512Str(rsaProvider.ToXmlString(false));

            FileSystem = new FileSystemProvider(this);

            ShareBuilder = new ShareBuilder(this);
            ShareBuilder.FinishedIndexing += ShareBuilder_FinishedIndexing;

            shareWatcher = new ShareWatcher(this);

            ShareHasher = new ShareHasher();

            transportManager = new TransportManager(this);

            FileTransferManager = new FileTransferManager(this);

            FileSearchManager = new FileSearchManager(this);

            DestinationManager = new DestinationManager(this);

            // XXX: Use reflection to load these:
            DestinationManager.RegisterSource(new TCPIPv4DestinationSource(this));
            DestinationManager.RegisterSource(new TCPIPv6DestinationSource(this));

            TrackerFactory.Register("meshwork", typeof(MeshworkTracker));

            ITransportListener tcpListener = new TcpTransportListener(this, Settings.TcpListenPort);

            transportListeners.Add(tcpListener);

            if (FinishedLoading != null)
            {
                FinishedLoading(null, EventArgs.Empty);
            }
        }
예제 #8
0
        public static async Task MoveFile(string source, string target, Action <TransferProgress> progress, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (IsSameDrive(source, target))
            {
                await FileTransferManager.MoveWithProgressAsync(source, target, progress, cancellationToken);
            }
            else
            {
                await CopyFile(source, target, progress, cancellationToken);

                File.Delete(source);
            }
        }
예제 #9
0
 private static void Server_NewClient(Server server, Client client)
 {
     if (client.Protocol == Protocol.FFTSI)
     {
         Explorer explorer = new Explorer(client, config.ProtectedDirectories.ToArray());
         client.PacketReceived += Client_PacketReceived;
         client.Connect(config.MaxBufferSize);
     }
     else
     {
         FileTransferManager ftm = new FileTransferManager(client, config.MaxBufferSize);
         client.Connect(config.MaxBufferSize);
     }
 }
예제 #10
0
        public FrmSendFile(FileTransferManager ftm, Jid[] jid)
        {
            InitializeComponent();

            fm      = ftm;
            _arrjid = jid;

            Text = "File transfer: " + jid;

            fm.OnError    += fm_OnError;
            fm.OnEnd      += fm_OnEnd;
            fm.OnStart    += fm_OnStart;
            fm.OnProgress += fm_OnProgress;
        }
예제 #11
0
        public FrmSendFile(FileTransferManager ftm, Jid[] jid)
        {
            InitializeComponent();

            fm = ftm;
            _arrjid = jid;

            Text = "File transfer: " + jid;

            fm.OnError += fm_OnError;
            fm.OnEnd += fm_OnEnd;
            fm.OnStart += fm_OnStart;
            fm.OnProgress += fm_OnProgress;
        }
예제 #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Title = "Select File";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    byte[] bytes = File.ReadAllBytes(openFileDialog.FileName);
                    string name  = openFileDialog.FileName.Substring(openFileDialog.FileName.LastIndexOf('\\') + 1);
                    FileTransferManager  transfer = new FileTransferManager();
                    FileTransferResponse success  = transfer.SendFileToServerTempFolder(name, bytes);
                }
            }
        }
    /// <summary>
    /// Configures the application, loads assets etc. Called only once when application started.
    /// </summary>
    void Start()
    {
        DontDestroyOnLoad(this.gameObject);

        sessionguid = System.Guid.NewGuid();
        GameObject.Find("txt_guid").GetComponent <Text>().text = sessionguid.ToString();

        gameCamera = GameObject.Find("Main Camera").GetComponent <Camera>();

        logManager          = gameObject.GetComponent <LogManager>();
        fileTransferManager = gameObject.GetComponent <FileTransferManager>();

        faceObject        = GameObject.Find("FaceObject").GetComponent <FaceObjectController>();
        selectedAssetType = AssetType.None;

        // Load Assets
        InitAssets("FaceObject/fo_faceshape/", AssetType.HeadShape, AssetGender.NoGender);
        InitAssets("FaceObject/fo_hair/", AssetType.Hair, AssetGender.NoGender);
        InitAssets("FaceObject/fo_ears/", AssetType.Ears, AssetGender.NoGender);
        InitAssets("FaceObject/fo_eyes/", AssetType.Eyes, AssetGender.NoGender);
        InitAssets("FaceObject/fo_eyebrows/", AssetType.Eyebrows, AssetGender.NoGender);
        InitAssets("FaceObject/fo_glasses/", AssetType.Glasses, AssetGender.NoGender);
        InitAssets("FaceObject/fo_facedetail/", AssetType.FaceTexture, AssetGender.NoGender);
        InitAssets("FaceObject/fo_nose/", AssetType.Nose, AssetGender.NoGender);
        InitAssets("FaceObject/fo_moustache/", AssetType.Moustache, AssetGender.NoGender);
        InitAssets("FaceObject/fo_beard/", AssetType.Beard, AssetGender.NoGender);
        InitAssets("FaceObject/fo_mouth/", AssetType.Mouth, AssetGender.NoGender);
        InitAssets("FaceObject/fo_body/", AssetType.Body, AssetGender.NoGender);
        InitAssets("FaceObject/fo_specialbody/", AssetType.SpecialBody, AssetGender.Female);
        InitAssets("FaceObject/fo_ghutra/", AssetType.Ghutra, AssetGender.Male);
        InitAssets("UI/bg_patterns/", AssetType.BackgroundTexture, AssetGender.NoGender);

        // Set the default selected category as Body.
        GameObject.Find("btn_body").GetComponent <UIAssetCategoryButtonController>().OnButtonClick();

        // Color palette management.
        defaultColorPalette = GameObject.Find("colorpalette_default").transform;
        defaultColorPalette.gameObject.SetActive(false);
        skinColorPalette = GameObject.Find("colorpalette_skin").transform;
        skinColorPalette.gameObject.SetActive(false);
        FillColorPalette();

        // Random avatar generation on the first run.
        faceObject.GenerateRandomAvatar();
    }
예제 #14
0
        private void _fileTransferManager_UpdateTransfer(FileTransferManager sender, FileTransfer fileTransfer)
        {
            Invoke((MethodInvoker) delegate
            {
                ListViewItem item    = lstTransfers.Items.Cast <ListViewItem>().FirstOrDefault(i => (string)i.Tag == fileTransfer.TransferId);
                ProgressBar progress = lstTransfers.Controls.OfType <ProgressBar>().FirstOrDefault(p => (string)p.Tag == fileTransfer.TransferId);

                progress.Value = fileTransfer.CalculatePercentage();
                item.SubItems[item.SubItems.Count - 3].Text = Explorer.GetSize(fileTransfer.Transferred());
                item.SubItems[item.SubItems.Count - 2].Text = Explorer.GetSize(fileTransfer.BytesPerSecond);

                if (!fileTransfer.Transfering)
                {
                    item.SubItems[1].Text = "Completed";
                    item.ForeColor        = Color.Green;
                }
            });
        }
예제 #15
0
        public FrmReceiveFile(FileTransferManager ftm, FileTransferEventArgs fea)
        {
            InitializeComponent();

            fm = ftm;
            ftea = fea;

            Text = "File transfer: " + ftea.Jid;

            lblSize.Text = Util.HumanReadableFileSize(ftea.FileSize);
            lblFileName.Text = ftea.Filename;
            lblDescription.Text = ftea.Description;

            fm.OnError += fm_OnError;
            fm.OnEnd += fm_OnEnd;
            fm.OnStart += fm_OnStart;
            fm.OnProgress += fm_OnProgress;
        }
예제 #16
0
        public static XmppClient InitXmppClient(string userName, string passWord, string domain, string server)
        {
            StaticClass2.xmppClient          = new XmppClient(userName, domain, passWord);
            StaticClass2.xmppClient.Hostname = server;

            //StaticClass.xmppClient.Open();

            StaticClass2.pm = new PresenceManager(xmppClient);
            StaticClass2.rm = new RosterManager(xmppClient);

            StaticClass2.muc = new MucManager(xmppClient);

            StaticClass2.fm = new FileTransferManager();
            //StaticClass.fm.OnProgress += Fm_OnProgress;
            //StaticClass.fm.OnEnd += Fm_OnEnd;

            return(StaticClass2.xmppClient);
        }
예제 #17
0
        public FrmReceiveFile(FileTransferManager ftm, FileTransferEventArgs fea)
        {
            InitializeComponent();

            fm   = ftm;
            ftea = fea;

            Text = "File transfer: " + ftea.Jid;

            lblSize.Text        = Util.HumanReadableFileSize(ftea.FileSize);
            lblFileName.Text    = ftea.Filename;
            lblDescription.Text = ftea.Description;

            fm.OnError    += fm_OnError;
            fm.OnEnd      += fm_OnEnd;
            fm.OnStart    += fm_OnStart;
            fm.OnProgress += fm_OnProgress;
        }
예제 #18
0
        public IObservable <ITransferProgress> Transfer(params string[] args)
        {
            string source      = args[0];
            string destination = args[1];

            async void Init()
            {
                await FileTransferManager.CopyWithProgressAsync(
                    source,
                    destination,
                    transferProgress.OnNext, true)
                .ContinueWith(a =>
                {
                });
            }

            Init();

            return(transferProgress.Cast <ITransferProgress>());
        }
예제 #19
0
        public void Initialize()
        {
            if (Config != null)
            {
                throw new Exception("BackupOperationManager is already initialized.");
            }

            Config       = new Configuration();
            USBHandler   = new USBInsertionEventHandler();
            DTHandler    = new DateTimeEventHandler();
            LogonHandler = new LogonEventHandler();
            USBWorker    = new BackgroundWorker();
            USBWorker.WorkerSupportsCancellation = true;
            USBWorker.DoWork += RunUSBHandler;
            DTWorker          = new BackgroundWorker();
            DTWorker.WorkerSupportsCancellation = true;
            DTWorker.DoWork += RunDateTimeHandler;
            try
            {
                LoadConfig();
                foreach (var trigger in Config.Triggers.Where(ev => ev.Enabled))
                {
                    List <Callback> callBacks = new List <Callback>();
                    foreach (var backop in Config.BackupOperations.Where(x => x.Triggers.Contains(trigger.Id)).Where(x => x.Enabled).ToList())
                    {
                        foreach (var dest in backop.Destinations)
                        {
                            callBacks.Add(new Callback(() =>
                            {
                                // Save original path
                                string ogname = dest.Path.AbsolutePath;
                                // Label the destination.
                                // It is important that the original be labeled and not the copy
                                // because we modify the destination information and save the configuration.
                                // If we modified a copy, we would lose those modifications and end up with
                                // adverse effects.
                                Labeler.Label(dest.Path, dest.Label);
                                // Make a copy of the destination
                                var labeledCopy = new Path(dest.Path);
                                // Reset the original path because we only need the label for the copy
                                dest.Path.AbsolutePath = ogname;

                                FileTransferManager.Copy(new Path(backop.Source), labeledCopy, backop.CopySubDirs, true);
                            }));
                        }
                    }

                    var triggerType = trigger.GetType();

                    // Send event to appropriate handler based on the event type
                    if (triggerType == typeof(USBInsertionEvent))
                    {
                        USBHandler.AddEvent(trigger, callBacks.ToList());
                    }
                    else if (triggerType == typeof(DateTimeEvent))
                    {
                        DTHandler.AddEvent(trigger, callBacks.ToList());
                    }
                    else if (triggerType == typeof(LogonEvent))
                    {
                        LogonHandler.AddEvent(trigger, callBacks.ToList());
                    }
                    else
                    {
                        ReportIO.WriteStatement("Invalid trigger type defined in configuration.");
                    }
                }
            }
            catch (Exception e)
            {
                ReportIO.WriteStatement(e.Message);
                Reload();
            }
        }
예제 #20
0
 public BatchValidation(FileTransferManager transferManager, List <ValidationFileInfo> validations)
 {
     this.transferManager  = transferManager;
     this.validations      = validations;
     this._readyToDownload = false;
 }
예제 #21
0
 private void button3_Click(object sender, EventArgs e)
 {
     FileTransferManager transfer = new FileTransferManager();
     string item = listBox1.SelectedItem.ToString().Remove(listBox1.SelectedItem.ToString().IndexOf(' ')).Trim();
     FileTransferResponse success = transfer.DeleteFileFromServerTempFolder(item);
 }
예제 #22
0
        public XMPPClient()
        {
            StreamNegotiationLogic = new StreamNegotiationLogic(this);
            GenericIQLogic = new GenericIQLogic(this);
            RosterLogic = new RosterLogic(this);
            PresenceLogic = new PresenceLogic(this);
            GenericMessageLogic = new GenericMessageLogic(this);
            ServiceDiscoveryLogic = new ServiceDiscoveryLogic(this);
            JingleSessionManager = new Jingle.JingleSessionManager(this);
            StreamInitiationAndTransferLogic = new StreamInitiationAndTransferLogic(this);
            PersonalEventingLogic = new PersonalEventingLogic(this);

            lock (LogicLock)
            {
                ActiveServices.Add(StreamNegotiationLogic); /// Handle SASL authentication
                ActiveServices.Add(GenericMessageLogic);
                ActiveServices.Add(GenericIQLogic); /// Handle pings and other common messages
                ActiveServices.Add(RosterLogic); /// Handles getting our roster
                ActiveServices.Add(PresenceLogic);
                ActiveServices.Add(ServiceDiscoveryLogic);
                ActiveServices.Add(JingleSessionManager);
                ActiveServices.Add(StreamInitiationAndTransferLogic);
                ActiveServices.Add(PersonalEventingLogic);
            }

            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/disco#items"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/disco#info"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("jabber:x:data"));

            // Jingle features
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:1"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:transports:ice-udp:0")); // not sure if we want ICE, makes the simple protocol difficult
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:transports:ice-udp:1"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:transports:raw-udp:0")); // raw udp much simpler
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:transports:raw-udp:1"));

            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:apps:rtp:1"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:apps:rtp:audio"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:jingle:apps:rtp:video"));

            /// si features... not sure about these
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/si"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/si/profile/file-transfer"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/ibb"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/bytestreams"));

            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/geoloc"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/geoloc+notify"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/tune"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("http://jabber.org/protocol/tune+notify"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:avatar:data"));
            this.OurServiceDiscoveryFeatureList.AddFeature(new feature("urn:xmpp:avatar:metadata"));
            //this.OurServiceDiscoveryFeatureList.AddFeature(new feature(""));

            FileTransferManager = new FileTransferManager(this);
        }
예제 #23
0
        /// <summary>
        /// Job Init processing
        /// </summary>
        /// <param name="sessionKey">Service generated GUID</param>
        /// <param name="appId">Application ID</param>
        /// <returns></returns>
        public List <RunNumberAndOutput> Processing(string sessionKey, int appId)
        {
            List <RunNumberAndOutput> objRunNumberAndOutputList = new List <RunNumberAndOutput>();

            emailList = new List <string>();
            try
            {
                String desLoc = String.Empty;
                SingletonLogger.Instance.Debug("Get application info");
                //Get application by id
                var appInfo = objApplicationRepository.Find(appId);
                if (appInfo == null)
                {
                    throw new NullReferenceException("Application details not found in database for Application Id : " + appId);
                }
                //Get applications Client information
                var clientInfo = objClientRepository.Find(appInfo.ClientId);
                if (clientInfo == null)
                {
                    throw new NullReferenceException("Client details not found in database for Client Id : " + appInfo.ClientId);
                }

                SingletonLogger.Instance.Debug("Client Id = " + clientInfo.ClientId + "\t Application Id : " + appId);
                SingletonLogger.Instance.Debug("Client Name = " + clientInfo.Name + "\t Application name : " + appInfo.Name);

                SingletonLogger.Instance.Debug("Adding Mapper...");
                mapper = new PatternMatchingMapper();
                mapper.SetCurrentDateFormat();
                mapper.SetClientAndAppDetails(clientInfo.Name, appInfo.Name);
                SingletonLogger.Instance.Debug("Mapper Added.");

                SingletonLogger.Instance.Debug("Get file transfer settings for application for File by Setting Id " + appInfo.FileTransferSettingId);
                var fileTransferSetting = objFileTransferSettingsRepository.Find(appInfo.FileTransferSettingId);
                if (fileTransferSetting == null)
                {
                    throw new Exception("No file transfer setting details found for File transfersettingId " + appInfo.FileTransferSettingId);
                }

                SingletonLogger.Instance.Debug("Get queue type for file transfer setting id " + fileTransferSetting.QueueTypeId);

                // Converting queue type from string, if not able to convert throw exception
                SingletonLogger.Instance.Debug("Checking for queue type.");
                QuequeType type = (QuequeType)Enum.ToObject(typeof(QuequeType), fileTransferSetting.QueueTypeId);
                SingletonLogger.Instance.Debug("Queue type is : " + type.ToString());

                var applicationFiles = objApplicationFileRepository.GetApplicationFileListByAppID(appInfo.ApplicationId);
                if (applicationFiles == null)
                {
                    throw new NullReferenceException("No app files (Input configuration) found in db for appId : " + appInfo.ApplicationId + "appName : " + appInfo.Name);
                }

                if (applicationFiles.Count() == 0)
                {
                    throw new InvalidDataException("No app files (Input configuration) found in db for appId : " + appInfo.ApplicationId + "appName : " + appInfo.Name);
                }

                SingletonLogger.Instance.Debug(string.Format("{0} files found for current application. ", applicationFiles.Count()));

                SingletonLogger.Instance.Debug("Processing files...");
                var validationType = ValidationType.Default;
                if (appInfo.IsBatch)
                {
                    validationType = ValidationType.Batch;
                }

                var adaptorSettings = SetLocationAdptorSettings(fileTransferSetting, appInfo, type);

                if (adaptorSettings == null)
                {
                    throw new NullReferenceException("Null validation adapter setting found when getting valid adapter.");
                }

                // Initializing transfer manager
                IFileTransferAdapter transferAdaptor = FileTransferAdapter.GetFileTransferAdapter(adaptorSettings);

                if (transferAdaptor == null)
                {
                    throw new NullReferenceException("Null transfer adapter found.");
                }

                FileTransferManager transferManager = new FileTransferManager(transferAdaptor);

                if (transferManager == null)
                {
                    throw new NullReferenceException("Null transfer manager found.");
                }

                SingletonLogger.Instance.Debug("validationType : " + validationType + "applicationFiles :" + applicationFiles.FirstOrDefault() + " transferManager :" + transferManager);

                IValidationPlugin validationAdaptor = GetValidationAdptor(validationType, applicationFiles.ToArray(), transferManager);

                if (validationAdaptor == null)
                {
                    throw new NullReferenceException("Null validation adapter found when getting valid adapter.");
                }

                // Validate
                if (validationAdaptor.Validate())
                {
                    SingletonLogger.Instance.Debug("file is  Validated by " + validationAdaptor + " now Ready to download");
                    int count = 1;
                    // If There are some valid files then insert run number information to DB.
                    if (validationAdaptor.ValidFiles.Count > 0 && validationAdaptor.Ready)
                    {
                        foreach (var file in validationAdaptor.ValidFiles)
                        {
                            RunNumberAndOutput objRunNumberAndOutput = new RunNumberAndOutput();

                            #region Create Job
                            switch (validationType)
                            {
                            case ValidationType.Default:
                                //Create run number and add entry in database
                                runNumber = GetRunNumber(clientInfo.Code, appInfo.Code, appId);
                                SingletonLogger.Instance.Debug("file is  Run in Single processing. RunNumber = " + runNumber);
                                runId = InsertRunDetails(appInfo.ApplicationId, runNumber);
                                SingletonLogger.Instance.Debug("Run details is saved in db successfully.");
                                break;

                            case ValidationType.Batch:
                                //Create run number and add entry in database
                                if (count == 1)
                                {
                                    runNumber = GetRunNumber(clientInfo.Code, appInfo.Code, appId);
                                    runId     = InsertRunDetails(appInfo.ApplicationId, runNumber);
                                }
                                SingletonLogger.Instance.Debug("Insert runDetails in db for RunNumber " + runNumber + " Client " + clientInfo.Name + " and Application " + appInfo.Name);
                                break;

                            case ValidationType.Custom:
                                throw new NotSupportedException("Functionality for custom validation not supported.");

                            default:
                                throw new InvalidOperationException("Invalid Validation type found.");
                            }
                            #endregion

                            #region Countinue Common Processing
                            mapper.SetClientAndAppDetails(runNumber);
                            if (String.IsNullOrEmpty(appInfo.HotFolder))
                            {
                                throw new Exception("Destination location is null or empty for " + appInfo.Name);
                            }

                            desLoc = mapper.EvaluateString(appInfo.HotFolder);
                            SingletonLogger.Instance.Debug("file is  downloading at " + desLoc);
                            transferAdaptor.Settings.DestinationLocation = desLoc;

                            // Add Run number and destination location
                            objRunNumberAndOutput.Output = desLoc;

                            #endregion

                            #region Download files
                            // download valid files
                            if (transferManager.DownloadFile(file))
                            {
                                SingletonLogger.Instance.Debug(file + " file is  downloaded successfully.");
                                //Inserting details to db
                                if (InsertRawFileDetails(runId, file, desLoc))
                                {
                                    SingletonLogger.Instance.Debug("file detail is saved in db in raw files");
                                    if (appInfo.IsArchive)
                                    {
                                        var arcvInpuFile = desLoc + "\\" + Path.GetFileName(file);
                                        mapper.SetFileFormat(arcvInpuFile);
                                        var outFile = mapper.EvaluateString(appInfo.ArchivePath + "\\" + appInfo.ArchiveFileName);
                                        Archieve(arcvInpuFile, outFile);
                                    }

                                    if (appInfo.IsFileMove)
                                    {
                                        try
                                        {
                                            SingletonLogger.Instance.Debug("Process start to delete file from " + file);
                                            transferManager.DeleteFile(file);
                                            SingletonLogger.Instance.Debug(file + " file is deleted from source location.");
                                        }
                                        catch (Exception ex)
                                        {
                                            throw ex;
                                        }
                                    }
                                }
                            }
                            #endregion

                            #region Create Run number and output List
                            switch (validationType)
                            {
                            case ValidationType.Default:        // Run each file as a single file
                                objRunNumberAndOutput.RunNumber = runNumber;
                                objRunNumberAndOutputList.Add(objRunNumberAndOutput);
                                break;

                            case ValidationType.Batch:
                                if (count == 1)       // If file downloading type is 'Batch' then no need to add directory in array, run file as a batch
                                {
                                    objRunNumberAndOutput.RunNumber = runNumber;
                                    objRunNumberAndOutputList.Add(objRunNumberAndOutput);
                                }
                                break;

                            case ValidationType.Custom:
                                throw new NotSupportedException("Functionality for custom validation not supported.");

                            default:
                                throw new InvalidOperationException("Invalid Validation type found.");
                            }
                            #endregion

                            #region Email

                            emailList.Add(Path.GetFileName(file));

                            #endregion

                            count++;
                        }
                    }
                    else
                    {
                        SingletonLogger.Instance.Debug("No valid files found or Files are not ready to download.");
                        objProcSessionsRepository.UpdateBySessionKey(sessionKey, Convert.ToByte(JobStatusType.Complete));
                    }
                    objProcSessionsRepository.UpdateBySessionKey(sessionKey, Convert.ToByte(JobStatusType.Complete));
                    SingletonLogger.Instance.Debug("Update values in ProcSession corresponding key" + sessionKey + " Value" + Convert.ToByte(JobStatusType.Complete));
                }

                SingletonLogger.Instance.Debug("No valid files found or Files are not ready to download.");
                objProcSessionsRepository.UpdateBySessionKey(sessionKey, Convert.ToByte(JobStatusType.Complete));

                //Prepare for email
                SendInputEmail inputEmail = new SendInputEmail();
                if (emailList != null)
                {
                    if (emailList.Count > 0)
                    {
                        inputEmail.SendInputFileEmail(appInfo, runId, emailList);
                    }
                }
                SingletonLogger.Instance.Debug("Email has been sent");
                return(objRunNumberAndOutputList);
            }
            catch (Exception ex)
            {
                objProcSessionsRepository.UpdateBySessionKey(sessionKey, Convert.ToByte(JobStatusType.Error));
                throw new Exception("Error in Job-init " + ex);
            }
        }
예제 #24
0
        /// <summary>
        /// Validate File
        /// </summary>
        /// <param name="validationType">Is batch / Default / custom</param>
        /// <param name="applicationFiles">Application files</param>
        /// <param name="transferManager">File transfer manager</param>
        /// <returns></returns>
        public IValidationPlugin GetValidationAdptor(ValidationType validationType, ApplicationFile[] applicationFiles, FileTransferManager transferManager)
        {
            IValidationPlugin validationAdaptor = null;

            try
            {
                switch (validationType)
                {
                case ValidationType.Default:
                    validationAdaptor = new DefaultValidation(transferManager, applicationFiles.Select(T => T.Mask).ToList());
                    break;

                case ValidationType.Batch:
                    var validateFileInfos = (from appFile in applicationFiles
                                             select new ValidationFileInfo(appFile.IsRequired, appFile.Mask)).ToList();
                    ///
                    validationAdaptor = new BatchValidation(transferManager, validateFileInfos);
                    break;

                case ValidationType.Custom:
                    throw new NotSupportedException("Functionality for custom validation not supported.");

                default:
                    throw new InvalidOperationException("Invalid Validation type found.");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(validationAdaptor);
        }
예제 #25
0
 public static Task CopyFile(string source, string target, Action <TransferProgress> progress, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(FileTransferManager.CopyWithProgressAsync(source, target, progress, false, false, cancellationToken));
 }
예제 #26
0
 private void FreeFilesForm_Load(object sender, EventArgs e)
 {
     fileTransferManager = new FileTransferManager();
     fileTransferManager.FilePartDownloaded += fileTransferManager_FilePartDownloaded;
 }
예제 #27
0
 public DefaultValidation(FileTransferManager transferManager, List <string> validations)
 {
     this.transferManager = transferManager;
     this.validations     = validations;
 }
예제 #28
0
        private async void MoveFiles(ObjectListView sourceListView, ObjectListView targetListView, IEnumerable <MyFileSystemInfo> sources, MyFileSystemInfo target, FileMoveMode mode = FileMoveMode.None)
        {
            if (mode == FileMoveMode.None)
            {
                return;
            }

            long totalSize        = 0;
            int  fileCount        = 0;
            long totalTransferred = 0;

            foreach (MyFileSystemInfo source in sources)
            {
                if (source.IsDirectory)
                {
                    fileCount += FileHelper.GetFolderFileCount(source.AsDirectory);
                    totalSize += FileHelper.GetFolderSize(source.AsDirectory);
                }
                else
                {
                    totalSize += source.AsFile.Length;
                    fileCount++;
                }
            }

            this.cancellationTokenSource = new CancellationTokenSource();

            FileCopyInfo info = new FileCopyInfo()
            {
                TotalSize = totalSize, FileCount = fileCount
            };

            Dictionary <string, TransferProgress> fileTransferred = new Dictionary <string, TransferProgress>();

            Action <TransferProgress> fileCopyProgress = (progress) =>
            {
                if (this.isCanceled)
                {
                    return;
                }

                if (!fileTransferred.ContainsKey(progress.SourcePath))
                {
                    fileTransferred.Add(progress.SourcePath, progress);
                }
                else
                {
                    fileTransferred[progress.SourcePath] = progress;
                }

                totalTransferred   = fileTransferred.Sum(item => item.Value.Transferred);
                info.FinishedCount = fileTransferred.Where(item => item.Value.Transferred == item.Value.Total).Count();

                info.TotalTransferred   = totalTransferred;
                info.CurrentSize        = progress.StreamSize;
                info.CurrentTransferred = progress.Transferred;
                info.CurrentPercent     = progress.Fraction;
                info.TotalPercent       = totalTransferred / (totalSize * 1.0);

                this.Feedback($"Progress:({info.FinishedCount}/{info.FileCount}) {FileHelper.FormatFileSize(info.TotalTransferred)}/{FileHelper.FormatFileSize(info.TotalSize)}, {info.TotalPercent.ToString("P")}");
            };

            try
            {
                this.isCanceled = false;
                this.isMoving   = true;

                foreach (MyFileSystemInfo source in sources)
                {
                    if (this.isCanceled)
                    {
                        break;
                    }

                    if (source.IsDirectory)
                    {
                        DirectoryInfo sourceFolder = source.AsDirectory;

                        string targetFolder = Path.Combine(target.FullName, sourceFolder.Name);

                        if (FileHelper.IsSameDrive(source.AsDirectory.FullName, targetFolder) && (mode == FileMoveMode.Cut || mode == FileMoveMode.Drag))
                        {
                            await FileTransferManager.MoveWithProgressAsync(source.AsDirectory.FullName, targetFolder, fileCopyProgress, this.cancellationTokenSource.Token);
                        }
                        else
                        {
                            await FileHelper.CopyFolder(source.AsDirectory.FullName, targetFolder, true, fileCopyProgress, this.cancellationTokenSource.Token);

                            if (mode == FileMoveMode.Cut)
                            {
                                source.AsDirectory.Delete(true);
                            }
                        }
                    }
                    else
                    {
                        FileInfo sourceFile = source.AsFile;

                        string targetFilePath = Path.Combine(target.FullName, sourceFile.Name);

                        if (FileHelper.IsSameDrive(sourceFile.DirectoryName, target.FullName) && (mode == FileMoveMode.Cut || mode == FileMoveMode.Drag))
                        {
                            await FileHelper.MoveFile(sourceFile.FullName, targetFilePath, fileCopyProgress, this.cancellationTokenSource.Token);
                        }
                        else
                        {
                            await FileHelper.CopyFile(sourceFile.FullName, targetFilePath, fileCopyProgress, this.cancellationTokenSource.Token);

                            if (mode == FileMoveMode.Cut)
                            {
                                sourceFile.Delete();
                            }
                        }
                    }
                }

                this.MoveObjects(sourceListView, targetListView, sources, target, mode);
            }
            catch (Exception ex)
            {
                this.Feedback(ex.Message, true);
            }
            finally
            {
                this.isMoving = false;

                if (mode != FileMoveMode.Copy)
                {
                    this.RefreshListView(this.navigator);
                }

                this.RefreshListView(this.lvFiles);
            }
        }