示例#1
0
        public async Task <bool> Cleanup(StatusFile sf)
        {
            if (sf.obsoletes.IsNullOrEmpty())
            {
                return(true);
            }

            var bkp     = st.status.ToBucketKeyPair();
            var prefix  = $"{bkp.key}/{S3HashStoreStatus.UploadStatusFilePrefix}";
            var success = true;

            await ParallelEx.ForEachAsync(sf.obsoletes, async file =>
            {
                var cts = new CancellationTokenSource();

                var id        = file.TrimStart(prefix).TrimEnd(".json").ToLongOrDefault(0);
                var folderBKP = st.destination.ToBucketKeyPair();
                var result    = await s3h.DeleteObjectAsync(
                    bucketName: folderBKP.bucket,
                    key: file,
                    throwOnFailure: false,
                    cancellationToken: cts.Token).TryCancelAfter(cts.Token, msTimeout: st.timeout);

                if (success)
                {
                    Console.WriteLine($"Status file: '{folderBKP.bucket}/{file}' was removed.");
                }
                else
                {
                    Console.WriteLine($"Failed to remove status file: '{folderBKP.bucket}/{file}'.");
                }
            }, maxDegreeOfParallelism : parallelism);

            return(success);
        }
示例#2
0
        /// <summary>
        /// Функция загружает фигуры из файла и возвращает массив типа Object[]
        /// </summary>
        public static Object[] LoadFiguresFromFile()
        {
            string currFullNameFile = Environment.CurrentDirectory + "\\FiguresOfGeometry.bin";

            Console.WriteLine("Будет загружен файл с сохранёнными фигурами {0}  (Y/N) Y-",
                              currFullNameFile);
            if (Console.ReadLine()?.ToUpper() == "N")
            {
                do
                {
                    Console.WriteLine("Введите полное имя к файлу");
                    currFullNameFile = Console.ReadLine();
                } while (currFullNameFile == "");
            }
            Object[] arrayOfFigures;

            using (FileManager fm = new FileManager())
            {
                StatusFile statusLoad = fm.LoadFromFile(currFullNameFile, out arrayOfFigures);
                ConsoleWriteColorText(StatusFileMsg.Msg[(int)statusLoad] + "\n",
                                      (statusLoad == StatusFile.Ok) ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed);
            }

            return(arrayOfFigures);
        }
示例#3
0
        /// <summary>
        /// Метод сохраняет массив типа Object[] в файл
        /// </summary>
        /// <param name="arrayOfFigures"></param>
        public static void SaveFiguresToFile(ref Object[] arrayOfFigures)
        {
            if (arrayOfFigures == null)
            {
                throw new ArgumentNullException(nameof(arrayOfFigures));
            }
            string currFullNameFile = Environment.CurrentDirectory + "\\FiguresOfGeometry.bin";

            Console.WriteLine("Сгенерированные объекты будут сохранены в файл {0}\n\tЖелаете изменить имя файла? (Y/N) N-",
                              currFullNameFile);
            if (Console.ReadLine()?.ToUpper() == "Y")
            {
                do
                {
                    Console.WriteLine("Введите новое полное имя файла");
                    currFullNameFile = Console.ReadLine();
                } while (currFullNameFile == "");
            }

            using (FileManager fm = new FileManager())
            {
                StatusFile statusSave = fm.SaveToFile(currFullNameFile, arrayOfFigures);
                ConsoleWriteColorText((statusSave == StatusFile.Ok) ? "Фигуры сохранены!\n" :
                                      StatusFileMsg.Msg[(int)statusSave],
                                      (statusSave == StatusFile.Ok) ? ConsoleColor.DarkYellow :
                                      ConsoleColor.DarkRed);
            }
        }
