Thursday, May 30, 2024

Merging PDF Files Based on Name Segments in C#

Merging PDF Files Based on Name Segments in C#

In this blog post, we will explore how to merge multiple PDF files using C#. The merging process will be based on a specific segment of each file's filename.

Scenario Overview

Assume you have a folder containing several PDF files named in a format that includes underscore-separated segments. The goal is to combine these PDFs into larger files based on the second segment of their filenames.

Step-by-Step Solution

  1. Setup and Initialization
  2. We start by defining the paths to our input and output folders:

    string folderPath = "C:\\Users\\ersan\\Downloads\\Form10BE_AAPAM3947A_2023_238914720240524_1";
    string outputFolder = "C:\\Users\\ersan\\Downloads\\output2\\";
  3. Sorting Files
  4. We retrieve all files from the input folder and sort them based on their filenames:

    var files = Directory.GetFiles(folderPath);
    Array.Sort(files, (a, b) => string.Compare(Path.GetFileName(a), Path.GetFileName(b)));
  5. Iterating and Merging
  6. We iterate through the sorted list of files, extracting the second segment of each filename. If the segment changes, we merge the current list of files into a single PDF:

    string lastName = "";
    var file2 = outputFolder + Path.GetFileName(files[0]);
    List list = new List();
    
    foreach (var file in files)
    {
        var fileName = Path.GetFileNameWithoutExtension(file);
        var splitName = fileName.Split('_');
        var name = splitName[1];
    
        if (!string.IsNullOrEmpty(lastName) && lastName.ToLower() != name.ToLower())
        {
            CombineMultiplePDFs(list.ToArray(), file2);
            file2 = outputFolder + Path.GetFileName(file);
            list = new List();
        }
    
        list.Add(file);
        lastName = name;
    }
  7. PDF Merging Method
  8. The CombineMultiplePDFs method takes an array of filenames and merges them into a single PDF:

    public static void CombineMultiplePDFs(string[] fileNames, string outFile)
    {
        if (File.Exists(outFile))
            throw new Exception("File already exists.");
    
        Document document = new Document();
        using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
        {
            PdfCopy writer = new PdfCopy(document, newFileStream);
            document.Open();
    
            foreach (string fileName in fileNames)
            {
                PdfReader reader = new PdfReader(fileName);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }
                reader.Close();
            }
    
            writer.Close();
            document.Close();
        }
    }
    
  9. Conclusion
  10. After processing all files, the merged PDFs are saved in the output folder. A success message is printed in the console upon completion.

Complete Code

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;

namespace PDFMerger
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string folderPath = "C:\\Users\\ersan\\Downloads\\Form10BE_AAPAM3947A_2023_238914720240524_1";
            string outputFolder = "C:\\Users\\ersan\\Downloads\\output2\\";
            var files = Directory.GetFiles(folderPath);
            Array.Sort(files, (a, b) => string.Compare(Path.GetFileName(a), Path.GetFileName(b)));

            string lastName = "";
            // Create a new PDF document with a 50-point margin

            var file2 = outputFolder + Path.GetFileName(files[0]);

            List list = new List();

            foreach (var file in files)
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                var splitName = fileName.Split('_');
                var name = splitName[1];
                if (!string.IsNullOrEmpty(lastName) && lastName.ToLower() != name.ToLower())
                {
                    CombineMultiplePDFs(list.ToArray(), file2);
                    file2 = outputFolder + Path.GetFileName(file);
                    list = new List();
                }
                list.Add(file);
                lastName = name;
            }

            // Print the success message
            Console.WriteLine("PDF files merged successfully!");
        }

        public static void CombineMultiplePDFs(string[] fileNames, string outFile)
        {
            if (File.Exists(outFile))
                throw new Exception("122");
            // step 1: creation of a document-object
            Document document = new Document();
            //create newFileStream object which will be disposed at the end
            using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
            {
                // step 2: we create a writer that listens to the document
                PdfCopy writer = new PdfCopy(document, newFileStream);

                // step 3: we open the document
                document.Open();

                foreach (string fileName in fileNames)
                {
                    // we create a reader for a certain document
                    PdfReader reader = new PdfReader(fileName);
                    reader.ConsolidateNamedDestinations();

                    // step 4: we add content
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }

                    reader.Close();
                }
                writer.Close();
                document.Close();
        }

    }

}
      
