Code refactoring -DRY c#











up vote
0
down vote

favorite












Need some help in code refactoring as there is lot of duplicated code:



public class Client
{
private List<MailMessage> _mailMessages;

/// <summary>
/// This method checks if a pdf file is editable.
/// </summary>
/// <param name="fileContents"></param>
/// <returns>true (if editable) or false (if not editable)</returns>
private bool IsEditablePdf(byte fileContents)
{
var pdfReader = new PdfReader(fileContents);

if (pdfReader.AcroForm == null)
return false;

return true;
}

/// <summary>
/// This method converts an editable pdf to uneditable pdf.
/// </summary>
/// <param name="fileContents"></param>
/// <returns></returns>
private byte GetUnEditablePdf(byte fileContents)
{
byte uneditableFileContents;

var reader = new PdfReader(fileContents);

if (reader.AcroForm != null)
uneditableFileContents = FlattenPdfFormToBytes(reader);

else uneditableFileContents = fileContents;

return uneditableFileContents;
}

private List<MailMessage> GetMailWithSinglePdf()
{
var mailMessagesWithSinglePdf = new List<MailMessage>();

//load items from mailbox inbox folder
if (_mailMessages != null)
{
foreach (var message in _mailMessages)
{
var pdfCount = message.Attachments
.Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

// list of attachments contain one pdf
if (pdfCount == 1)
mailMessagesWithSinglePdf.Add(message);
}
}

return mailMessagesWithSinglePdf;
}

private List<MailMessage> GetMailWithMultiplePdf()
{
var mailMessagesWithMultiplePdf = new List<MailMessage>();

//load items from mailbox inbox folder
if (_mailMessages != null)
{
foreach (var message in _mailMessages)
{
var pdfCount = message.Attachments
.Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

// list of attachments contain one pdf
if (pdfCount > 1)
mailMessagesWithMultiplePdf.Add(message);
}
}

return mailMessagesWithMultiplePdf;
}

private int PageCount(FileAttachment pdfAttachment)
{
using (var reader = new PdfReader(pdfAttachment.Content))
return reader.NumberOfPages;
}

private void SaveToEmaDirectory(string filePath, byte fileContent)
{
File.WriteAllBytes(filePath, fileContent);
}

private string GenerateFilePath(FileAttachment singlePagePdf)
{
if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

return Path.Combine(
Statics.EmaFileWatcherWorkingDirectory,
GenerateFileName(singlePagePdf));
}

private string GenerateFileName(FileAttachment singlePagePdf)
{
if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

return string.Join("_",
"fax",
DateTime.Now.Date.ToString("ddMMyy"),
singlePagePdf.Name,
DateTime.Now.Ticks + ".pdf");
}

private byte UnEditableVersionOf(byte pdfContent)
{
if (pdfContent == null) throw new ArgumentNullException(nameof(pdfContent));

return IsEditablePdf(pdfContent)
? GetUnEditablePdf(pdfContent)
: pdfContent;
}

/// <summary>
/// Moves this item to a the specified folder. Calling this method results in a call to EWS.
/// </summary>
/// <param name="destinationFolderName"></param>
/// <param name="messages"></param>
public void MoveMailToFolder(string destinationFolderName, List<MailMessage> messages)
{
if (string.IsNullOrWhiteSpace(destinationFolderName))
throw new MessageException("Invalid folder name");

if (messages != null && (messages.Any()))
{
var fId = GetFolderId(destinationFolderName);
var results = WorkingFolder.FindItems(new ItemView(100));

if (results?.Items?.Count > 0)
foreach (var item in results.Items)
{
if (item is EmailMessage)
{
item.Load();

var mailMessage = new MailMessage();
mailMessage.Id = item.Id.ToString();

if (messages.Contains(mailMessage))
item.Move(fId);
}
}
}
}

public void MoveSinglePagePdfToFolder()
{
var messagesWithSinglePdf = GetMailWithSinglePdf();

var processed = new List<MailMessage>();
var rejected = new List<MailMessage>();

if (messagesWithSinglePdf?.Count > 0)
{
foreach (var message in messagesWithSinglePdf)
{
_service.GetAttachments(
message.Attachments.ToArray(),
BodyType.HTML,
null);

var pdfAttachment = message
.Attachments
.Cast<FileAttachment>()
.Single(attachment => attachment.Name.EndsWith(".pdf"));

if (PageCount(pdfAttachment) == 1)
{
SaveToEmaDirectory(GenerateFilePath(pdfAttachment), UnEditableVersionOf(pdfAttachment.Content));

processed.Add(message);
}

else rejected.Add(message);
}

MoveMailToFolder(Statics.Rejected, rejected);
MoveMailToFolder(Statics.Processed, processed);
}
}

public void MoveMultiplePagePdfToFolder()
{
var messagesWithMultiplePdf = GetMailWithMultiplePdf();

var processed = new List<MailMessage>();
var rejected = new List<MailMessage>();

if (messagesWithMultiplePdf?.Count > 0)
{
foreach (var message in messagesWithMultiplePdf)
{
_service.GetAttachments(
message.Attachments.ToArray(),
BodyType.HTML,
null);

var pdfAttachmentList = message
.Attachments
.Cast<FileAttachment>()
.Where(attachment => attachment.Name.EndsWith(".pdf"));

bool isMessageOk = true;

foreach (var pdfAttachment in pdfAttachmentList)
{
if (PageCount(pdfAttachment) != 1)
/*SaveToEmaDirectory(GenerateFilePath(pdfAttachment),
UnEditableVersionOf(pdfAttachment.Content))*/;
isMessageOk = false;
}

if(isMessageOk)
processed.Add(message);

else rejected.Add(message);
}

MoveMailToFolder(Statics.Rejected, rejected);
MoveMailToFolder(Statics.Processed, processed);
}
}
}