示例#4
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            IReadOnlyList <GeofenceStateChangeReport> reports = GeofenceMonitor.Current.ReadReports();

            foreach (var report in reports)
            {
                if ((report.NewState != GeofenceState.None) &&
                    (report.NewState != GeofenceState.Removed))
                {
                    await StatusFile.AddStatusEntry(
                        report.Geofence.Id,
                        report.NewState == GeofenceState.Entered?EntryType.EnteredZone : EntryType.ExitedZone);
                }
            }

            XmlDocument template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

            NotificationTemplateHelper.CompleteToastOrTileTemplate(
                template,
                new string[]
            {
                "One or more of our fences has been crossed"
            },
                null);

            ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.Show(new ToastNotification(template));

            deferral.Complete();
        }
        /// <summary>
        /// Converts the file from one format to another.
        /// </summary>
        /// <param name="p_filename">The command file
        /// (.im_command, .ex_command, .pv_command)</param>
        /// <param name="p_language">the language of the directory
        /// the file was written in</param>
        public void Convert(string p_fileName, string p_language)
        {
            lock (locker)
            {
                try
                {
                    ResetState();
                    m_statusFileName = p_fileName.Substring(
                        0, p_fileName.Length - FILE_EXT_LEN) + "status";
                    DetermineConversionValues(p_fileName);

                    m_log.Log("[Idml]: The converter will process file: " + m_originalFileName);
                    InDesignApplication indesignApp = InDesignApplication.getInstance();

                    //The status name will be changed to *.pv_status from *.status
                    //when execute the preview command(*.pv_command) file
                    indesignApp.ConvertInddToPDF(m_originalFileName, m_newFileName, m_masterTranslated, m_translateHiddenLayer);


                    StatusFile.WriteSuccessStatus(m_statusFileName,
                                                  m_originalFileName + " was converted successfully.");

                    m_log.Log("[Idml]: Converted successfully to: " + m_newFileName);
                }
                catch (Exception e)
                {
                    Logger.LogError("[Idml]: Idml Conversion Failed", e);
                    StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
                }
                finally
                {
                    DeleteInputFile(p_fileName);
                }
            }
        }
        /// <summary>
        /// Converts the file from one format to another.
        /// </summary>
        /// <param name="p_filename">The command file (.im_command, .ex_command)</param>
        /// <param name="p_language">the language of the directory the file was written in</param>
        public void Convert(string p_fileName, string p_language)
        {
            try
            {
                ResetState();

                m_statusFileName = p_fileName.Substring(
                    0, p_fileName.Length - FILE_EXT_LEN) + "status";
                DetermineConversionValues(p_fileName);

                m_log.Log("Processing file " + m_originalFileName);

                CreatePowerPointAppClass();
                OpenDocument();
                SaveDocument();

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("Converted successfully to " + m_newFileName);
            }
            catch (Exception e)
            {
                Logger.LogError("PowerPoint XP Conversion Failed", e);
                StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
            }
            finally
            {
                DeleteInputFile(p_fileName);
            }
        }
        public void CreateStatusFileTest()
        {
            FileHelper.FileSystem = new MockFileSystem(new Dictionary <string, MockFileData>());
            StatusFile statusFile     = new StatusFile("site1");
            string     statusFilePath = @"c:\site1\status.xml";

            Assert.IsFalse(FileHelper.FileSystem.File.Exists(statusFilePath));
            statusFile.LoadOrCreate();
            Assert.IsTrue(FileHelper.FileSystem.File.Exists(statusFilePath));
        }
        public void Convert(string p_filename, string p_srcLanguage)
        {
            Process p = null;

            try
            {
                DetermineConversionValues(p_filename);

                m_statusFileName = m_baseFileName + "status";


                m_log.Log("Processing file " + m_originalFileName);

                CleanResultFile();
                CleanTempFiles();
                p = OpenDoc();

                if (m_newFileName.EndsWith("pdf"))
                {
                    Thread tpsThread = new Thread(new ThreadStart(CheckTps));
                    tpsThread.Start();
                }

                WaitResultFile();

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("Converted successfully to " + m_newFileName);
            }
            catch (Exception e)
            {
                Logger.LogError("FrameMaker Conversion Failed", e);
                StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
            }
            finally
            {
                DeleteInputFile(p_filename);

                try
                {
                    if (p != null)
                    {
                        p.Kill();
                    }
                }
                catch { }

                CloseDistiller();

                CleanTempFiles();
            }
        }
        private void VerifyStatusFile(StatusFileTestData expected, StatusFile result)
        {
            Assert.AreEqual(expected.BytesCopied, result.BytesCopied, "bytes copied");
            Assert.AreEqual(expected.Complete, result.Complete, "complete");

            VerifyDateTime(expected.EndTime, result.EndTime);
            VerifyDateTime(expected.StartTime, result.StartTime);

            Assert.AreEqual(expected.ObjectsAdded, result.ObjectsAdded, "objects added");
            Assert.AreEqual(expected.ObjectsDeleted, result.ObjectsDeleted, "objects deleted");
            Assert.AreEqual(expected.ObjectsUpdated, result.ObjectsUpdated, "objects updated");
            Assert.AreEqual(expected.ParametersChanged, result.ParametersChanged, "parameters changed");
            Assert.AreEqual(expected.State, result.State, "state");
        }