Final Thoughts

This solution provides a straightforward approach to programmatically merge PDF files based on a specific naming convention using C#. By leveraging libraries like iTextSharp (via PdfCopy), you can efficiently handle and consolidate PDF documents based on your application's requirements.

This approach can be extended or customized further to meet additional criteria or integrate with other functionalities as needed.

For more details, you can refer to the complete code and explanation above.

Automating Email with VBA in Excel Macro

Automating Email with VBA

In this blog post, I will walk you through a VBA script that automates the process of sending emails using Outlook. Below is the script and an explanation of how it works:

                
Sub SendEmail()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim ws As Worksheet
    Dim rng As Range
    Dim toEmail() As String
    Dim ccEmail() As String
    Dim subject As String
    Dim body As String
    Dim filePath As String
    Dim i As Long
    
    Set OutApp = CreateObject("Outlook.Application")
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    For Each rng In ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
        toEmail = Split(rng.Value, ";")
        ccEmail = Split(rng.Offset(0, 1).Value, ";")
        subject = rng.Offset(0, 2).Value
        body = rng.Offset(0, 3).Value
        filePath = rng.Offset(0, 4).Value
        
        Set OutMail = OutApp.CreateItem(0)
        With OutMail
            ' Add To recipients
            For i = LBound(toEmail) To UBound(toEmail)
                .Recipients.Add toEmail(i)
            Next i
            
            ' Add CC recipients
            For i = LBound(ccEmail) To UBound(ccEmail)
                .Recipients.Add ccEmail(i)
            Next i
            
            .subject = subject
            .body = body
              
            ' Attach file if path is provided
            If filePath <> "" Then
                .Attachments.Add filePath
            End If
                  
            .Send
        End With
        
        Set OutMail = Nothing
    Next rng
    
    Set OutApp = Nothing
End Sub

                
            

Explanation:

  • OutApp and OutMail: These objects are used to interface with Outlook.
  • ws: Refers to the worksheet containing the email data.
  • rng: Loops through each row of data to extract email details.
  • toEmail, ccEmail, subject, body, filePath: Variables to store email details from the worksheet.
  • The script sets the necessary fields for each email and sends it using Outlook.

Wednesday, May 1, 2024

Exploring My Passions: Music, Movies, Family, and More

Exploring My Passions: Music, Movies, Family, and More

Hello! I’m excited to share a bit about myself and the things I’m passionate about. From music to movies, and spending quality time with family and friends, here’s a glimpse into my world.

The Soundtrack of My Life: Indian Melody Songs

Music has always been a significant part of my life. I have a deep appreciation for Indian melody songs. The rich and diverse musical heritage of India offers a plethora of melodious tunes that can uplift the spirit and soothe the soul. Whether it’s classical, folk, or contemporary, Indian music has a unique way of connecting with the heart.

A Cinematic Favorite: 3 Idiots

When it comes to movies, "3 Idiots" stands out as my all-time favorite. This film is not just entertaining but also thought-provoking, offering valuable life lessons wrapped in humor and emotion. The story of friendship, the importance of pursuing one’s passion, and the critique of the traditional education system resonate deeply with me. It's a film that I can watch over and over again.

Family Life in Delhi NCR

I live in Delhi NCR with my family, and spending time with them is something I cherish immensely. The bustling city life, combined with the comfort of family, makes every moment special. Whether it’s enjoying a meal together, going for a walk, or just having a heartfelt conversation, these moments are priceless.

The Joy of Traveling

Traveling is another passion of mine. Exploring new places, experiencing different cultures, and meeting new people bring a sense of adventure and joy. Whether it’s a weekend getaway or a long vacation, traveling helps me unwind and gain a fresh perspective on life.

Friends: The Chosen Family

Apart from my family, I also love spending time with my friends. They are my chosen family, and our time together is filled with laughter, support, and countless memories. Whether we’re hanging out at our favorite spots in Delhi NCR or planning trips together, the bond we share is invaluable.

