Exemplo n.º 1
0
        void NavigateToSolution()
        {
            var helper = new MergeHelper(this);

            helper.NavigateToSolution(CurrentBranch, dte);
            Update();
        }
Exemplo n.º 2
0
        public void Update()
        {
            Logger.AddInfo("UpdateCommand. Start");

            if (!InitializeConnection())
            {
                return;
            }
            if (!PortOptions.IsAttached)
            {
                Logger.AddInfo("UpdateCommand. End - cant merge since port is not initialized");
                CanTotalMerge = false;
                return;
            }


            MasterBranch             = FindMasterBranch(PortOptions);
            CanTotalMerge            = MasterBranch != null;
            PortOptions.MasterBranch = MasterBranch;

            MergeHelper helper = new MergeHelper(this);

            SelectedItems = new ObservableCollection <ProjectItemBase>();
            Selector      = new ChildNodesSelector(item => FilterItems(item, helper));
            var source = GenerateSource(helper);

            Source = source;

            currentBranchLocker.DoIfNotLocked(() => CurrentBranch = Options.Branches.LastOrDefault(item => item != MasterBranch));
            MergeProgress = 0;

            Logger.AddInfo("UpdateCommand. End - successful initialized");
        }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddNewtonsoftJson(options => {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.Converters.Add(new ClaimJsonConverter());
            });

            services.AddIdentityServer(options =>
            {
                var configuredOptions = Config.GetServerOptions();
                MergeHelper.Merge(configuredOptions, options);
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUsers())
            .AddRedirectUriValidator <RedirectUriValidator>()
            .AddProfileService <ProfileService>()
            .AddCorsPolicyService <CorsPolicyService>();

            var aspNetServicesOptions = Config.GetAspNetServicesOptions();

            AspNetServicesHelper.ConfigureAspNetServices(services, aspNetServicesOptions);

            Config.ConfigureAccountOptions();

            services.AddRouting();
        }
