Example #1
0
        private void ThreadProc()
        {
            Log.Verbose("Starting the thread proc.");
            _stopEvent.Reset();
            string SourceDirectoryPath;
            string FailedDirectoryPath;
            string ManagementServerAddress;
            string ManagementServerPassword;

            if (Settings.Default.SourceDirectory.Length == 0)
            {
                Log.WriteError("SourceDirectory is empty. Exiting.");
                _done = true;
                return;
            }

            ManagementServerAddress = Settings.Default.ManagementServerAddress;
            if (ManagementServerAddress.Length == 0)
            {
                Log.WriteError("ManagementServerAddress is empty. Exiting.");
                _done = true;
                return;
            }

            if (Settings.Default.IsIdEncrypted)
                ManagementServerPassword = Crypto.DecryptFromBase64String(
                    Settings.Default.ManagementServerId);
            else
                ManagementServerPassword = Settings.Default.ManagementServerId;

            SourceDirectoryPath = Settings.Default.SourceDirectory;
            FailedDirectoryPath = Path.Combine(SourceDirectoryPath, "Failed");
            DirectoryInfo SourceDirectoryInfo = TryGetDirectory(SourceDirectoryPath);
            if (SourceDirectoryInfo == null)
            {
                Log.WriteError("SourceDirectoryInfo is empty. Exiting.");
                _done = true;
                return;
            }
            DirectoryInfo FailedDirectoryInfo = TryGetDirectory(FailedDirectoryPath);
            if (FailedDirectoryInfo == null)
            {
                Log.WriteError("FailedDirectoryInfo is empty. Exiting.");
                _done = true;
                return;
            }

            Log.Verbose("Entering thread loop.");
            while (!_done)
            {
                try
                {
                    FileInfo[] FileInfoList = SourceDirectoryInfo.GetFiles("*.xml");
                    var SortedFileInfoList = new SortedList(
                        new FileInfoDateComparer(FileInfoDateComparer.DateCompareType.CreationTime));
                    foreach (FileInfo fi in FileInfoList)
                    {
                        if (!SortedFileInfoList.Contains(fi))
                            SortedFileInfoList.Add(fi, fi);
                        else // this should never happen, but it did! what?!??!
                            Log.WriteError("For some reason, " + fi.FullName + " showed up twice in the directory!");
                    }
                    foreach (DictionaryEntry entry in SortedFileInfoList)
                    {
                        if (_done)
                            break;
                        var xmlFileInfo = entry.Value as FileInfo;
                        var transferFile = new ScheduledFTPFile();
                        ScheduledFTPFile.FileUploadRow row;
                        try
                        {
                            transferFile.ReadXml(xmlFileInfo.FullName);
                        }
                        catch (Exception e)
                        {
                            Log.WriteError(xmlFileInfo.FullName + " Exception: " + e.Message);
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            continue;
                        }
                        row = transferFile.FileUpload[0];
                        string wmvPath = row.FilePath;
                        if (!File.Exists(wmvPath))
                        {
                            Log.WriteLog(wmvPath + " does not exist. Moving to Failed directory.");
                            try
                            {
                                File.Move(xmlFileInfo.FullName,
                                          Path.Combine(FailedDirectoryInfo.FullName, xmlFileInfo.Name));
                            }
                            catch (Exception e)
                            {
                                Log.WriteError("Could not move " + xmlFileInfo.FullName + ": " + e.Message);
                            }
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            continue;
                        }

                        // open the file and see if it is in use... if it is, continue and try again...
                        // and keep trying until WME lets go of the file... sheesh
                        try
                        {
                            Log.WriteLog("Checking to see if " + wmvPath + " is still held by the encoder...");
                            var fileCheck = new FileStream(wmvPath, FileMode.Open, FileAccess.ReadWrite);
                            fileCheck.Close();
                            Log.WriteLog(wmvPath + " is free to upload.");
                        }
                        catch (Exception e)
                        {
                            if (e.Message.IndexOf("because it is being used") != -1)
                            {
                                Log.WriteLog("Yep, {0} is in use. Will try again... and again.", wmvPath);
                                continue;
                            }
                            // just try again anyway...
                            Log.WriteError("Error: {0} error: {1}", wmvPath, e.Message);
                            continue;
                        }

                        if (FtpSession.State != FtpState.Disconnected)
                        {
                            Log.WriteLog("Closing FTP session at {0}", (IPEndPoint) FtpSession.RemoteEndPoint);
                            FtpSession.Disconnect();
                        }
                        string user, pass;
                        if (row.EncryptedCredentials)
                        {
                            user = Crypto.DecryptFromBase64String(row.User);
                            pass = Crypto.DecryptFromBase64String(row.Password);
                        }
                        else
                        {
                            user = row.User;
                            pass = row.Password;
                        }
                        try
                        {
                            Log.WriteLog("Connecting to ftp server at {0}:{1} ...", row.ServerAddress, row.ServerPort);
                            FtpSession.Connect(row.ServerAddress, row.ServerPort);
                            FtpSession.Login(user, pass);
                        }
                        catch (Exception ftpex)
                        {
                            Log.WriteError("Could not connect to " + row.ServerAddress + ":" + row.ServerPort +
                                           ftpex.Message);
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            Log.Verbose("Pausing for " + Settings.Default.WaitTimeAfterUploadFailureInSeconds + " seconds.");
                            Thread.Sleep(Settings.Default.WaitTimeAfterUploadFailureInSeconds*1000); // sleep for awhile after a failure
                            continue;
                        }

                        try
                        {
                            lock (_statusLock)
                            {
                                StatusContract.AttemptedLastUploadTime = DateTime.Now;
                                StatusContract.AttemptedTransferCountSinceStartup++;
                                StatusContract.AttemptedLastUploadFileName = wmvPath;
                            }
                            _uploadingFile = new FileInfo(wmvPath);
                            string wmvName = Path.GetFileName(wmvPath);
                            Log.WriteLog("Transferring {0}", wmvPath);

                            long bytesSent = FtpSession.PutFile(wmvPath, wmvName);

                            Log.WriteLog(string.Format("Transfer complete. {0} bytes sent in file {1}.",
                                                       bytesSent, wmvPath));

                            Log.WriteLog("Connecting to Oyster system at " + ManagementServerAddress);

                            var oyster = new OysterClassLibrary.Oyster(
                                ManagementServerAddress, ManagementServerPassword);
                            Recording rec =
                                oyster.GetRecordingByName(wmvName);
                            if (rec == null)
                            {
                                throw new ApplicationException(wmvName + " is not a valid recording on the server.");
                            }
                            rec.IsReady = true;
                            Log.Verbose("Recording is ready: " + wmvName);

                            xmlFileInfo.Delete();
                            Log.WriteLog("Deleted : " + xmlFileInfo.Name);
                            File.Delete(wmvPath);
                            Log.WriteLog("Deleted : " + wmvName);
                            OnFireUploadedEvent(xmlFileInfo.FullName, true);
                            _uploadingFile = null;
                            lock (_statusLock)
                            {
                                StatusContract.TransferCountSinceStartup++;
                                StatusContract.LastUploadTime = StatusContract.AttemptedLastUploadTime;
                                StatusContract.AttemptedLastUploadFileName = wmvPath;
                                StatusContract.LastUploadTimeSpan = DateTime.Now - StatusContract.LastUploadTime;
                            }
                        }
                        catch (Exception upex)
                        {
                            Log.WriteLog("Transfer failed: " + xmlFileInfo.FullName + ": " + upex.Message);
                            Log.Verbose("Pausing for " + Settings.Default.WaitTimeAfterUploadFailureInSeconds + " seconds.");
                            Thread.Sleep(Settings.Default.WaitTimeAfterUploadFailureInSeconds*1000); // sleep for awhile after a failure
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            _uploadingFile = null;
                            continue;
                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception mainex)
                {
                    lock (_statusLock)
                    {
                        StatusContract.LastException = mainex;
                    }
                    Log.WriteError("Exception in main loop: " + mainex);

                    try
                    {
                        FtpSession.Disconnect();
                    }
                    catch (Exception ftpex)
                    {
                        lock (_statusLock)
                        {
                            StatusContract.LastException = ftpex;
                        }
                        Log.Verbose("Exception on ftp disconnect: " + ftpex);
                    }
                }
            }
            Log.Verbose("Thread loop exited.");
            _stopEvent.Set();
        }
Example #2
0
        private static void MakeScheduleFiles(string SourceDirectoryPath, int fileCountToMake, IOyster oyster,
		                                      string managementServerAddress, int managementServerPort)
        {
            Random rnd;

            for (int i = 0; i < fileCountToMake; i++)
            {
                string guidName = Guid.NewGuid().ToString();
                string wmvName = guidName + ".wmv";
                rnd = new Random();
                Console.WriteLine(Environment.NewLine + "{0} of {1}", i + 1, fileCountToMake);
                Console.WriteLine("Generating random data...");
                var data = new byte[rnd.Next(0x4000000)];

                rnd.NextBytes(data);

                Console.WriteLine("Writing random data to file...");
                string wmvFilePath = Path.Combine(SourceDirectoryPath, wmvName);
                var fs = new FileStream(wmvFilePath, FileMode.Create);
                fs.Write(data, 0, data.Length);
                Console.WriteLine("Created " + wmvFilePath);
                fs.Close();

                Console.WriteLine("Creating Scheduled FTP file...");
                var uploadFile =
                    new ScheduledFTPFile();
                uploadFile.FileUpload.AddFileUploadRow(wmvFilePath,
                                                       managementServerAddress, managementServerPort,
                                                       "", "", DateTime.MinValue,
                                                       "KQp6oeYCF/x+KqUSZ2Q9bg==",
                                                       "6UUOxPUaawXGQnOYItIeoA==",
                                                       true);
                string guidFilePath = Path.Combine(SourceDirectoryPath, guidName);
                uploadFile.WriteXml(guidFilePath + ".xml");

                if (oyster != null)
                {
                    //string userName = Crypto.DecryptFromBase64String("KQp6oeYCF/x+KqUSZ2Q9bg==");
                    DateTime bogusDate = DateTime.Parse("1753/01/01");

                    Recording recording = oyster.CreateRecording(wmvName, bogusDate.ToString(), 23, 20, 80, null, null);
                    if (recording == null)
                    {
                        Console.WriteLine("*** Could not add {0}.wmv to the Oyster database ***", guidFilePath);
                    }
                    else
                    {
                        Console.WriteLine("\tAdded {0}.wmv to the Oyster database.", guidFilePath);
                    }
                }
                Console.WriteLine("Created {0}.xml in the current directory.", guidFilePath);
            }
        }