A Passion for Table Tennis

I am a big fan of table tennis and love watching the game. The speed, skill, and strategy involved make it incredibly exciting. Whether it’s watching international tournaments or local matches, table tennis never fails to captivate me. It’s not just about the competition but also the sportsmanship and the sheer joy of the game.

Conclusion

In conclusion, my life is enriched by a mix of music, movies, travel, and cherished moments with family and friends. Each of these passions adds a unique flavor to my life, making it vibrant and fulfilling. Thank you for taking the time to read about my interests. I hope this post gives you a glimpse into the things that make my life special.

Wednesday, April 10, 2024

Need detail for ESI

ESI-- Date of joining Aadhar card Mobile number Father name/Nominee detail Bank detail(IFSC Code and account number)

Tuesday, April 9, 2024

Mastering Print Functionality in Web Development with jQuery

Mastering Print Functionality in Web Development with jQuery

In today's blog post, we're going to delve into an essential feature for web applications: print functionality. This is especially useful for applications that involve invoices, reports, or any content that users might need a physical copy of. We’ll explore how to implement this using JavaScript and jQuery with a simple and effective approach.

Understanding the Code

Let’s break down the snippet that makes this magic happen:

var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);

This piece of code ensures that only the desired content gets printed while temporarily hiding the rest of the page. Here's how it works step-by-step:

Backup the Current Page Content

var restorepage = $('body').html();

We start by saving the current HTML content of the entire body. This allows us to restore it after the printing is done.

Clone the Content to be Printed

var printcontent = $('#' + el).clone();

Here, we clone the HTML content of the element with the ID stored in the variable el. Cloning is essential to keep the original content intact in the DOM.

Replace the Body Content with the Cloned Content

$('body').empty().html(printcontent);

The body of the document is emptied and replaced with the cloned content. Now, only the content we want to print is visible in the body.

Trigger the Print Dialog

window.print();

This command triggers the browser's print dialog, allowing the user to print the current view of the page.

Restore the Original Page Content

$('body').html(restorepage);

Finally, the original content of the body is restored, making the page look as it was before the print action was initiated.

Implementing the Print Functionality

To implement this functionality in your web application, follow these steps:

Include jQuery

Make sure jQuery is included in your project. You can add it via CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Create the Print Function

Add the following JavaScript function to your script:

function printElement(el) {
    var restorepage = $('body').html();
    var printcontent = $('#' + el).clone();
    $('body').empty().html(printcontent);
    window.print();
    $('body').html(restorepage);
}

Add a Print Button

Create a button or link that calls the printElement function when clicked. Make sure to pass the ID of the element you want to print:

<button onclick="printElement('printSection')">Print Content</button>

Mark the Content to Print

Wrap the content you want to print within an element with a specific ID:

<div id="printSection">
    <!-- Content to be printed -->
</div>

Considerations

  • Styles for Print: Ensure that your print styles are properly defined in your CSS. You can use @media print to customize the appearance of your content when printed.
  • Content Cloning: Cloning the content ensures that any interactive elements (like forms or scripts) are not copied over to the print view, preventing potential issues.

By following these steps, you can add robust print functionality to your web application, enhancing its usability and user experience.

Conclusion

Printing web content is a common requirement, and with jQuery, it's a breeze to implement. The code snippet we discussed provides a straightforward method to print specific parts of your web page without any hassle. Try integrating this into your next project and see how it improves the functionality and professionalism of your application.

Tuesday, January 9, 2024

How to Add a Filter to a Lookup Field in Microsoft Dynamics CRM

How to Add a Filter to a Lookup Field in Microsoft Dynamics CRM

In Microsoft Dynamics CRM, there are times when you need to filter the records displayed in a lookup field to show only a subset of the data. This can be achieved using JavaScript to add a pre-search filter. In this blog, we'll walk you through the steps to filter active contacts in a lookup field.

Step-by-Step Guide