The two methods MoveMultiplePagePdfToFolder and MoveSinglePagePdfToFolder are nearly same. MoveSinglePagePdfToFolder contains all email messages with single pdf as attachments and if the number of pages in pdf is 1, then it sends to Processed folder else Rejected.



MoveMultiplePagePdfToFolder checks multiple pdf attachments in message and if all of them contain single page then it moves the message to Processed otherwise Rejected.



Hope it helps.









share







New contributor




Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    0
    down vote

    favorite












    Need some help in code refactoring as there is lot of duplicated code:



    public class Client
    {
    private List<MailMessage> _mailMessages;

    /// <summary>
    /// This method checks if a pdf file is editable.
    /// </summary>
    /// <param name="fileContents"></param>
    /// <returns>true (if editable) or false (if not editable)</returns>
    private bool IsEditablePdf(byte fileContents)
    {
    var pdfReader = new PdfReader(fileContents);

    if (pdfReader.AcroForm == null)
    return false;

    return true;
    }

    /// <summary>
    /// This method converts an editable pdf to uneditable pdf.
    /// </summary>
    /// <param name="fileContents"></param>
    /// <returns></returns>
    private byte GetUnEditablePdf(byte fileContents)
    {
    byte uneditableFileContents;

    var reader = new PdfReader(fileContents);

    if (reader.AcroForm != null)
    uneditableFileContents = FlattenPdfFormToBytes(reader);

    else uneditableFileContents = fileContents;

    return uneditableFileContents;
    }

    private List<MailMessage> GetMailWithSinglePdf()
    {
    var mailMessagesWithSinglePdf = new List<MailMessage>();

    //load items from mailbox inbox folder
    if (_mailMessages != null)
    {
    foreach (var message in _mailMessages)
    {
    var pdfCount = message.Attachments
    .Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

    // list of attachments contain one pdf
    if (pdfCount == 1)
    mailMessagesWithSinglePdf.Add(message);
    }
    }

    return mailMessagesWithSinglePdf;
    }

    private List<MailMessage> GetMailWithMultiplePdf()
    {
    var mailMessagesWithMultiplePdf = new List<MailMessage>();

    //load items from mailbox inbox folder
    if (_mailMessages != null)
    {
    foreach (var message in _mailMessages)
    {
    var pdfCount = message.Attachments
    .Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

    // list of attachments contain one pdf
    if (pdfCount > 1)
    mailMessagesWithMultiplePdf.Add(message);
    }
    }

    return mailMessagesWithMultiplePdf;
    }

    private int PageCount(FileAttachment pdfAttachment)
    {
    using (var reader = new PdfReader(pdfAttachment.Content))
    return reader.NumberOfPages;
    }

    private void SaveToEmaDirectory(string filePath, byte fileContent)
    {
    File.WriteAllBytes(filePath, fileContent);
    }

    private string GenerateFilePath(FileAttachment singlePagePdf)
    {
    if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

    return Path.Combine(
    Statics.EmaFileWatcherWorkingDirectory,
    GenerateFileName(singlePagePdf));
    }

    private string GenerateFileName(FileAttachment singlePagePdf)
    {
    if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

    return string.Join("_",
    "fax",
    DateTime.Now.Date.ToString("ddMMyy"),
    singlePagePdf.Name,
    DateTime.Now.Ticks + ".pdf");
    }

    private byte UnEditableVersionOf(byte pdfContent)
    {
    if (pdfContent == null) throw new ArgumentNullException(nameof(pdfContent));

    return IsEditablePdf(pdfContent)
    ? GetUnEditablePdf(pdfContent)
    : pdfContent;
    }

    /// <summary>
    /// Moves this item to a the specified folder. Calling this method results in a call to EWS.
    /// </summary>
    /// <param name="destinationFolderName"></param>
    /// <param name="messages"></param>
    public void MoveMailToFolder(string destinationFolderName, List<MailMessage> messages)
    {
    if (string.IsNullOrWhiteSpace(destinationFolderName))
    throw new MessageException("Invalid folder name");

    if (messages != null && (messages.Any()))
    {
    var fId = GetFolderId(destinationFolderName);
    var results = WorkingFolder.FindItems(new ItemView(100));

    if (results?.Items?.Count > 0)
    foreach (var item in results.Items)
    {
    if (item is EmailMessage)
    {
    item.Load();

    var mailMessage = new MailMessage();
    mailMessage.Id = item.Id.ToString();

    if (messages.Contains(mailMessage))
    item.Move(fId);
    }
    }
    }
    }

    public void MoveSinglePagePdfToFolder()
    {
    var messagesWithSinglePdf = GetMailWithSinglePdf();

    var processed = new List<MailMessage>();
    var rejected = new List<MailMessage>();

    if (messagesWithSinglePdf?.Count > 0)
    {
    foreach (var message in messagesWithSinglePdf)
    {
    _service.GetAttachments(
    message.Attachments.ToArray(),
    BodyType.HTML,
    null);

    var pdfAttachment = message
    .Attachments
    .Cast<FileAttachment>()
    .Single(attachment => attachment.Name.EndsWith(".pdf"));

    if (PageCount(pdfAttachment) == 1)
    {
    SaveToEmaDirectory(GenerateFilePath(pdfAttachment), UnEditableVersionOf(pdfAttachment.Content));

    processed.Add(message);
    }

    else rejected.Add(message);
    }

    MoveMailToFolder(Statics.Rejected, rejected);
    MoveMailToFolder(Statics.Processed, processed);
    }
    }

    public void MoveMultiplePagePdfToFolder()
    {
    var messagesWithMultiplePdf = GetMailWithMultiplePdf();

    var processed = new List<MailMessage>();
    var rejected = new List<MailMessage>();

    if (messagesWithMultiplePdf?.Count > 0)
    {
    foreach (var message in messagesWithMultiplePdf)
    {
    _service.GetAttachments(
    message.Attachments.ToArray(),
    BodyType.HTML,
    null);

    var pdfAttachmentList = message
    .Attachments
    .Cast<FileAttachment>()
    .Where(attachment => attachment.Name.EndsWith(".pdf"));

    bool isMessageOk = true;

    foreach (var pdfAttachment in pdfAttachmentList)
    {
    if (PageCount(pdfAttachment) != 1)
    /*SaveToEmaDirectory(GenerateFilePath(pdfAttachment),
    UnEditableVersionOf(pdfAttachment.Content))*/;
    isMessageOk = false;
    }

    if(isMessageOk)
    processed.Add(message);

    else rejected.Add(message);
    }

    MoveMailToFolder(Statics.Rejected, rejected);
    MoveMailToFolder(Statics.Processed, processed);
    }
    }
    }


    The two methods MoveMultiplePagePdfToFolder and MoveSinglePagePdfToFolder are nearly same. MoveSinglePagePdfToFolder contains all email messages with single pdf as attachments and if the number of pages in pdf is 1, then it sends to Processed folder else Rejected.



    MoveMultiplePagePdfToFolder checks multiple pdf attachments in message and if all of them contain single page then it moves the message to Processed otherwise Rejected.



    Hope it helps.









    share







    New contributor




    Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Need some help in code refactoring as there is lot of duplicated code:



      public class Client
      {
      private List<MailMessage> _mailMessages;

      /// <summary>
      /// This method checks if a pdf file is editable.
      /// </summary>
      /// <param name="fileContents"></param>
      /// <returns>true (if editable) or false (if not editable)</returns>
      private bool IsEditablePdf(byte fileContents)
      {
      var pdfReader = new PdfReader(fileContents);

      if (pdfReader.AcroForm == null)
      return false;

      return true;
      }

      /// <summary>
      /// This method converts an editable pdf to uneditable pdf.
      /// </summary>
      /// <param name="fileContents"></param>
      /// <returns></returns>
      private byte GetUnEditablePdf(byte fileContents)
      {
      byte uneditableFileContents;

      var reader = new PdfReader(fileContents);

      if (reader.AcroForm != null)
      uneditableFileContents = FlattenPdfFormToBytes(reader);

      else uneditableFileContents = fileContents;

      return uneditableFileContents;
      }

      private List<MailMessage> GetMailWithSinglePdf()
      {
      var mailMessagesWithSinglePdf = new List<MailMessage>();

      //load items from mailbox inbox folder
      if (_mailMessages != null)
      {
      foreach (var message in _mailMessages)
      {
      var pdfCount = message.Attachments
      .Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

      // list of attachments contain one pdf
      if (pdfCount == 1)
      mailMessagesWithSinglePdf.Add(message);
      }
      }

      return mailMessagesWithSinglePdf;
      }

      private List<MailMessage> GetMailWithMultiplePdf()
      {
      var mailMessagesWithMultiplePdf = new List<MailMessage>();

      //load items from mailbox inbox folder
      if (_mailMessages != null)
      {
      foreach (var message in _mailMessages)
      {
      var pdfCount = message.Attachments
      .Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

      // list of attachments contain one pdf
      if (pdfCount > 1)
      mailMessagesWithMultiplePdf.Add(message);
      }
      }

      return mailMessagesWithMultiplePdf;
      }

      private int PageCount(FileAttachment pdfAttachment)
      {
      using (var reader = new PdfReader(pdfAttachment.Content))
      return reader.NumberOfPages;
      }

      private void SaveToEmaDirectory(string filePath, byte fileContent)
      {
      File.WriteAllBytes(filePath, fileContent);
      }

      private string GenerateFilePath(FileAttachment singlePagePdf)
      {
      if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

      return Path.Combine(
      Statics.EmaFileWatcherWorkingDirectory,
      GenerateFileName(singlePagePdf));
      }

      private string GenerateFileName(FileAttachment singlePagePdf)
      {
      if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

      return string.Join("_",
      "fax",
      DateTime.Now.Date.ToString("ddMMyy"),
      singlePagePdf.Name,
      DateTime.Now.Ticks + ".pdf");
      }

      private byte UnEditableVersionOf(byte pdfContent)
      {
      if (pdfContent == null) throw new ArgumentNullException(nameof(pdfContent));

      return IsEditablePdf(pdfContent)
      ? GetUnEditablePdf(pdfContent)
      : pdfContent;
      }

      /// <summary>
      /// Moves this item to a the specified folder. Calling this method results in a call to EWS.
      /// </summary>
      /// <param name="destinationFolderName"></param>
      /// <param name="messages"></param>
      public void MoveMailToFolder(string destinationFolderName, List<MailMessage> messages)
      {
      if (string.IsNullOrWhiteSpace(destinationFolderName))
      throw new MessageException("Invalid folder name");

      if (messages != null && (messages.Any()))
      {
      var fId = GetFolderId(destinationFolderName);
      var results = WorkingFolder.FindItems(new ItemView(100));

      if (results?.Items?.Count > 0)
      foreach (var item in results.Items)
      {
      if (item is EmailMessage)
      {
      item.Load();

      var mailMessage = new MailMessage();
      mailMessage.Id = item.Id.ToString();

      if (messages.Contains(mailMessage))
      item.Move(fId);
      }
      }
      }
      }

      public void MoveSinglePagePdfToFolder()
      {
      var messagesWithSinglePdf = GetMailWithSinglePdf();

      var processed = new List<MailMessage>();
      var rejected = new List<MailMessage>();

      if (messagesWithSinglePdf?.Count > 0)
      {
      foreach (var message in messagesWithSinglePdf)
      {
      _service.GetAttachments(
      message.Attachments.ToArray(),
      BodyType.HTML,
      null);

      var pdfAttachment = message
      .Attachments
      .Cast<FileAttachment>()
      .Single(attachment => attachment.Name.EndsWith(".pdf"));

      if (PageCount(pdfAttachment) == 1)
      {
      SaveToEmaDirectory(GenerateFilePath(pdfAttachment), UnEditableVersionOf(pdfAttachment.Content));

      processed.Add(message);
      }

      else rejected.Add(message);
      }

      MoveMailToFolder(Statics.Rejected, rejected);
      MoveMailToFolder(Statics.Processed, processed);
      }
      }

      public void MoveMultiplePagePdfToFolder()
      {
      var messagesWithMultiplePdf = GetMailWithMultiplePdf();

      var processed = new List<MailMessage>();
      var rejected = new List<MailMessage>();

      if (messagesWithMultiplePdf?.Count > 0)
      {
      foreach (var message in messagesWithMultiplePdf)
      {
      _service.GetAttachments(
      message.Attachments.ToArray(),
      BodyType.HTML,
      null);

      var pdfAttachmentList = message
      .Attachments
      .Cast<FileAttachment>()
      .Where(attachment => attachment.Name.EndsWith(".pdf"));

      bool isMessageOk = true;

      foreach (var pdfAttachment in pdfAttachmentList)
      {
      if (PageCount(pdfAttachment) != 1)
      /*SaveToEmaDirectory(GenerateFilePath(pdfAttachment),
      UnEditableVersionOf(pdfAttachment.Content))*/;
      isMessageOk = false;
      }

      if(isMessageOk)
      processed.Add(message);

      else rejected.Add(message);
      }

      MoveMailToFolder(Statics.Rejected, rejected);
      MoveMailToFolder(Statics.Processed, processed);
      }
      }
      }


      The two methods MoveMultiplePagePdfToFolder and MoveSinglePagePdfToFolder are nearly same. MoveSinglePagePdfToFolder contains all email messages with single pdf as attachments and if the number of pages in pdf is 1, then it sends to Processed folder else Rejected.



      MoveMultiplePagePdfToFolder checks multiple pdf attachments in message and if all of them contain single page then it moves the message to Processed otherwise Rejected.



      Hope it helps.









      share







      New contributor




      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      Need some help in code refactoring as there is lot of duplicated code:



      public class Client
      {
      private List<MailMessage> _mailMessages;

      /// <summary>
      /// This method checks if a pdf file is editable.
      /// </summary>
      /// <param name="fileContents"></param>
      /// <returns>true (if editable) or false (if not editable)</returns>
      private bool IsEditablePdf(byte fileContents)
      {
      var pdfReader = new PdfReader(fileContents);

      if (pdfReader.AcroForm == null)
      return false;

      return true;
      }

      /// <summary>
      /// This method converts an editable pdf to uneditable pdf.
      /// </summary>
      /// <param name="fileContents"></param>
      /// <returns></returns>
      private byte GetUnEditablePdf(byte fileContents)
      {
      byte uneditableFileContents;

      var reader = new PdfReader(fileContents);

      if (reader.AcroForm != null)
      uneditableFileContents = FlattenPdfFormToBytes(reader);

      else uneditableFileContents = fileContents;

      return uneditableFileContents;
      }

      private List<MailMessage> GetMailWithSinglePdf()
      {
      var mailMessagesWithSinglePdf = new List<MailMessage>();

      //load items from mailbox inbox folder
      if (_mailMessages != null)
      {
      foreach (var message in _mailMessages)
      {
      var pdfCount = message.Attachments
      .Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

      // list of attachments contain one pdf
      if (pdfCount == 1)
      mailMessagesWithSinglePdf.Add(message);
      }
      }

      return mailMessagesWithSinglePdf;
      }

      private List<MailMessage> GetMailWithMultiplePdf()
      {
      var mailMessagesWithMultiplePdf = new List<MailMessage>();

      //load items from mailbox inbox folder
      if (_mailMessages != null)
      {
      foreach (var message in _mailMessages)
      {
      var pdfCount = message.Attachments
      .Where(z => z is FileAttachment).Count(p => p.Name.EndsWith(".pdf"));

      // list of attachments contain one pdf
      if (pdfCount > 1)
      mailMessagesWithMultiplePdf.Add(message);
      }
      }

      return mailMessagesWithMultiplePdf;
      }

      private int PageCount(FileAttachment pdfAttachment)
      {
      using (var reader = new PdfReader(pdfAttachment.Content))
      return reader.NumberOfPages;
      }

      private void SaveToEmaDirectory(string filePath, byte fileContent)
      {
      File.WriteAllBytes(filePath, fileContent);
      }

      private string GenerateFilePath(FileAttachment singlePagePdf)
      {
      if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

      return Path.Combine(
      Statics.EmaFileWatcherWorkingDirectory,
      GenerateFileName(singlePagePdf));
      }

      private string GenerateFileName(FileAttachment singlePagePdf)
      {
      if (singlePagePdf == null) throw new ArgumentNullException(nameof(singlePagePdf));

      return string.Join("_",
      "fax",
      DateTime.Now.Date.ToString("ddMMyy"),
      singlePagePdf.Name,
      DateTime.Now.Ticks + ".pdf");
      }

      private byte UnEditableVersionOf(byte pdfContent)
      {
      if (pdfContent == null) throw new ArgumentNullException(nameof(pdfContent));

      return IsEditablePdf(pdfContent)
      ? GetUnEditablePdf(pdfContent)
      : pdfContent;
      }

      /// <summary>
      /// Moves this item to a the specified folder. Calling this method results in a call to EWS.
      /// </summary>
      /// <param name="destinationFolderName"></param>
      /// <param name="messages"></param>
      public void MoveMailToFolder(string destinationFolderName, List<MailMessage> messages)
      {
      if (string.IsNullOrWhiteSpace(destinationFolderName))
      throw new MessageException("Invalid folder name");

      if (messages != null && (messages.Any()))
      {
      var fId = GetFolderId(destinationFolderName);
      var results = WorkingFolder.FindItems(new ItemView(100));

      if (results?.Items?.Count > 0)
      foreach (var item in results.Items)
      {
      if (item is EmailMessage)
      {
      item.Load();

      var mailMessage = new MailMessage();
      mailMessage.Id = item.Id.ToString();

      if (messages.Contains(mailMessage))
      item.Move(fId);
      }
      }
      }
      }

      public void MoveSinglePagePdfToFolder()
      {
      var messagesWithSinglePdf = GetMailWithSinglePdf();

      var processed = new List<MailMessage>();
      var rejected = new List<MailMessage>();

      if (messagesWithSinglePdf?.Count > 0)
      {
      foreach (var message in messagesWithSinglePdf)
      {
      _service.GetAttachments(
      message.Attachments.ToArray(),
      BodyType.HTML,
      null);

      var pdfAttachment = message
      .Attachments
      .Cast<FileAttachment>()
      .Single(attachment => attachment.Name.EndsWith(".pdf"));

      if (PageCount(pdfAttachment) == 1)
      {
      SaveToEmaDirectory(GenerateFilePath(pdfAttachment), UnEditableVersionOf(pdfAttachment.Content));

      processed.Add(message);
      }

      else rejected.Add(message);
      }

      MoveMailToFolder(Statics.Rejected, rejected);
      MoveMailToFolder(Statics.Processed, processed);
      }
      }

      public void MoveMultiplePagePdfToFolder()
      {
      var messagesWithMultiplePdf = GetMailWithMultiplePdf();

      var processed = new List<MailMessage>();
      var rejected = new List<MailMessage>();

      if (messagesWithMultiplePdf?.Count > 0)
      {
      foreach (var message in messagesWithMultiplePdf)
      {
      _service.GetAttachments(
      message.Attachments.ToArray(),
      BodyType.HTML,
      null);

      var pdfAttachmentList = message
      .Attachments
      .Cast<FileAttachment>()
      .Where(attachment => attachment.Name.EndsWith(".pdf"));

      bool isMessageOk = true;

      foreach (var pdfAttachment in pdfAttachmentList)
      {
      if (PageCount(pdfAttachment) != 1)
      /*SaveToEmaDirectory(GenerateFilePath(pdfAttachment),
      UnEditableVersionOf(pdfAttachment.Content))*/;
      isMessageOk = false;
      }

      if(isMessageOk)
      processed.Add(message);

      else rejected.Add(message);
      }

      MoveMailToFolder(Statics.Rejected, rejected);
      MoveMailToFolder(Statics.Processed, processed);
      }
      }
      }


      The two methods MoveMultiplePagePdfToFolder and MoveSinglePagePdfToFolder are nearly same. MoveSinglePagePdfToFolder contains all email messages with single pdf as attachments and if the number of pages in pdf is 1, then it sends to Processed folder else Rejected.



      MoveMultiplePagePdfToFolder checks multiple pdf attachments in message and if all of them contain single page then it moves the message to Processed otherwise Rejected.



      Hope it helps.







      c# asp.net





      share







      New contributor




      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 6 mins ago









      Gauravsa

      1014




      1014




      New contributor




      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Gauravsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Gauravsa is a new contributor. Be nice, and check out our Code of Conduct.










           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208209%2fcode-refactoring-dry-c%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Gauravsa is a new contributor. Be nice, and check out our Code of Conduct.










           

          draft saved


          draft discarded


















          Gauravsa is a new contributor. Be nice, and check out our Code of Conduct.













          Gauravsa is a new contributor. Be nice, and check out our Code of Conduct.












          Gauravsa is a new contributor. Be nice, and check out our Code of Conduct.















           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208209%2fcode-refactoring-dry-c%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'