示例#10
0
        public static void WriteSyncFile(this SyncTarget st, StatusFile sf)
        {
            var ds = PathEx.RuntimeCombine(st.sync, st.id, "sync.json").ToFileInfo();

            ds.Directory.TryCreate();

            if (ds.TryCreate())
            {
                ds.WriteAllText(sf.JsonSerialize(Newtonsoft.Json.Formatting.Indented));
            }
            else
            {
                throw new Exception($"Failed to create status '{ds?.Directory?.FullName ?? "undefined"}' for the Sync Target '{st?.id ?? "undefined"}'.");
            }
        }
        /// <summary>
        /// Converts the file from one format to another.
        /// </summary>
        /// <param name="p_filename">The command file (.im_command, .ex_command)</param>
        /// <param name="p_language">the language of the directory the file was written in</param>
        public void Convert(string p_fileName, string p_language)
        {
            try
            {
                ResetState();

                m_statusFileName = p_fileName.Substring(
                    0, p_fileName.Length - FILE_EXT_LEN) + "status";
                DetermineConversionValues(p_fileName);

                m_log.Log("Processing file " + m_originalFileName);

                GfxdataHandler handler = null;
                if (!m_newFileName.EndsWith(".pdf"))
                {
                    string htmFile = m_conversionType == ConversionType.IMPORT ? m_newFileName : m_originalFileName;
                    handler = new GfxdataHandler(htmFile, OfficeFormat.Pptx, m_log);

                    if (m_handleGfxdata && m_conversionType == ConversionType.EXPORT)
                    {
                        handler.HandleConvertBack();
                    }
                }

                CreatePowerPointAppClass();
                OpenDocument();
                SaveDocument();

                if (handler != null && m_handleGfxdata && m_conversionType == ConversionType.IMPORT)
                {
                    handler.HandleConvert();
                }

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("Converted successfully to " + m_newFileName);
            }
            catch (Exception e)
            {
                Logger.LogError(m_log, "PowerPoint Conversion Failed", e);
                StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
            }
            finally
            {
                DeleteInputFile(p_fileName);
            }
        }
        public void SaveStatusFileTest()
        {
            string   profileName = "site";
            DateTime startTime   = DateTime.Now;
            DateTime endTime     = DateTime.Now.AddHours(1);

            StatusFileTestData[] tests = new StatusFileTestData[]
            {
                new StatusFileTestData()
                {
                    State             = DeployState.Succeeded,
                    ObjectsAdded      = 10,
                    ObjectsUpdated    = 20,
                    ObjectsDeleted    = 30,
                    ParametersChanged = 40,
                    BytesCopied       = 50,
                    StartTime         = DateTime.UtcNow,
                    EndTime           = DateTime.UtcNow.AddHours(1),
                    Complete          = true
                }
            };

            System.IO.Abstractions.FileBase MockFile = FileHelper.FileSystem.File;

            for (int i = 0; i < tests.Length; i++)
            {
                StatusFile statusFile = new StatusFile(profileName);
                statusFile.State             = tests[i].State;
                statusFile.ObjectsAdded      = tests[i].ObjectsAdded;
                statusFile.ObjectsUpdated    = tests[i].ObjectsUpdated;
                statusFile.ObjectsDeleted    = tests[i].ObjectsDeleted;
                statusFile.ParametersChanged = tests[i].ParametersChanged;
                statusFile.BytesCopied       = tests[i].BytesCopied;
                statusFile.StartTime         = tests[i].StartTime;
                statusFile.EndTime           = tests[i].EndTime;
                statusFile.Complete          = tests[i].Complete;

                statusFile.Save();

                Assert.IsTrue(MockFile.Exists(@"c:\" + profileName + @"\status.xml"));

                statusFile = new StatusFile(profileName);
                statusFile.LoadOrCreate();

                VerifyStatusFile(tests[i], statusFile);
            }
        }
示例#13
0
        private void FillForm()
        {
            StatusFile statusFile = DataMethod.CheckStatusFile(_fileStruct.fileId);

            _statusReview = (statusFile == StatusFile.Review) ? true : false;

            this.RefreshTable();
            this.comboBoxStatusFile.Text = (statusFile == StatusFile.Project) ? "Проект" : "Черновик";
            this.Text                    = "Свойства файла: " + _fileStruct.name + _fileStruct.expansion.ToLower();
            this.textBoxName.Text        = _fileStruct.name;
            this.richTextBoxComment.Text = _fileStruct.comment;
            this.textBoxExpansion.Text   = _fileStruct.expansion.ToUpper();
            this.textBoxAT.Text          = _changeStruct.dateTimeAT.ToString();
            this.textBoxUP.Text          = _changeStruct.dateTimeUP.ToString();
            this.linkLabelLogin.Text     = _userStruct.login;
            this.textBoxSize.Text        = FileMethod.FileSize(Convert.ToDouble(_fileStruct.size));
        }
示例#14
0
        private void DoConvert(string p_fileName, string p_language, bool retry)
        {
            try
            {
                ResetState();
                m_statusFileName = p_fileName.Substring(
                    0, p_fileName.Length - FILE_EXT_LEN) + "status";
                DetermineConversionValues(p_fileName);

                if (m_newFileName.EndsWith(PDF))
                {
                    m_statusFileName = p_fileName.Substring(
                        0, p_fileName.Length - FILE_EXT_LEN) + "pdf.status";
                }

                m_log.Log("Processing file " + m_originalFileName);

                CreateWordAppClass();
                OpenWordDoc();
                SaveDocument();

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("Converted successfully to " + m_newFileName);
            }
            catch (Exception e)
            {
                string emsg = e.StackTrace.ToString();
                if (retry && emsg != null && emsg.Contains("RPC_E_SERVERCALL_RETRYLATER"))
                {
                    // sleep 10 seconds
                    Thread.Sleep(1000 * 10);
                    QuitWord();
                    Thread.Sleep(1000 * 10);

                    m_log.Log("Retry conversion after exception: " + emsg);
                    DoConvert(p_fileName, p_language, false);
                }
                else
                {
                    Logger.LogError(m_log, "Word 2007 Conversion Failed", e);
                    StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
                }
            }
        }
示例#15
0
        /// <summary>
        /// Converts the file from one format to another.
        /// </summary>
        /// <param name="p_filename">The command file
        /// (.im_command, .ex_command)</param>
        /// <param name="p_language">the language of the directory
        /// the file was written in</param>
        public void Convert(string p_fileName, string p_language)
        {
            try
            {
                ResetState();
                m_statusFileName = p_fileName.Substring(
                    0, p_fileName.Length - FILE_EXT_LEN) + "status";
                DetermineConversionValues(p_fileName);
                FileInfo      file = new FileInfo(p_fileName);
                DirectoryInfo dir  = file.Directory;

                m_log.Log("Processing file " + m_originalFileName);

                CommandUtil comUtil = new CommandUtil();

                // process files
                if (!m_isConvertBack)
                {
                    List <TranslateUnit3RD> units = Extract(comUtil);
                    String xml = XmlUtil3RD.OutputTranslateUnits(units);
                    XmlUtil3RD.WriteXml(xml, m_xmlFileName, "UTF-8");
                }
                else
                {
                    String xml = XmlUtil3RD.ReadFile(m_xmlFileName, "UTF-8");
                    List <TranslateUnit3RD> units = XmlUtil3RD.ParseTranslateUnits(xml);
                    int c = units.Count;
                    Merge(comUtil, units);
                }

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("Converted successfully to " + m_newFileName);
            }
            catch (Exception e)
            {
                Logger.LogError(m_log, "Windows Portable Executable Conversion Failed", e);
                StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
            }
            finally
            {
                DeleteInputFile(p_fileName);
            }
        }
        /// <summary>
        /// Converts the file from one format to another.
        /// </summary>
        /// <param name="p_filename">The command file
        /// (.im_command, .ex_command, .pv_command)</param>
        /// <param name="p_language">the language of the directory
        /// the file was written in</param>
        public void Convert(string p_fileName, string p_language)
        {
            try
            {
                ResetState();
                m_statusFileName = p_fileName.Substring(
                    0, p_fileName.Length - FILE_EXT_LEN) + "status";
                DetermineConversionValues(p_fileName);

                m_log.Log("[Indesign]: The converter will process file: " + m_originalFileName + "\r\n");

                InDesignApplication indesignApp = InDesignApplication.getInstance();
                if (m_conversionType == ConversionType.EXPORT)
                {
                    indesignApp.ConvertXmlToIndd(m_originalFileName, m_newFileName, m_masterTranslated);
                }
                else if (m_conversionType == ConversionType.PREVIEW)
                {
                    //The status name will be changed to *.pv_status from *.status
                    //when execute the preview command(*.pv_command) file
                    m_statusFileName = m_statusFileName.Substring(0,
                                                                  m_statusFileName.LastIndexOf(".")) + ".pv_status";
                    indesignApp.ConvertInddToPDF(m_originalFileName, m_newFileName, m_masterTranslated);
                }
                else
                {
                    indesignApp.ConvertInddToXml(m_originalFileName, m_newFileName, m_masterTranslated);
                }

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("[Indesign]: Converted successfully to: " + m_newFileName);
            }
            catch (Exception e)
            {
                Logger.LogError("[Indesign]: InDesign Conversion Failed", e);
                StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
            }
            finally
            {
                DeleteInputFile(p_fileName);
            }
        }
        /// <summary>
        /// Converts the file from one format to another.
        /// </summary>
        /// <param name="p_filename">The command file
        /// (.im_command, .ex_command)</param>
        /// <param name="p_language">the language of the directory
        /// the file was written in</param>
        public void Convert(string p_fileName, string p_language)
        {
            try
            {
                ResetState();
                m_statusFileName = p_fileName.Substring(
                    0, p_fileName.Length - FILE_EXT_LEN) + "status";
                DetermineConversionValues(p_fileName);

                m_log.Log("The converter will process file: " + m_originalFileName + "\r\n");

                InDesignApplication indesignApp = InDesignApplication.getInstance();
                if (m_conversionType == ConversionType.EXPORT)
                {
                    indesignApp.ConvertXmlToIndd(m_originalFileName, m_newFileName);
                }
                else
                {
                    indesignApp.ConvertInddToXml(m_originalFileName, m_newFileName);
                }

                StatusFile.WriteSuccessStatus(m_statusFileName,
                                              m_originalFileName + " was converted successfully.");

                m_log.Log("Converted successfully to: " + m_newFileName);
            }
            catch (Exception e)
            {
                Logger.LogError("InDesign Conversion Failed", e);
                StatusFile.WriteErrorStatus(m_statusFileName, e, (int)1);
            }
            finally
            {
                DeleteInputFile(p_fileName);
            }
        }
示例#18
0
        public async Task <StatusFile> GetStatusFile(SyncTarget st, string statusPrefix)
        {
            var bkp    = st.status.ToBucketKeyPair();
            var prefix = $"{bkp.key}/{statusPrefix}";
            var list   = await GetStatusList(st, statusPrefix);

            var id = list.IsNullOrEmpty() ? 0 : list.Last().Key.TrimStart(prefix).TrimEnd(".json").ToLongOrDefault(0); //latest staus id

            id = id <= 0 ? DateTimeEx.TimestampNow() : id;
            var key = $"{prefix}{id}.json";

            if (list.IsNullOrEmpty() || id <= 0)
            {
                return(new StatusFile()
                {
                    id = id.ToString(),
                    timestamp = DateTimeEx.UnixTimestampNow(),
                    bucket = bkp.bucket,
                    key = key,
                    location = $"{bkp.bucket}/{key}",
                    finalized = false,
                    version = 0
                });
            }

            var status = await _S3Helper.DownloadJsonAsync <StatusFile>(bkp.bucket, key, throwIfNotFound : true)
                         .Timeout(msTimeout: st.timeout)
                         .TryCatchRetryAsync(maxRepeats: st.retry);

            var elapsed = (DateTime.UtcNow - long.Parse(status?.id ?? "0").ToDateTimeFromTimestamp()).TotalSeconds;

            if (status == null || (status.finalized == true && st.retention > 0 && elapsed > st.retention))
            {
                id     = DateTimeEx.TimestampNow();
                key    = $"{prefix}{id}.json";
                status = new StatusFile()
                {
                    id        = id.ToString(),
                    timestamp = DateTimeEx.UnixTimestampNow(),
                    bucket    = bkp.bucket,
                    key       = key,
                    location  = $"{bkp.bucket}/{key}",
                    finalized = false,
                    version   = 0
                };
            }

            if (st.cleanup && st.rotation > 0 && list.Count > st.rotation)
            {
                var validStatus = new List <StatusFile>();
                list.Reverse();
                foreach (var f in list) //find non obsolete files
                {
                    var s = await _S3Helper.DownloadJsonAsync <StatusFile>(bkp.bucket, f.Key, throwIfNotFound : false)
                            .Timeout(msTimeout: st.timeout)
                            .TryCatchRetryAsync(maxRepeats: st.retry);

                    if (s == null)
                    {
                        continue;
                    }

                    if (s.finalized && s.id.ToLongOrDefault(0) > 0)
                    {
                        validStatus.Add(s);
                    }
                    else if (!s.finalized || status.id == id.ToString())
                    {
                        validStatus.Add(s);
                    }

                    if (validStatus.Count > st.rotation)
                    {
                        break;
                    }
                }

                status.obsoletes = list.Where(x => !validStatus.Any(v => v.key.ToLower().Trim() == x.Key.ToLower().Trim()))
                                   .Select(x => x.Key).ToArray(); //status files that are obsolete
            }

            return(status);
        }
示例#19
0
 /// <summary>
 /// Writes out error information to the status file
 /// </summary>
 /// <param name="p_ex">some exception</param>
 public void writeErrorStatus(Exception p_ex)
 {
     StatusFile.WriteErrorStatus(m_baseFileName + ".status", p_ex, m_errorCode);
 }
示例#20
0
 /// <summary>
 /// Writes out that the given PDF file was converted successfully
 /// </summary>
 public void writeSuccessStatus()
 {
     StatusFile.WriteSuccessStatus(m_baseFileName + ".status",
                                   m_baseFileName + ".pdf was converted successfully.");
 }
        public void LoadStatusFileTest()
        {
            StatusFile statusFile  = null;
            string     profileName = "site";

            List <string> tests = new List <string>()
            {
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<status>" +
                "</status>",

                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<status>" +
                "    <state>failed</state>" +
                "    <startTime>3/17/2014</startTime>" +
                "    <endTime>3/18/2014</endTime>" +
                "    <complete>true</complete>" +
                "    <objectsAdded>100</objectsAdded>" +
                "    <objectsUpdated>1000</objectsUpdated>" +
                "    <objectsDeleted>10000</objectsDeleted>" +
                "    <parametersChanged>100000</parametersChanged>" +
                "    <bytesCopied>1000000</bytesCopied>" +
                "</status>",

                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<status>" +
                "    <state>InvalidState</state>" +
                "    <startTime>InvalidTime</startTime>" +
                "    <endTime>InvalidTime</endTime>" +
                "    <complete>NotBool</complete>" +
                "    <objectsAdded>NotNum</objectsAdded>" +
                "    <objectsUpdated>NotNum</objectsUpdated>" +
                "    <objectsDeleted>NotNum</objectsDeleted>" +
                "    <parametersChanged>NotNum</parametersChanged>" +
                "    <bytesCopied>NotNum</bytesCopied>" +
                "</status>",
            };

            var expected = new[] {
                new StatusFileTestData(),
                new StatusFileTestData()
                {
                    State             = DeployState.Failed,
                    StartTime         = DateTime.Parse("3/17/2014"),
                    EndTime           = DateTime.Parse("3/18/2014"),
                    Complete          = true,
                    ObjectsAdded      = 100,
                    ObjectsUpdated    = 1000,
                    ObjectsDeleted    = 10000,
                    ParametersChanged = 100000,
                    BytesCopied       = 1000000
                },
                new StatusFileTestData()
            };


            for (int i = 0; i < tests.Count; i++)
            {
                FileHelper.FileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
                {
                    {
                        @"c:\site\status.xml", new MockFileData(tests[i])
                    }
                });

                statusFile = new StatusFile(profileName);
                statusFile.LoadOrCreate();

                VerifyStatusFile(expected[i], statusFile);
            }
        }
示例#22
0
        async Task RebuildListOfNotifications()
        {
            string[] fileEntries = await StatusFile.ReadAllStatusEntries();

            this.listNotifications.ItemsSource = fileEntries;
        }
        public DeploymentChangeSummary DeployContentToOneSite(
            IConfigRepository repository,
            string contentPath,
            string publishSettingsFile)
        {
            var sourceBaseOptions = new DeploymentBaseOptions();
            DeploymentBaseOptions destBaseOptions;
            string siteName = SetDestBaseOptions(publishSettingsFile, out destBaseOptions);
            bool   success  = true;
            DeploymentChangeSummary summary = null;

            AddSkips(repository.Config.SkipRules, sourceBaseOptions, destBaseOptions);

            Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile));

            using (StatusFile status = new StatusFile(siteName))
                using (LogFile logFile = new LogFile(siteName, false))
                {
                    sourceBaseOptions.Trace += logFile.LogEventHandler;
                    destBaseOptions.Trace   += logFile.LogEventHandler;

                    try
                    {
                        logFile.Log(TraceLevel.Info, "Beginning sync");

                        status.State = Models.DeployState.Deploying;
                        status.Save();

                        // Publish the content to the remote site
                        using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions))
                        {
                            // Note: would be nice to have an async flavor of this API...
                            summary = deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions());
                        }

                        string summaryString = string.Format("Total Changes: {0} ({1} added, {2} deleted, {3} updated, {4} parameters changed, {5} bytes copied)",
                                                             summary.TotalChanges,
                                                             summary.ObjectsAdded,
                                                             summary.ObjectsDeleted,
                                                             summary.ObjectsUpdated,
                                                             summary.ParameterChanges,
                                                             summary.BytesCopied);

                        status.ObjectsAdded      = summary.ObjectsAdded;
                        status.ObjectsDeleted    = summary.ObjectsDeleted;
                        status.ObjectsUpdated    = summary.ObjectsUpdated;
                        status.ParametersChanged = summary.ParameterChanges;
                        status.BytesCopied       = summary.BytesCopied;

                        logFile.Log(TraceLevel.Info, summaryString);
                        logFile.Log(TraceLevel.Info, "Sync completed successfully");
                    }
                    catch (Exception e)
                    {
                        logFile.Log(TraceLevel.Error, e.ToString());
                        success      = false;
                        status.State = Models.DeployState.Failed;
                    }

                    if (success)
                    {
                        status.State = Models.DeployState.Succeeded;
                    }
                }// Close log file and status file

            return(summary);
        }