Step 1: Create a JavaScript Web Resource

  1. Navigate to CRM:

    Go to your Dynamics CRM environment.

  2. Open the Solution:

    Open the solution where you want to add the JavaScript.

  3. Add a Web Resource:
    • Go to the "Web Resources" section.
    • Click on "New" and create a new JavaScript web resource.
  4. Add the JavaScript Code:

    Copy and paste the following JavaScript code into your new web resource:

    function setActiveContactsFilter(executionContext) {
        var formContext = executionContext.getFormContext();
        var contacts = formContext.getControl("new_activecontacts");
        contacts.addPreSearch(filterActiveContacts);
    }
    
    function filterActiveContacts() {
        var fetchXml = [
            "<filter type='and'>",
            "  <condition attribute='statuscode' operator='eq' value='1' />", // Adjust the value based on your status code for 'Active'
            "</filter>"
        ].join('');
        
        // Get the lookup control
        var lookupControl = Xrm.Page.getControl("new_activecontacts");
        
        // Fetch the view ID and entity name
        var viewId = "{00000000-0000-0000-0000-000000000000}"; // Replace with the actual view ID if required
        var entityName = "contact"; // Replace with the actual entity name if different
    
        // Create the view
        var viewDisplayName = "Filtered Active Contacts";
        var viewIsDefault = true;
        var layoutXml = ""; // Define the layout XML if needed
    
        // Add the view
        lookupControl.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, viewIsDefault);
    }

    Save and publish the web resource.

Step 2: Add the JavaScript Web Resource to the Form

  1. Open the Form:

    Open the form where you want to add the lookup filter.

  2. Form Properties:

    Click on "Form Properties".

  3. Add the Web Resource:
    • In the "Form Libraries" section, add the JavaScript web resource you created.
    • In the "Event Handlers" section, add an event handler for the OnLoad event.
    • Set the function name to setActiveContactsFilter.
    • Ensure "Pass execution context as first parameter" is checked.
  4. Save and Publish:

    Save and publish your form changes.

Step 3: Test the Lookup Filter

  1. Open the Form:

    Navigate to the form where you applied the changes.

  2. Verify the Lookup Field:

    Click on the lookup field and verify that it now only displays active contacts.

Conclusion

Adding a filter to a lookup field in Microsoft Dynamics CRM can significantly enhance the user experience by ensuring that users only see relevant records. By following the steps outlined above, you can easily implement a filter for active contacts or any other criteria you require. Happy customizing!

Tuesday, December 26, 2023

Six Essential Principles of Success in Trading

Six Essential Principles of Success in Trading

Success in trading is not just about luck or intuition; it involves a systematic approach grounded in solid principles. Here are six essential principles to guide you on your trading journey:

1. Information

Having a solid grasp of relevant knowledge is crucial. It’s important to stay informed and up-to-date on the latest developments in your field. In trading, this means keeping abreast of market news, trends, and financial data.

2. Planning

Strategic preparation sets the foundation. Planning helps you identify your goals, develop a roadmap to achieve them, and stay on track. A well-thought-out trading plan includes risk management strategies, entry and exit points, and criteria for evaluating trades.

3. Timing

Precision in execution is essential. Timing is critical in achieving success. Knowing when to act and when to wait can make all the difference. This involves understanding market cycles, recognizing patterns, and being patient enough to wait for the right opportunities.

4. Practice

Consistent rehearsal is paramount. Practice helps you hone your skills, build confidence, and prepare for success. Simulated trading, also known as paper trading, can be an effective way to practice without risking real money.

5. Patience

Endurance through challenges is indispensable. Patience is key to overcoming obstacles and persevering through difficult times. Markets can be unpredictable, and having the patience to stick to your plan is essential for long-term success.

6. Results

The culmination of efforts and dedication. Results are the ultimate measure of success. They reflect the hard work, dedication, and perseverance that went into achieving your goals. Regularly review your trading performance to understand what’s working and what needs improvement.

Remember, success is not just about achieving your goals, but also about the journey you take to get there. Keep these principles in mind and you’ll be well on your way to achieving your dreams!

Featured Post

Links

https://www.examtopics.com/discussions/microsoft/view/52755-exam-pl-600-topic-2-question-4-discussion/ https://www.examtopics.com/discussion...