Ejemplo n.º 1
0
        /// <summary>
        /// Initialize the helper to create any document.
        /// </summary>
        private void Initialize()
        {
            try
            {
                SyncServiceTrace.D(Resources.InitializationOfDocument);

                InitializeFileNameWithTimeStamp();

                RegisterServices();

                // Create the Model
                CreateModel();

                // Configure;
                Configure();

                // Get the service
                GetService();
            }
            catch (Exception e)
            {
                // ReSharper disable once PossibleIntendedRethrow
                SyncServiceTrace.LogException(e);
                throw e;
            }
        }
Ejemplo n.º 2
0
        public void AutoRefreshGivenQuery(string queryName, Document wordDocument, ISyncServiceDocumentModel documentModel, IConfiguration configuration)
        {
            //RegisterServices();

            _documentModel = documentModel;
            _wordDocument  = documentModel.WordDocument as Document;

            _configuration = configuration;
            _documentModel.Configuration.RefreshMappings();
            _documentModel.Configuration.ActivateMapping(_documentModel.MappingShowName);

            //Get the service
            GetService();

            //Search the workitems
            _workItems = GetWorkItemsIdsByQueryName(queryName);

            Find();

            while (IsFindingWorkItems)
            {
                Thread.CurrentThread.Join(50);
            }

            // Show how many work items were found
            ConsoleExtensionLogging.LogMessage(string.Format("{0}{1}", Resources.WorkItemsCountInformation, FoundWorkItems.Count), ConsoleExtensionLogging.LogLevel.Both);
            SyncServiceTrace.D((string.Format("{0}{1}", Resources.WorkItemsCountInformation, FoundWorkItems.Count)));

            Import();
            while (IsImporting)
            {
                Thread.CurrentThread.Join(50);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Save the document
        /// </summary>
        private void SaveDocument()
        {
            if (_fileName == null)
            {
                InitializeFileNameWithTimeStamp();
            }

            // Filename cannot be null
            // ReSharper disable AssignNullToNotNullAttribute
            if (!Directory.Exists(Path.GetDirectoryName(_fileName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(_fileName));
            }
            // ReSharper restore AssignNullToNotNullAttribute

            if (_documentConfiguration.Settings.Overwrite)
            {
                // Save the document
                _wordDocument.SaveAs(_fileName);
            }
            else
            {
                if (File.Exists(_fileName))
                {
                    throw new Exception(Resources.FileExistsError);
                }

                // Save the document
                _wordDocument.SaveAs(_fileName);
            }
            SyncServiceTrace.D(Resources.WordDocSaveMessage);
        }
Ejemplo n.º 4
0
        private ITfsTestSuite SearchtestSuiteByName(IEnumerable <ITfsTestSuite> suites, string testSuiteName)
        {
            SyncServiceTrace.D(Resources.SearchingTestSuiteByName);
            if (_tfsTestPlan.RootTestSuite.Title == testSuiteName)
            {
                return(_tfsTestPlan.RootTestSuite);
            }
            var testSuites = suites as List <ITfsTestSuite>;

            if (testSuites == null)
            {
                SyncServiceTrace.D(Resources.TestSuitesNotExist);
                return(null);
            }

            foreach (var suite in testSuites)
            {
                if (suite.Title == testSuiteName)
                {
                    return(suite);
                }
                else if (suite.TestSuites.Any())
                {
                    var foundSuite = SearchtestSuiteByName(suite.TestSuites, testSuiteName);
                    if (foundSuite != null)
                    {
                        return(foundSuite);
                    }
                }
            }

            // fallback return, if none of the conditions above was true, no approprate test suite was fond
            return(null);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///  This method creates a word document with the GetWorkItems-Command
        /// </summary>
        /// <param name="documentConfiguration">The configuration</param>
        /// <param name="workItems">The string that identifies the work items that should be imported</param>
        /// <param name="type">The type of the import operation</param>
        public void CreateWorkItemDocument(DocumentConfiguration documentConfiguration, string workItems, string type)
        {
            try
            {
                _documentConfiguration = documentConfiguration;

                // Initialize the document
                Initialize();

                if (type.Equals("ByID"))
                {
                    _workItems = GetWorkItemsIdsByString(workItems);
                }
                else if (type.Equals("ByQuery"))
                {
                    _workItems = GetWorkItemsIdsByQueryName(workItems);
                }

                if (_workItems == null || _workItems.Count < 1)
                {
                    SyncServiceTrace.E(Resources.NoWorkItemsFoundInformation);
                    throw new Exception(Resources.NoWorkItemsFoundInformation);
                }

                // Get the work items that should be imported / This will come from the query settings
                Find();

                while (IsFindingWorkItems)
                {
                    Thread.CurrentThread.Join(50);
                }

                // Show how many work items were found
                ConsoleExtensionLogging.LogMessage(string.Format("{0}{1}", Resources.WorkItemsCountInformation, FoundWorkItems.Count), ConsoleExtensionLogging.LogLevel.Both);
                SyncServiceTrace.D(string.Format("{0}{1}", Resources.WorkItemsCountInformation, FoundWorkItems.Count));

                Import();

                while (IsImporting)
                {
                    Thread.CurrentThread.Join(50);
                }

                ConsoleExtensionLogging.LogMessage(Resources.WorkItemsImportedInformation, ConsoleExtensionLogging.LogLevel.Both);
                SyncServiceTrace.D(Resources.WorkItemsImportedInformation);

                FinalizeDocument();
            }
            catch (Exception e)
            {
                // close any open word applications form this method
                if (_wordApplication != null)
                {
                    _wordApplication.Quit();
                }
                SyncServiceTrace.LogException(e);
                // ReSharper disable once PossibleIntendedRethrow
                throw e;
            }
        }
        /// <summary>
        /// Creates hyperlinks to selected work items at the current cursor position.
        /// </summary>
        public void CreateHyperlink()
        {
            SyncServiceTrace.I(Resources.CreateHyperlinks);

            // set actual selected configuration
            var ignoreFormatting  = DocumentModel.Configuration.IgnoreFormatting;
            var conflictOverwrite = DocumentModel.Configuration.ConflictOverwrite;

            DocumentModel.Configuration.ActivateMapping(DocumentModel.MappingShowName);
            DocumentModel.Configuration.IgnoreFormatting  = ignoreFormatting;
            DocumentModel.Configuration.ConflictOverwrite = conflictOverwrite;
            DocumentModel.Configuration.IgnoreFormatting  = ignoreFormatting;

            var source          = SyncServiceFactory.CreateTfs2008WorkItemSyncAdapter(DocumentModel.TfsServer, DocumentModel.TfsProject, null, DocumentModel.Configuration);
            var destination     = SyncServiceFactory.CreateWord2007TableWorkItemSyncAdapter(WordDocument, DocumentModel.Configuration);
            var importWorkItems = (from wim in FoundWorkItems
                                   where wim.IsChecked
                                   select wim.Item).ToList();


            // search for already existing work items in word and ask whether to overide them
            if (!(source.Open(importWorkItems.Select(x => x.TfsItem.Id).ToArray()) && destination.Open(null)))
            {
                return;
            }

            foreach (var workItem in importWorkItems)
            {
                destination.CreateWorkItemHyperlink(workItem.TfsItem.Title, source.GetWorkItemEditorUrl(workItem.TfsItem.Id));
            }
        }
        /// <summary>
        /// Execute import work items from TFS to Word process.
        /// </summary>
        public void Import()
        {
            SyncServiceTrace.I(Resources.ImportWorkItems);
            SyncServiceFactory.GetService <IInfoStorageService>().ClearAll();

            // check whether cursor is not inside the table
            if (WordSyncHelper.IsCursorInTable(WordDocument.ActiveWindow.Selection))
            {
                SyncServiceTrace.W(Resources.WordToTFS_Error_TableInsertInTable);
                MessageBox.Show(Resources.WordToTFS_Error_TableInsertInTable, Resources.MessageBox_Title, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // disable all other functionality
            if (WordRibbon != null)
            {
                WordRibbon.ResetBeforeOperation(DocumentModel);
                WordRibbon.DisableAllControls(DocumentModel);
            }

            // display progress dialog
            var progressService = SyncServiceFactory.GetService <IProgressService>();

            progressService.ShowProgress();
            progressService.NewProgress(Resources.GetWorkItems_Title);
            IsImporting = true;

            // start background thread to execute the import
            var backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork             += DoImport;
            backgroundWorker.RunWorkerCompleted += ImportFinished;
            backgroundWorker.RunWorkerAsync(backgroundWorker);
        }
Ejemplo n.º 8
0
        private static void ExportResource(string subFolder, string fileName)
        {
            try
            {
                var path = Path.Combine(LocalAppData, subFolder);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var source = $"TFS.SyncService.View.Word2007.{subFolder}.{fileName}";
                var target = Path.Combine(path, fileName);

                using (
                    Stream readStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(source),
                    writeStream = new FileStream(target, FileMode.Create, FileAccess.Write))
                {
                    if (readStream != null)
                    {
                        readStream.CopyTo(writeStream);
                    }
                }
            }

            catch (Exception e)
            {
                SyncServiceTrace.LogException(e);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// The method replaces the text of bookmark by specified text.
        /// </summary>
        /// <param name="bookmarkName">Bookmark where is to insert the specified text.</param>
        /// <param name="text">Text which is to insert on the position of the bookmark.</param>
        /// <param name="textFormat">Format of the given text.</param>
        /// <param name="bookmarkToInsertName"></param>
        /// <exception cref="ConfigurationException">Thrown if the bookmark does not exist.</exception>
        public void ReplaceBookmarkText(string bookmarkName, string text, PropertyValueFormat textFormat, string bookmarkToInsertName)
        {
            Guard.ThrowOnArgumentNull(text, "text");

            var bookmark = GetBookmark(bookmarkName);

            bookmark.Select();

            // TODO MIS 6.7.2015: Change to Switch Statement if possible for PropertyValueFormat
            if (textFormat == PropertyValueFormat.PlainText)
            {
                if (!string.IsNullOrEmpty(bookmarkToInsertName))
                {
                    var range = bookmark.Range;
                    range.Text = text;
                    range.Bookmarks.Add(bookmarkToInsertName);
                    StoreOriginalBookmark(bookmarkToInsertName);
                }
                else
                {
                    bookmark.Range.Text = text;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(text))
                {
                    bookmark.Range.Delete();
                }
                else
                {
                    // Editing html fields using vs or browser will not always surround text in tags.
                    // Word appears to only parse strings like "A&amp;B" correctly when they are surrounded with tags.
                    if (!(text.StartsWith("<", StringComparison.Ordinal) && text.EndsWith(">", StringComparison.Ordinal)))
                    {
                        text = $"<span>{text}</span>";
                        SyncServiceTrace.W(Resources.ResultIfTextIsNotHtml);
                    }
                    try
                    {
                        //Used to make numbers of shared steps bold
                        if (PropertyValueFormat.HTMLBold == textFormat)
                        {
                            WordHelper.PasteSpecial(bookmark.Range, text, true);
                        }
                        else
                        {
                            WordHelper.PasteSpecial(bookmark.Range, text);
                        }
                    }
                    catch (COMException)
                    {
                        // If pasting the html text failed, we still have to remove the bookmark text.
                        bookmark.Range.Delete();
                        //bm.Delete();
                    }
                }
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// The method calls the event <see cref="TemplatesChanged"/>.
 /// </summary>
 private void RaiseTemplatesChangedEvent()
 {
     if (TemplatesChanged != null)
     {
         SyncServiceTrace.D(Resources.TemplatesChanged);
         TemplatesChanged(this, EventArgs.Empty);
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="RunWorkerCompletedEventArgs"/> that contains the event data.</param>
        private void FindingFinished(object sender, RunWorkerCompletedEventArgs e)
        {
            e.Error.NotifyIfException("Failed to find work items.");

            IsFindingWorkItems = false;

            SyncServiceTrace.I(Resources.WorkItemsAreFound);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Background method to import the work items from TFS.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="DoWorkEventArgs"/> that contains the event data.</param>
        private void DoImport(object sender, DoWorkEventArgs e)
        {
            SyncServiceTrace.I(Resources.ImportWorkItems);
            var workItemSyncService = SyncServiceFactory.GetService <IWorkItemSyncService>();
            var configService       = SyncServiceFactory.GetService <IConfigurationService>();

            // save query configuration to document
            DocumentModel.SaveQueryConfiguration(_queryConfiguration);
            DocumentModel.Save();

            // set actual selected configuration
            var configuration = configService.GetConfiguration(WordDocument);

            var ignoreFormatting  = configuration.IgnoreFormatting;
            var conflictOverwrite = configuration.ConflictOverwrite;

            configuration.ActivateMapping(DocumentModel.MappingShowName);
            DocumentModel.Configuration.IgnoreFormatting = ignoreFormatting;
            configuration.ConflictOverwrite = conflictOverwrite;
            configuration.IgnoreFormatting  = ignoreFormatting;

            var config = SyncServiceFactory.GetService <IConfigurationService>().GetConfiguration(WordDocument);
            var source = SyncServiceFactory.CreateTfs2008WorkItemSyncAdapter(DocumentModel.TfsServer, DocumentModel.TfsProject, null, config);

            _importWordAdapter = SyncServiceFactory.CreateWord2007TableWorkItemSyncAdapter(WordDocument, configuration);

            _importWordAdapter.PrepareDocumentForLongTermOperation();
            //////////
            _importWordAdapter.ProcessOperations(configuration.PreOperations);
            var importWorkItems = (from wim in FoundWorkItems
                                   where wim.IsChecked
                                   select wim.Item).ToList();

            // search for already existing work items in word and ask whether to overide them
            if (!(source.Open(importWorkItems.Select(x => x.TfsItem.Id).ToArray()) && _importWordAdapter.Open(null)))
            {
                return;
            }

            if (importWorkItems.Select(x => x.TfsItem.Id).Intersect(_importWordAdapter.WorkItems.Select(x => x.Id)).Any())
            {
                SyncServiceTrace.W(Resources.TFSExport_ExistingWorkItems);
                if (
                    System.Windows.Forms.MessageBox.Show((IWin32Window)WordRibbon,
                                                         Resources.TFSExport_ExistingWorkItems,
                                                         Resources.MessageBox_Title,
                                                         MessageBoxButtons.YesNo,
                                                         MessageBoxIcon.Question,
                                                         MessageBoxDefaultButton.Button2, 0) == DialogResult.No)
                {
                    return;
                }
            }

            workItemSyncService.Refresh(source, _importWordAdapter, importWorkItems.Select(x => x.TfsItem), configuration);
            _importWordAdapter.ProcessOperations(configuration.PostOperations);
        }
Ejemplo n.º 13
0
        private string GetValueAsHtml()
        {
            // Make sure that when reading from multiple threads, the old values and
            // images are read before they are overwritten by a new read.
            lock (HtmlExportLock)
            {
                try
                {
                    if (_range == null)
                    {
                        return(string.Empty);
                    }

                    var helper = new ClipboardHelper(_range);

                    // apply workaround for when only an inline shape is in the field and no text. Word will not export the embedded element if there is no other text.
                    if (string.IsNullOrEmpty(helper.Html))
                    {
                        if (ContainsShapes && Configuration.ShapeOnlyWorkaroundMode == ShapeOnlyWorkaroundMode.AddSpace)
                        {
                            _range.InsertAfter(Resources.ShapeOnlyAutoText);
                            helper = new ClipboardHelper(_range);
                        }
                    }

                    // Generate the file name --> FieldName.Index.Extension --> example AIT.Common.Description.1.png
                    var html = helper.Html;
                    using (var htmlHelper = new HtmlHelper(html, false))
                    {
                        foreach (var image in htmlHelper.Images)
                        {
                            image.Name = Guid.NewGuid().ToString() + image.LocalFileInfo.Extension;
                            html       = html.Replace(image.Source, image.LocalFileInfo.FullName);
                        }
                    }

                    /////////////////////////////////////////////////////////////////////////////////////
                    //if (scaleRatio != null)
                    //{
                    //    // Images in word are displayed 20% smaller than they actually are.
                    //    // Thus we have to shrink the images to 80% in order to display them correctly in the TFS fields.
                    //    // On the other hand, when copied into word, image sizes are increased by 25%.
                    //    // Therefore they are again displayed correctly in word when we download them from the TFS.
                    //    html = HtmlHelper.ShrinkImages(html, scaleRatio);
                    //    this.RescalePictures(scaleRatio);
                    //}
                    /////////////////////////////////////////////////////////////////////////////////////

                    return(html);
                }
                catch (Exception ex)
                {
                    SyncServiceTrace.LogException(ex);
                    return(GetValueAsPlainText());
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Convert a string to a list of work Items
        /// </summary>
        /// <param name="workitems"></param>
        /// <returns>ids of workitems</returns>
        private List <int> GetWorkItemsIdsByString(string workitems)
        {
            ConsoleExtensionLogging.LogMessage(Resources.GetWorkItemById, ConsoleExtensionLogging.LogLevel.Both);
            SyncServiceTrace.D(Resources.GetWorkItemById);

            var stringIDs = workitems.Split(new[] { ' ', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
            int intValue;

            return(stringIDs.Where(x => int.TryParse(x, out intValue)).Select(int.Parse).ToList());
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="RunWorkerCompletedEventArgs"/> that contains the event data.</param>
        private void ImportFinished(object sender, RunWorkerCompletedEventArgs e)
        {
            e.Error.NotifyIfException("Failed to import work items.");

            IsImporting = false;
            var progressService = SyncServiceFactory.GetService <IProgressService>();

            progressService.HideProgress();

            SyncServiceTrace.I(Resources.WorkItemsAreImported);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Initialize the filename for the current document.
        /// If the settings contain a variable for the timestamp, the the filename or folder will contain the current date and time.
        /// </summary>
        private void InitializeFileNameWithTimeStamp()
        {
            SyncServiceTrace.D(Resources.InitializationOfFileName);
            _fileName = _documentConfiguration.Settings.Filename;

            if (_documentConfiguration.Settings.Filename.Contains(TIME_STAMP_VARIABLE))
            {
                var currentTimeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                _fileName = _documentConfiguration.Settings.Filename.Replace(TIME_STAMP_VARIABLE, currentTimeStamp);
            }
        }
Ejemplo n.º 17
0
 private static void RegisterServices()
 {
     SyncServiceTrace.D(Resources.RegisterServices);
     // Initialize all assemblies.
     AssemblyInit.Instance.Init();
     // ReSharper disable RedundantNameQualifier
     Adapter.Word2007.AssemblyInit.Instance.Init();
     Service.AssemblyInit.Instance.Init();
     AssemblyInit.Instance.Init();
     // ReSharper restore RedundantNameQualifier
 }
Ejemplo n.º 18
0
        /// <summary>
        /// This method creates a word document with the TestResultReport-Command
        /// </summary>
        public void CreateTestResultDocument(DocumentConfiguration documentConfiguration)
        {
            try
            {
                SyncServiceTrace.D(Resources.CreateTestResultDoc);
                _documentConfiguration = documentConfiguration;
                Initialize();
                var testResultSettings = _documentConfiguration.TestResultSettings;
                var testAdapter        = SyncServiceFactory.CreateTfsTestAdapter(_documentModel.TfsServer, _documentModel.TfsProject, _documentModel.Configuration);
                TestCaseSortType testCaseSortType;
                Enum.TryParse(testResultSettings.SortTestCasesBy, out testCaseSortType);
                DocumentStructureType documentStructure;
                Enum.TryParse(testResultSettings.DocumentStructure, out documentStructure);
                ConfigurationPositionType configurationPositionType;
                Enum.TryParse(testResultSettings.TestConfigurationsPosition, out configurationPositionType);
                var testPlan = testAdapter.GetTestPlans(null).Where(plan => plan.Name == testResultSettings.TestPlan).FirstOrDefault();
                if (testPlan == null)
                {
                    SyncServiceTrace.D(Resources.TestSettingsInvalidTestPlan);
                    throw new ArgumentException(Resources.TestSettingsInvalidTestPlan);
                }
                var testSuiteSearcher = new TestSuiteSearcher(testPlan);
                var testSuite         = testSuiteSearcher.SearchTestSuiteWithinTestPlan(testResultSettings.TestSuite);

                var reportModel = new TestResultReportModel(_documentModel,
                                                            testAdapter,
                                                            testPlan,
                                                            testSuite,
                                                            testResultSettings.CreateDocumentStructure,
                                                            testResultSettings.SkipLevels,
                                                            documentStructure,
                                                            testCaseSortType,
                                                            testResultSettings.IncludeTestConfigurations,
                                                            configurationPositionType,
                                                            testResultSettings.IncludeOnlyMostRecentResults,
                                                            testResultSettings.MostRecentForAllConfigurations,
                                                            testResultSettings.Build,
                                                            testResultSettings.TestConfiguration,
                                                            new TestReportingProgressCancellationService(false));

                reportModel.CreateReport();
                FinalizeDocument();
            }
            catch
            {
                if (_wordApplication != null)
                {
                    _wordApplication.Quit();
                }
                // ReSharper disable once PossibleIntendedRethrow
                throw;
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Parses a <c>Table</c> into a <c>IWorkItem</c>. Uses the currently set configuration to determine
        /// what work item types are available.
        /// </summary>
        /// <param name="table">table representing the work item</param>
        /// <returns>A work item represented by the table or <c>null</c> if the type
        /// of the work item could not be determined </returns>
        private WordTableWorkItem CreateHeader(Table table)
        {
            IConfigurationItem config = GetConfigurationItemFromTable(table, Configuration.Headers);

            if (config == null)
            {
                SyncServiceTrace.W(Resources.LogService_TableToWorkItemException);
                return(null);
            }

            return(new WordTableWorkItem(table, config.WorkItemType, Configuration, config));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Logs an exception to file and creates an entry in the info storage service.
        /// If the exception is null, nothing is logged.
        /// </summary>
        /// <param name="exception">Exception that occurred or null.</param>
        /// <param name="title">Title of the user information entry.</param>
        public static void NotifyIfException(this Exception exception, string title)
        {
            if (exception != null)
            {
                SyncServiceTrace.LogException(exception);

                var infoStorage = SyncServiceFactory.GetService <IInfoStorageService>();
                if (infoStorage != null)
                {
                    infoStorage.NotifyError(title, exception);
                }
            }
        }
Ejemplo n.º 21
0
        private void ReadAllMappings()
        {
            _defaultMappingShowName = null;
            _mappings.Clear();
            foreach (string subfolder in Directory.GetDirectories(MappingFolder))
            {
                // It is one time occured, that the folder in MappingFolder was deleted.
                // It takes some time and the method 'GetDirectories' returned this folder,
                // but the 'GetFiles' method was finished with exception folder not found.
                // Use exception handling
                try
                {
                    foreach (string mappingFile in Directory.GetFiles(subfolder, "*.w2t", SearchOption.AllDirectories))
                    {
                        SyncServiceTrace.I(Properties.Resources.LogService_LoadFile, mappingFile);

                        var serializer = new XmlSerializer(typeof(MappingConfigurationShort));
                        MappingConfigurationShort mappingConfiguration;
                        try
                        {
                            using (var stream = new StreamReader(mappingFile))
                            {
                                mappingConfiguration = serializer.Deserialize(stream) as MappingConfigurationShort;
                            }
                        }
                        catch (Exception ex)
                        {
                            SyncServiceTrace.LogException(ex);
                            mappingConfiguration = null;
                        }

                        if (mappingConfiguration == null || MappingExists(mappingConfiguration.ShowName))
                        {
                            continue;
                        }

                        var mi = new MappingInfo(mappingConfiguration.ShowName, mappingFile);
                        _mappings[mi.ShowName] = mi;
                        if (mappingConfiguration.DefaultMapping && string.IsNullOrEmpty(_defaultMappingShowName))
                        {
                            _defaultMappingShowName = mi.ShowName;
                        }
                    }
                }
                catch (Exception e)
                {
                    SyncServiceTrace.LogException(e);
                }
            }
            SyncServiceTrace.D("Mapping are read.");
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Execute find work items process to fill up the Find list box.
        /// </summary>
        public void FindWorkItems()
        {
            SaveQueryConfiguration();
            SyncServiceTrace.I(Resources.FindWorkItems);

            // check whether is at least one link type selected
            if (QueryConfiguration.UseLinkedWorkItems && IsCustomLinkType && QueryConfiguration.LinkTypes.Count == 0)
            {
                MessageBox.Show(Resources.WordToTFS_Error_LinkTypesNotSelected, Resources.MessageBox_Title, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            // parse IDs
            if (ImportOption == QueryImportOption.IDs && !ParseIDs(QueryConfiguration.ByIDs))
            {
                return;
            }

            if (ImportOption == QueryImportOption.TitleContains)
            {
                QueryConfiguration.ByTitle = ImportTitleContains;
            }

            // disable all other functionality
            if (WordRibbon != null)
            {
                WordRibbon.ResetBeforeOperation(DocumentModel);
                WordRibbon.DisableAllControls(DocumentModel);
            }

            // display progress dialog
            var progressService = SyncServiceFactory.GetService <IProgressService>();

            progressService.ShowProgress();
            progressService.NewProgress(Resources.GetWorkItems_Title);
            IsFinding = true;

            TaskScheduler scheduler = null;

            try
            {
                scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            }
            catch (InvalidOperationException)
            {
                scheduler = TaskScheduler.Current;
            }

            Task.Factory.StartNew(DoFind).ContinueWith(FindFinished, scheduler);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="RunWorkerCompletedEventArgs"/> that contains the event data.</param>
        private void ImportFinished(object sender, RunWorkerCompletedEventArgs e)
        {
            e.Error.NotifyIfException("Failed to import work items.");

            IsImporting = false;
            _importWordAdapter.UndoPreparationsDocumentForLongTermOperation();
            var progressService = SyncServiceFactory.GetService <IProgressService>();

            progressService.HideProgress();

            // enable all other functionality
            WordRibbon?.EnableAllControls(DocumentModel);
            SyncServiceTrace.I(Resources.ImportFinished);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Create the model of the document and bind the project to the server
        /// </summary>
        private void CreateModel()
        {
            SyncServiceTrace.D(Resources.CreateModelInfo);
            // Create a word appliaction and set it to visible
            if (!_documentConfiguration.Settings.Overwrite && File.Exists(_fileName))
            {
                throw new Exception(Resources.FileExistsError);
            }
            SyncServiceTrace.D(Resources.FileIsOverwrittenOrNotExists);

            string wordTemplateFile = null;

            if (!string.IsNullOrEmpty(_documentConfiguration.Settings.DotxTemplate))
            {
                wordTemplateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _documentConfiguration.Settings.DotxTemplate);

                // if the path is absolute, use it
                if (Path.IsPathRooted(_documentConfiguration.Settings.DotxTemplate))
                {
                    wordTemplateFile = _documentConfiguration.Settings.DotxTemplate;
                }
            }

            if (!string.IsNullOrEmpty(wordTemplateFile) && !File.Exists(wordTemplateFile))
            {
                throw new Exception(string.Format(Resources.Error_TemplateDoesNotExist, wordTemplateFile));
            }

            _wordApplication         = new Application();
            _wordApplication.Visible = !_documentConfiguration.Settings.WordHidden;

            if (!string.IsNullOrEmpty(wordTemplateFile))
            {
                _wordApplication.Documents.Add(wordTemplateFile);
            }
            else
            {
                _wordApplication.Documents.Add();
            }


            _wordDocument = _wordApplication.ActiveDocument;
            PrepareDocumentForReportGeneration();
            _documentModel = new SyncServiceDocumentModel(_wordDocument);

            _documentModel.MappingShowName = _documentConfiguration.Settings.Template;
            _documentModel.BindProject(_documentConfiguration.Settings.Server, _documentConfiguration.Settings.Project);
            SaveDocument();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Execution of the console parameter
        /// </summary>
        /// <param name="remainingArguments"></param>
        /// <returns></returns>
        public override int Run(string[] remainingArguments)
        {
            try
            {
                var conf = CreateDocumentConfig();

                if (conf == null || conf.TestSpecSettings == null)
                {
                    throw new ArgumentException(string.Format(Resources.ConfigurationFileMisconfigured, "TestSpecificationConfiguration"));
                }

                // One of the two options has to be chosen
                if (_workitems == null && _query == null)
                {
                    ConsoleExtensionLogging.LogMessage(Resources.OptionsNullError, ConsoleExtensionLogging.LogLevel.Both);
                    ConsoleExtensionLogging.LogMessage(Resources.OptionsNullErrorInstruction, ConsoleExtensionLogging.LogLevel.Console);
                    SyncServiceTrace.D(Resources.OptionsNullError);
                    return(CommandReturnCodeFail);
                }

                // It isn't allowed to choose both options simultaneously
                if (_workitems != null && _query != null)
                {
                    ConsoleExtensionLogging.LogMessage(Resources.OptionsOverloadedError, ConsoleExtensionLogging.LogLevel.Both);
                    SyncServiceTrace.D(Resources.OptionsOverloadedError);
                    return(CommandReturnCodeFail);
                }

                if (_workitems != null)
                {
                    var crm = new ConsoleExtensionHelper(new TestReportingProgressCancellationService(false));
                    crm.CreateTestSpecDocumentByQuery(conf, _workitems, "ByID");
                }
                // Get work items by query
                else
                {
                    var crm = new ConsoleExtensionHelper(new TestReportingProgressCancellationService(false));
                    crm.CreateTestSpecDocumentByQuery(conf, _query, "ByQuery");
                }
            }
            catch (Exception e)
            {
                ConsoleExtensionLogging.LogMessage(e.Message, ConsoleExtensionLogging.LogLevel.Both);
                SyncServiceTrace.D(e.Message);
                return(CommandReturnCodeFail);
            }

            return(CommandReturnCodeSuccess);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// The method deletes all cached files.
 /// </summary>
 public void Cleanup()
 {
     try
     {
         Directory.Delete(TemplateBundleCacheLocation, true);
     }
     catch (IOException e)
     {
         SyncServiceTrace.LogException(e);
     }
     catch (UnauthorizedAccessException e)
     {
         SyncServiceTrace.LogException(e);
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Occurs when the background operation has completed, has been canceled, or has raised an exception.
        /// </summary>
        private void FindFinished(Task task)
        {
            IsFinding = false;
            var progressService = SyncServiceFactory.GetService <IProgressService>();

            progressService.HideProgress();

            // enable all other functionality
            if (WordRibbon != null)
            {
                WordRibbon.EnableAllControls(DocumentModel);
            }

            SyncServiceTrace.I(Resources.FindFinished);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Call this method to bind the active document to the TFS project.
        /// </summary>
        public void BindProject()
        {
            if (TfsDocumentBound)
            {
                return;
            }

            var tfs = SyncServiceFactory.GetService <ITeamFoundationServerMaintenance>();

            if (tfs == null)
            {
                return;
            }

            var serverUrl   = string.Empty;
            var projectName = string.Empty;

            if (!string.IsNullOrEmpty(Configuration.DefaultProjectName) && !string.IsNullOrEmpty(Configuration.DefaultServerUrl))
            {
                if (!tfs.ValidateConnectionSettings(Configuration.DefaultServerUrl, Configuration.DefaultProjectName, out serverUrl, out projectName))
                {
                    //Publish error if connection fails
                    PublishConnectionError(Resources.Error_Wrong_Connection_Short, Resources.Error_Wrong_Connection_Long);
                    return;
                }
            }
            else
            {
                try
                {
                    if (!tfs.SelectOneTfsProject(out serverUrl, out projectName))
                    {
                        return;
                    }
                }
                catch (Exception e)
                {
                    PublishConnectionError(Resources.Error_TeamPickerFailed_Short, Resources.Error_TeamPickerFailed_Long);
                    SyncServiceTrace.W(Resources.Error_TeamPickerFailed_Long);
                    SyncServiceTrace.W(e.Message);
                    return;
                }
            }

            SetDocumentVariableValue(ConstTfsBound, ConstTfsBound, null);
            SetDocumentVariableValue(ConstTfsServer, serverUrl, null);
            SetDocumentVariableValue(ConstTfsProject, projectName, null);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Activates all loaded mappings.
 /// </summary>
 public void ActivateAllMappings()
 {
     try
     {
         _configurations.Clear();
         _headers.Clear();
         foreach (var valuePair in _mappings)
         {
             ReadConfigurationItems(valuePair.Value.MappingFileName);
         }
     }
     catch (Exception ex)
     {
         SyncServiceTrace.LogException(ex);
     }
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Get the click once location and the path of the user
        /// </summary>
        private void GetPathAndClickOnceLocations()
        {
            SyncServiceTrace.I(Resources.GetPath);
            //Get the assembly information and the codebase
            var assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
            var uriCodeBase  = new Uri(assemblyInfo.CodeBase);

            _clickOnceLocation = Path.GetDirectoryName(uriCodeBase.LocalPath);

            var environment = Registry.CurrentUser.CreateSubKey(@"Environment\");

            if (environment != null)
            {
                _path = (string)environment.GetValue("PATH");
            }
        }