Exemplo n.º 4
0
        public void ShowNavigationConfig()
        {
            Logger.AddInfo("ShowNavigationConfigCommand. Start.");

            try {
                NavigationConfigViewModel model = SerializeHelper.DeSerializeNavigationConfig();
                if (PortOptions != null)
                {
                    MergeHelper          helper = new MergeHelper(this);
                    IEnumerable <string> roots  = helper.FindWorkingFolders(Options.Branches);
                    model.Roots = roots;
                }

                model.GenerateTreeSource();
                if (GetService <IDialogService>(NavigationConfigWindow).ShowDialog(MessageButton.OKCancel, "Navigation config", model) == MessageResult.OK)
                {
                    model.Save();
                    generateMenuItemsHelper.Release();
                    generateMenuItemsHelper.GenerateDefault();
                    generateMenuItemsHelper.GenerateMenus();
                }
            }
            catch (Exception e) {
                Logger.AddError("ShowNavigationConfigCommand. Failed.", e);
            }

            Logger.AddInfo("ShowNavigationConfigCommand. End.");
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddIdentityServer(options =>
            {
                var configuredOptions = Config.GetServerOptions();
                MergeHelper.Merge(configuredOptions, options);
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUsers())
            .AddRedirectUriValidator <RedirectUriValidator>()
            .AddProfileService <ProfileService>()
            .AddCorsPolicyService <CorsPolicyService>();

            var aspNetServicesOptions = Config.GetAspNetServicesOptions();

            AspNetServicesHelper.ConfigureAspNetServices(services, aspNetServicesOptions);

            services.AddRouting();
        }
Exemplo n.º 6
0
        public void CodeMergeItemWithSpaciliseShallPerformAnAdditionalSubstitutionOnSpacilisedInputAndMergeItems()
        {
            //Setup
            var inputCode          = @"public string somethingElse SomethingElse { get; set; }";
            var expectedOutputCode = @"public string nameMe NameMe { get; set; }";

            var swapValue = "SomethingElse";
            var mergeItem = new MergeItem
            {
                MergeParings = new List <MergePairing>
                {
                    new MergePairing {
                        SwapValue = swapValue, InputValue = "NameMe"
                    }
                }
            };

            //var mergeItem = new MergeItem { SwapValue = "SomethingElse", MergeParings = new List<string> { "NameMe" } };

            var mergeOptions = new MergeOptions {
                CameliseSubstitutionAlso = true
            };

            //Exercise
            var actualCodeOutput = MergeHelper.MergeItem(inputCode, mergeItem, mergeOptions);

            //Verify
            Assert.AreEqual(expectedOutputCode, actualCodeOutput, "The actual code output is not what was expected: " + actualCodeOutput);
        }
Exemplo n.º 7
0
 IEnumerable GenerateSource(MergeHelper helper)
 {
     if (UseFlatUI)
     {
         return(GetFlatItemsSource().Where(item => !FilterItems(item, helper)).ToList());
     }
     return(GetTreeItemsSource());
 }
Exemplo n.º 8
0
        public FileDiffInfo GetFileDiffInfo(string filePath, Action <int, int> progress)
        {
            IDXVcsRepository dxRepository = DXVcsConnectionHelper.Connect(PortOptions.VcsServer);
            MergeHelper      helper       = new MergeHelper(toolWindowViewModel);
            string           vcsFile      = helper.GetMergeVcsPathByOriginalPath(filePath, PortOptions.MasterBranch);

            return(dxRepository.GetFileDiffInfo(vcsFile, progress, SpacesAction.IgnoreAll));
        }
Exemplo n.º 9
0
        MergeState PerformMerge(ProjectItemBase item, bool showPreview)
        {
            if (item is FolderItem)
            {
                return(MergeState.Success);
            }
            var helper = new MergeHelper(this);

            item.ItemWrapper.Save();
            return(helper.MergeChanges(CurrentBranch, item.Path, null, showPreview, item.IsNew));
        }
Exemplo n.º 10
0
        void ManualMerge()
        {
            Logger.AddInfo("ManualMergeCommand. Merge start.");

            var helper      = new MergeHelper(this);
            var manualMerge = new ManualMergeViewModel(SelectedItem.Path);

            SelectedItem.MergeState = helper.ManualMerge(CurrentBranch, manualMerge,
                                                         () => GetService <IDialogService>(ManualMergeWindow).ShowDialog(MessageButton.OKCancel, "Manual merge", manualMerge) == MessageResult.OK);
            Logger.AddInfo("ManualMergeCommand. Merge end.");
        }
Exemplo n.º 11
0
        public List <MergeResult <DscResource> > MergeDscResources(List <MergeResult <DscResource> > mergeResultsToMerge)
        {
            mergeResultsToMerge = mergeResultsToMerge.Where(x => !IsOverriddenByThis(x)).ToList();
            ResourceStepName    = MergeHelper.GetMergableName(ResourceStepName, mergeResultsToMerge);

            mergeResultsToMerge.Add(new MergeResult <DscResource>
            {
                Value   = this,
                Success = true
            });

            return(mergeResultsToMerge);
        }
Exemplo n.º 12
0
        public override bool Run(Dictionary <string, string> mergeValues)
        {
            try
            {
                var qry = MergeHelper.Merge(settings.Razor, mergeValues);

                return(true);
            }
            catch (Exception es)
            {
                return(settings.ContinueOnError);
            }
        }
        private void margeButton_Click(object sender, EventArgs e)
        {
            try
            {
                MergeHelper.AddByteArrayOfEachFile(filesToMerge, ref filesByteArrayList);
                byte[] mergedFile;

                if (formatComboBox.SelectedItem.ToString() == "PDF")
                {
                    mergedFile = MergeHelper.MergePdfs(filesByteArrayList);
                }
                else if (formatComboBox.SelectedItem.ToString() == "DOCX")
                {
                    mergedFile = MergeHelper.DocxMerge(filesByteArrayList);
                }
                else
                {
                    mergedFile = null;
                }

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = saveFileDialog.Filter = $"{formatComboBox.SelectedItem.ToString()} files (*." +
                                                                $"{formatComboBox.SelectedItem.ToString().ToLower()})|*." +
                                                                $"{formatComboBox.SelectedItem.ToString().ToLower()};";
                saveFileDialog.FileName        = "MergedFile";
                saveFileDialog.OverwritePrompt = true;

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string savePath = Path.Combine(desktopPath, saveFileDialog.FileName);

                    if (formatComboBox.SelectedItem.ToString() == "PDF" || formatComboBox.SelectedItem.ToString() == "DOCX")
                    {
                        File.WriteAllBytes(savePath, mergedFile);
                    }
                    else
                    {
                        MergeHelper.TxtMerge(savePath, filesToMerge);
                    }
                }
            }
            catch (InvalidOperationException invalidOperationEx)
            {
                MessageBox.Show(invalidOperationEx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot merge attached files", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 14
0
        public void CodeMergeConsignmentWithSimpleConsignmentAndDefaultOptionsShallSucceed()
        {
            //Setup
            var inputCode          = @"public TYPE PROP;
";
            var expectedOutputCode = @"public string Name;
public int Id;
";

            var mergeConsignment = new MergeConsignment
            {
                CodeInput  = inputCode,
                MergeItems = new List <MergeItem>
                {
                    new MergeItem
                    {
                        MergeParings = new List <MergePairing>
                        {
                            new MergePairing {
                                SwapValue = "PROP", InputValue = "Name"
                            },
                            new MergePairing {
                                SwapValue = "TYPE", InputValue = "string"
                            }
                        }
                    },
                    new MergeItem
                    {
                        MergeParings = new List <MergePairing>
                        {
                            new MergePairing {
                                SwapValue = "PROP", InputValue = "Id"
                            },
                            new MergePairing {
                                SwapValue = "TYPE", InputValue = "int"
                            }
                        }
                    }
                }
            };

            var mergeOptions = new MergeOptions();//Default

            //Exercise
            var actualCodeOutput = MergeHelper.Merge(mergeConsignment, mergeOptions);

            //Verify
            Assert.AreEqual(expectedOutputCode, actualCodeOutput, "The actual code output is not what was expected: " + actualCodeOutput);
        }
Exemplo n.º 15
0
        public override void MergeWith(object obj)
        {
            if (!MergeHelper.IsMergeable(this, obj))
            {
                return;
            }

            WoWVersion pver = (WoWVersion)obj;

            // Manually check confuration elements
            TalentConfig = TalentConfig ?? pver.TalentConfig;
            QuestConfig  = QuestConfig ?? pver.QuestConfig;

            base.MergeWith(pver);
        }
Exemplo n.º 16
0
        string GetCheckInPath(CheckInTarget target, string selectedItemPath)
        {
            switch (target)
            {
            case CheckInTarget.Master:
                return(selectedItemPath);

            case CheckInTarget.Port:
                MergeHelper helper = new MergeHelper(this);
                return(helper.GetFilePathForBranch(selectedItemPath, CurrentBranch));

            default:
                throw new ArgumentException("target");
            }
        }
Exemplo n.º 17
0
        void CheckIn(CheckInTarget target)
        {
            if (IsSingleSelection)
            {
                Logger.AddInfo("CheckInCommand. Start single check in.");

                var           model  = new CheckInViewModel(GetCheckInPath(target, SelectedItem.Path), false);
                MessageResult result = GetService <IDialogService>(Checkinwindow).ShowDialog(MessageButton.OKCancel, "Check in", model);
                if (result == MessageResult.OK)
                {
                    var helper = new MergeHelper(this);
                    helper.CheckIn(new CheckInViewModel(SelectedItem.Path, model.StaysChecked)
                    {
                        Comment = model.Comment
                    }, GetCheckInBranch(target), SelectedItem.IsNew);
                    SelectedItem.IsChecked = model.StaysChecked;
                }

                Logger.AddInfo("CheckInCommand. End single check in.");
            }
            else
            {
                Logger.AddInfo("CheckInCommand. Start multiple check in.");

                var model  = new CheckInViewModel(GetCheckInPath(target, Solution.Path), false);
                var result = GetService <IDialogService>(MultipleCheckinWindow).ShowDialog(MessageButton.OKCancel, "Multiple Check in", model);
                if (result == MessageResult.OK)
                {
                    var helper = new MergeHelper(this);
                    foreach (var item in SelectedItems)
                    {
                        var currentFileModel = new CheckInViewModel(item.Path, model.StaysChecked)
                        {
                            Comment = model.Comment
                        };
                        bool success = helper.CheckIn(currentFileModel, GetCheckInBranch(target), item.IsNew);
                        item.IsChecked = success && model.StaysChecked;
                    }
                }

                Logger.AddInfo("CheckInCommand. End multiple check in.");
            }
            ReloadProject();
        }
Exemplo n.º 18
0
        void UndoCheckout()
        {
            var helper = new MergeHelper(this);

            if (IsSingleSelection)
            {
                SelectedItem.IsCheckOut = helper.UndoCheckout(SelectedItem.Path);
                SelectedItem.Save();
            }
            else
            {
                foreach (var item in SelectedItems)
                {
                    item.IsCheckOut = helper.UndoCheckout(item.Path);
                    item.Save();
                }
            }
            ReloadProject();
        }
Exemplo n.º 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddIdentityServer(options =>
            {
                var configuredOptions = Config.GetServerOptions();
                MergeHelper.Merge(configuredOptions, options);
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUsers());

            services.AddRouting();
            services.AddCors();
        }
Exemplo n.º 20
0
        public InternalBlameViewModel(string filePath, int?lineNumber, IToolWindowViewModel tool)
        {
            this.blameHelper           = new BlameHelper(tool);
            this.mergeHelper           = new MergeHelper(tool);
            FilePath                   = filePath;
            PreviousRevisionCommand    = new DelegateCommand(NavigateToPreviousRevision, CanNavigateToPreviousRevision);
            NextRevisionCommand        = new DelegateCommand(NavigateToNextRevision, CanNavigateToNextRevision);
            SpecifiedRevisionCommand   = new DelegateCommand(NavigateToSpecifiedRevision, CanNavigateToSpecifiedRevision);
            LastRevisionCommand        = new DelegateCommand(NavigateToLastRevision, CanNavigateToLastRevision);
            CompareWithPreviousCommand = new DelegateCommand(CompareWithPrevious, CanCompareWithPrevious);
            CompareCurrentFileCommand  = new DelegateCommand(CompareCurrentFile, CanCompareCurrentFile);
            CopyCommentCommand         = new DelegateCommand(CopyComment, CanCopyComment);

            int line = lineNumber - 1 ?? 0;

            InitializeFileDiffInfo();
            Blame           = fileDiffInfo.BlameAtRevision(LastRevision);
            CurrentRevision = LastRevision;
            CurrentLine     = Blame.ElementAtOrDefault(line);
        }
Exemplo n.º 21
0
        public void CodeMergeItemWithDefaultOptionsShallSucceed()
        {
            //Setup
            var inputCode          = @"public string Something { get; set; }

";
            var expectedOutputCode = @"public string Name { get; set; }

public string Code { get; set; }

public string Description { get; set; }

";
            var swapValue          = "Something";
            var mergeItem          = new MergeItem
            {
                MergeParings = new List <MergePairing>
                {
                    new MergePairing {
                        SwapValue = swapValue, InputValue = "Name"
                    },
                    new MergePairing {
                        SwapValue = swapValue, InputValue = "Code"
                    },
                    new MergePairing {
                        SwapValue = swapValue, InputValue = "Description"
                    }
                }
            };


            var mergeOptions = new MergeOptions();//Default

            //Exercise
            var actualCodeOutput = MergeHelper.MergeItem(inputCode, mergeItem, mergeOptions);

            //Verify
            Assert.AreEqual(expectedOutputCode, actualCodeOutput, "The actual code output is not what was expected: " + actualCodeOutput);
        }
Exemplo n.º 22
0
        //void ShowExternalBlameInternal(Uri svnFile, int? lineNumber) {
        //    if (string.IsNullOrEmpty(svnFile.ToString()))
        //        throw new ArgumentException("svnFile");

        //    var startInfo = new ProcessStartInfo();
        //    startInfo.FileName = GetTortoiseProcPath();
        //    startInfo.Arguments = string.Format("/command:blame /path:{0} /startrev:0 /endrev:-1", svnFile.AbsoluteUri);

        //    if (lineNumber.HasValue)
        //        startInfo.Arguments += string.Format(" /line:{0}", lineNumber);

        //    using (Process process = Process.Start(startInfo)) {
        //        process.WaitForExit();
        //    }
        //}
        void PrepareBlameFileAndShowBlameUI(string filePath, int?lineNumber)
        {
            string blameFile = null;
            string logFile   = null;

            try {
                IDXVcsRepository dxRepository = DXVcsConnectionHelper.Connect(portOptions.VcsServer);
                MergeHelper      helper       = new MergeHelper(options, portOptions);
                string           vcsFile      = helper.GetMergeVcsPathByOriginalPath(filePath, portOptions.MasterBranch);

                FileDiffInfo       diffInfo = dxRepository.GetFileDiffInfo(vcsFile);
                int                revision = diffInfo.LastRevision;
                IList <IBlameLine> blame    = diffInfo.BlameAtRevision(revision);
                blameFile = MakeBlameFile(vcsFile, blame);
                logFile   = MakeLog(blame);
                ShowExternalBlameInternal(filePath, vcsFile, blameFile, logFile, revision, lineNumber);
            }
            finally {
                blameFile.Do(File.Delete);
                logFile.Do(File.Delete);
            }
        }
Exemplo n.º 23
0
        public override bool Run(Dictionary <string, string> mergeValues)
        {
            var qry = MergeHelper.Merge(settings.Query, mergeValues);

            try
            {
                if (settings.UseSisyphusContext)
                {
                    var context = new DataContext();
                    context.RawSqlQuery(qry, 3600);
                }
                else
                {
                    var context = new RestorationContext();
                    context.RawSqlQuery(qry, 3600);
                }

                return(true);
            }
            catch (Exception e)
            {
                return(settings.ContinueOnError);
            }
        }
Exemplo n.º 24
0
        private void Merge()
        {
            //Setup
            string inputCode = this.txtInputCode.Text;

            var mergeItem = new MergeItem
            {
                MergeParings =
                    this.GetInputValues()
                    .Select(i => new MergePairing {
                    SwapValue = this.SwapValue, InputValue = i
                })
                    .ToList()
            };

            var mergeOptions = new MergeOptions {
                CameliseSubstitutionAlso = this.cbCamel.Checked, SpaciliseSubstitutionAlso = this.cbAddSpaces.Checked
            };

            //Exercise
            var actualCodeOutput = MergeHelper.MergeItem(inputCode, mergeItem, mergeOptions);

            this.txtOutputCode.Text = actualCodeOutput;
        }
Exemplo n.º 25
0
        public void NavigateToSolution(string path)
        {
            var helper = new MergeHelper(this);

            helper.NavigateToSolution(path, dte);
        }
Exemplo n.º 26
0
        void CompareWithPortVersion()
        {
            var helper = new MergeHelper(this);

            helper.CompareWithPortVersion(SelectedItem.Path, CurrentBranch, SelectedItem.IsNew);
        }
Exemplo n.º 27
0
 void Blame()
 {
     var helper = new MergeHelper(this);
 }
Exemplo n.º 28
0
        public static byte[] GetOwnerVerification(OwnerVerificationReportModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      ownerCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (HetOwner owner in reportModel.Owners)
                        {
                            ownerCount++;

                            using (MemoryStream ownerStream = new MemoryStream())
                            {
                                WordprocessingDocument ownerDocument = (WordprocessingDocument)wordTemplate.Clone(ownerStream);
                                ownerDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", owner.Classification },
                                    { "districtAddress", reportModel.DistrictAddress },
                                    { "districtContact", reportModel.DistrictContact },
                                    { "organizationName", owner.OrganizationName },
                                    { "address1", owner.Address1 },
                                    { "address2", owner.Address2 },
                                    { "reportDate", reportModel.ReportDate },
                                    { "ownerCode", owner.OwnerCode },
                                    { "sharedKeyHeader", owner.SharedKeyHeader },
                                    { "sharedKey", owner.SharedKey },
                                    { "workPhoneNumber", owner.PrimaryContact.WorkPhoneNumber }
                                };

                                // update classification number first [ClassificationNumber]
                                owner.Classification = owner.Classification.Replace("&", "&amp;");
                                bool found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("ClassificationNumber"))
                                            {
                                                // replace text
                                                text.InnerXml = text.InnerXml.Replace("<w:t>ClassificationNumber</w:t>",
                                                                                      $"<w:t xml:space='preserve'>ORCS: {owner.Classification}</w:t>");

                                                found = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // update merge fields
                                MergeHelper.ConvertFieldCodes(ownerDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, ownerDocument.MainDocumentPart.Document);
                                ownerDocument.MainDocumentPart.Document.Save();

                                // setup table for equipment data
                                Table     equipmentTable = GenerateEquipmentTable(owner.HetEquipment);
                                Paragraph tableParagraph = null;
                                found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("Owner Equipment Table"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(equipmentTable);
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // merge owner into the master document
                                if (ownerCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in ownerDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)ownerDocument.Clone(documentStream);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = ownerDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = ownerDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = ownerDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    ownerDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph         para      = new Paragraph();
                                    SectionProperties sectProp  = new SectionProperties();
                                    SectionType       secSbType = new SectionType()
                                    {
                                        Val = SectionMarkValues.OddPage
                                    };
                                    PageSize pageSize = new PageSize()
                                    {
                                        Width = 11900U, Height = 16840U, Orient = PageOrientationValues.Portrait
                                    };
                                    PageMargin pageMargin = new PageMargin()
                                    {
                                        Top = 2642, Right = 23U, Bottom = 278, Left = 23U, Header = 714, Footer = 0, Gutter = 0
                                    };

                                    // page numbering throws out the "odd page" section breaks
                                    //PageNumberType pageNum = new PageNumberType() {Start = 1};

                                    sectProp.AppendChild(secSbType);
                                    sectProp.AppendChild(pageSize);
                                    sectProp.AppendChild(pageMargin);
                                    //sectProp.AppendChild(pageNum);

                                    ParagraphProperties paragraphProperties = new ParagraphProperties(sectProp);
                                    para.AppendChild(paragraphProperties);

                                    mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{ownerCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();

                                    ownerStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(ownerStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 29
0
 bool FilterItems(ProjectItemBase item, MergeHelper helper)
 {
     return(item.IsNew && !string.IsNullOrEmpty(item.FullPath) && !helper.IsItemUnderVss(item.FullPath, MasterBranch));
 }
Exemplo n.º 30
0
        public static byte[] GetRentalAgreement(RentalAgreementDocViewModel reportModel, string name)
        {
            try
            {
                char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[] { 10 });
                char   crLf       = characters[0];

                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Rental Agreement template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        using (MemoryStream agreementStream = new MemoryStream())
                        {
                            WordprocessingDocument agreementDocument = (WordprocessingDocument)wordTemplate.Clone(agreementStream);
                            agreementDocument.Save();

                            // create note
                            string note = "";
                            if (reportModel.Note != null)
                            {
                                foreach (NoteLine line in reportModel.Note)
                                {
                                    if (!string.IsNullOrEmpty(note))
                                    {
                                        note += $"{crLf.ToString()}{line.Line}";
                                    }
                                    else
                                    {
                                        note += $"{line.Line}";
                                    }
                                }
                            }

                            // equipment full name
                            string equipmentName = $"{reportModel.Equipment.Year}/" +
                                                   $"{reportModel.Equipment.Make}/" +
                                                   $"{reportModel.Equipment.Model}/" +
                                                   $"{reportModel.Equipment.Size}/" +
                                                   $"{reportModel.Equipment.SerialNumber}";

                            // rates included in total
                            string rateString1 = "";
                            string comment1    = "";
                            if (reportModel.RentalAgreementRatesWithTotal != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesWithTotal)
                                {
                                    if (!string.IsNullOrEmpty(rateString1))
                                    {
                                        rateString1 += $"{crLf.ToString()}{rate.RateString}";
                                        comment1    += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        rateString1 += $"{rate.RateString}";
                                        comment1    += $"{rate.Comment}";
                                    }
                                }
                            }

                            // rates not included in total
                            string rateString2 = "";
                            string comment2    = "";
                            if (reportModel.RentalAgreementRatesWithoutTotal != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesWithoutTotal)
                                {
                                    if (!string.IsNullOrEmpty(rateString2))
                                    {
                                        rateString2 += $"{crLf.ToString()}{rate.RateString}";
                                        comment2    += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        rateString2 += $"{rate.RateString}";
                                        comment2    += $"{rate.Comment}";
                                    }
                                }
                            }

                            // agreement conditions
                            string comment3 = "";
                            if (reportModel.RentalAgreementConditions != null)
                            {
                                foreach (HetRentalAgreementCondition cond in reportModel.RentalAgreementConditions)
                                {
                                    var conditionComment = string.IsNullOrEmpty(cond.Comment) ? cond.ConditionName : cond.Comment;

                                    if (!string.IsNullOrEmpty(comment3))
                                    {
                                        comment3 += $"{crLf.ToString()}{conditionComment}";
                                    }
                                    else
                                    {
                                        comment3 += $"{conditionComment}";
                                    }
                                }
                            }

                            // rates not included in total
                            string overtimeRate    = "";
                            string overtimeComment = "";
                            if (reportModel.RentalAgreementRatesOvertime != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesOvertime.OrderByDescending(x => x.Comment))
                                {
                                    if (!string.IsNullOrEmpty(overtimeRate))
                                    {
                                        overtimeRate    += $"{crLf.ToString()}{rate.RateString}";
                                        overtimeComment += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        overtimeRate    += $"{rate.RateString}";
                                        overtimeComment += $"{rate.Comment}";
                                    }
                                }
                            }

                            Dictionary <string, string> values = new Dictionary <string, string>
                            {
                                { "classification", reportModel.Classification },
                                { "equipmentCode", reportModel.Equipment.EquipmentCode },
                                { "number", reportModel.Number },
                                { "organizationName", reportModel.Equipment.Owner.OrganizationName },
                                { "address1", reportModel.Equipment.Owner.Address1 },
                                { "address2", reportModel.Equipment.Owner.Address2 },
                                { "ownerCode", reportModel.Equipment.Owner.OwnerCode },
                                { "workPhoneNumber", reportModel.Equipment.Owner.PrimaryContact.WorkPhoneNumber },
                                { "mobilePhoneNumber", reportModel.Equipment.Owner.PrimaryContact.MobilePhoneNumber },
                                { "faxPhoneNumber", reportModel.Equipment.Owner.PrimaryContact.FaxPhoneNumber },
                                { "equipmentFullName", equipmentName },
                                { "noteLine", note },
                                { "baseRateString", reportModel.BaseRateString },
                                { "rateComment", reportModel.RateComment },
                                { "projectNumber", reportModel.Project.ProvincialProjectNumber },
                                { "projectName", reportModel.Project.Name },
                                { "district", reportModel.Project.District.Name },
                                { "estimateHours", reportModel.EstimateHours.ToString() },
                                { "estimateStartWork", reportModel.EstimateStartWork },
                                { "localAreaName", reportModel.Equipment.LocalArea.Name },
                                { "workSafeBcpolicyNumber", reportModel.Equipment.Owner.WorkSafeBcpolicyNumber },
                                { "agreementCity", reportModel.AgreementCity },
                                { "datedOn", reportModel.DatedOn },
                                { "rateString1", rateString1 },
                                { "comment1", comment1 },
                                { "agreementTotalString", reportModel.AgreementTotalString },
                                { "rateString2", rateString2 },
                                { "comment2", comment2 },
                                { "comment3", comment3 },
                                { "overtimeRate", overtimeRate },
                                { "overtimeComment", overtimeComment },
                                { "doingBusinessAs", reportModel.DoingBusinessAs },
                                { "emailAddress", reportModel.EmailAddress }
                            };

                            // update main document
                            MergeHelper.ConvertFieldCodes(agreementDocument.MainDocumentPart.Document);
                            MergeHelper.MergeFieldsInElement(values, agreementDocument.MainDocumentPart.Document);
                            agreementDocument.MainDocumentPart.Document.Save();

                            wordDocument = (WordprocessingDocument)agreementDocument.Clone(documentStream);

                            agreementDocument.Close();
                            agreementDocument.Dispose();
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }