Check email count on mailbox with C#

Below is an example of .Net core 3.1 Console App that is reading a mailbox on Exchange and checking the count of mails. If the mail count cross a certain threshold, it’ll check for an e-mail older than 2 hours to send an alert.

Such an example can be used to schedule alerts or log information if you’re tracking mails in a mailbox.

Install Nuget package Microsoft.Exchange.WebServices to use ExchangeService class.

using Microsoft.Exchange.WebServices.Data;

public static void Main(string[] args)
	string TextlogMessage;
	string Subject = "";
	string sUsername = ConfigurationManager.AppSettings.Get("UserName");
	var section = ConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
	string vCount = ConfigurationManager.AppSettings.Get("Count");
	int Count = Convert.ToInt32(vCount);
	string sPassword = ConfigurationManager.AppSettings.Get("Password");
	string sDomain = ConfigurationManager.AppSettings.Get("Domain");
	TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
	DateTime indianTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);
	DateTime comparedate = indianTime.AddHours(-2);
	DateTime MailDateTime = comparedate;
	ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
	exchange.Credentials = new WebCredentials(sUsername, sPassword, sDomain);
	exchange.Url = new Uri(ConfigurationManager.AppSettings.Get("ExchangeUrl"));
	Folder inbox = Folder.Bind(exchange, WellKnownFolderName.Inbox);
	var oSendemail = 0;
	TextlogMessage = "Start With count:" + inbox.TotalCount;

	if (inbox.TotalCount > Count)

		Console.WriteLine("Count " + inbox.TotalCount);

		ItemView view = new ItemView(1);

		view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
		var findResults = exchange.FindItems(WellKnownFolderName.Inbox, view);

		foreach (Item item in findResults.Items)

			Console.WriteLine("Test: " + item.DateTimeReceived + " %" + comparedate);
			DateTime newdate = TimeZoneInfo.ConvertTimeToUtc(item.DateTimeReceived);

			int Dresult = DateTime.Compare(newdate, comparedate);
			if (Dresult < 0)
				Console.WriteLine("Alert " + "Sub" + item.Subject + newdate + " %" + comparedate);
				oSendemail = 1;
				MailDateTime = newdate;
				Subject = item.Subject;


		if (oSendemail > 0)
			Program p = new Program();
			//To Do Send Email Logic..
			p.SendEmail(exchange, oSendemail, inbox.TotalCount, TextlogMessage);
			TextlogMessage = TextlogMessage + " EmailTime: " + MailDateTime + "CompareTime " + comparedate + "  Alert Sent Subject : " + Subject;



	//To Do logging..


Download word file without Protected View .Net ReactJS

I have an Intranet Application where a .docm template downloaded from a ReactJS UI as a blob is opening in Protected View on the users’ machines. This is happening when downloading in browsers other than IE or Edge browser in IE mode.

When you download the document from Chrome or other browsers, MS Word is considering it as an Internet Application. Hence, the checkbox for Protected View is applying these changes and downloading it in Protected View.

Enable Protected View For Files Originating From The Internet. This setting controls documents opened from a website.

The code to download this as a blob is in ReactJS is available here.

However, if you generate the .docm file on the Server where the API is located and put it in a location on the Server itself. Create a Virtual Directory in IIS to make the document downloadable as http. So just return the hyperlink at the Client-side Javascript. You can receive this hyperlink and assign to anchor link clicking it through code.

var downloadUrl =;
        const link = document.createElement("a"); = "DownloadLink";
        link.href = downloadUrl;
        link.setAttribute("download", "filename");
        document.getElementById("DownloadLink").outerHTML = "";

This will prevent it from opening in Protected View.

Also, if your word file has Macros, read-only fields become editable when you click on “Enable Editing” when you open the document in Protected View until you enable the Macros.

TELNET to test connection to POP3/IMAP

First, make sure TELNET is installed on your machine else you’ll get error. You can install TELNET through Add or Remove feature on Windows.
You can use TELNET via a command prompt to confirm.

For IMAP check port 143 and if using SSL then check port 993.

For POP3 check port 110 and if using SSL then check port 995.

Test POP3 connection:

  • Start a command prompt
  • Enter TELNET {webserver} port e.g. TELNET exchangesrvr01 995
  • Enter USER {login} e.g. USER
  • Enter PASS {password} e.g. PASS secret
  • Enter LIST to show the mailbox
  • Enter QUIT to Exit

At each stage you should receive an OK message. If there is an issue at any stage you will receive an error

Test IMAP connection:

  • Start a command prompt
  • Enter TELNET {webserver} port e.g. TELNET exchangesrvr01 143
  • Enter . LOGIN {login} {password} e.g. LOGIN secret
  • Enter . LIST “” “*” to show the mailbox
  • Press CTRL + ] and then QUIT to Exit

At each stage you should receive an OK message. If there is an issue at any stage you will receive an error.

Register and unregister COM component using regsvr32 command

You’ll need to open Command Prompt in Admin mode to make the changes especially when User Account Control (UAC) is enabled on your Windows 10 machine. CD to system32 for 64-bit registration and SysWoW64 for 32-bit registration.
Place the COM component in the folder from you want to register and also your executable is placed e.g. “C:\TFS\Code\bin\” in the example below.

To register use the below command:

regsvr32 "C:\TFS\Code\bin\MailObj.dll"

To unregister use the below command:

regsvr32 /u "C:\TFS\Code\bin\MailObj.dll"

You should get a prompt that the register/unregister command succeeded.
This command can be used to register/unregister DLL or OCX files.

Set Project Build Order in Visual Studio

In order to set the Build order for your Solution, right-click on the Solution in Solution Explorer and Select Project Build Order:

Your Project Dependencies should be set correctly which is used to determine the Build order by Visual Studio.

The image below shows the Project references added in the Business layer to determine that the DTO and Persistence Projects should be built first before the Business layer Project.

The Project Build order will make sure the required dlls are available for the Api to compile correctly.

Now give your car batteries a good re-conditioning they need. Click here to know more.

Join Armoney for best Cryptocurrency trading experience. Trade from anywhere, anytime!

Use Robocopy to copy files on Windows Server

Robocopy is a robust file copy command for the Windows command line. It allows users to copy files, directories, and even drives from one location to another. It can be automated with Task Scheduler to run at specific times.

Robocopy example to copy a file from Source to Destination:


Robocopy [Src] [Dest] [filename] [options]

Src: Can be local or UNC path

Dest: Can be local or UNC path

Code Sample batch file:

SET DTVARYEAR=%Date:~10,4%

echo Sync Started

Robocopy C:\Data\TestFolder C:\Data\Logs\TestFolder\%DTVARYEAR%-%DTVARMONTH%-%DTVARDATE%_TestFolder testlogfile.log /FFT /Z /XA:H /LOG+:C:\Data\SchedTasks\LogsTest\%DTVARYEAR%-%DTVARMONTH%_AppLogs.txt 

echo  Log synced

The above code will copy the testlogfile.log from Source to Destination.

/FFT Assumes FAT file times (two-second precision).
/Z Copies files in restartable mode.
/XA:H exclude hidden file
/LOG+ log output to file and append.

Additional useful options:
/MIR Mirrors a directory tree (equivalent to /e plus /purge).
/XF exclude specified file
/XD exclude specified directory

Move files based on Date Time using PowerShell

This post shows how we can use PowerShell to move files from one folder to another say while Archiving the files.

$SrcFolder = "C:\Files"
$DestFolder = "C:\Backup\2017"
$count = 0

 if(-not (Test-Path $DestFolder)){
        New-Item -Path $DestFolder -ItemType Directory
    Write-Host $DestFolder "Path exists"

 Get-ChildItem -Path $SrcFolder | Where-Object {$_.LastWriteTime -lt (Get-Date).AddMonths(-13)} | ForEach-Object {
    Write-Host "Moving: " $SrcFolder"\"$_ $_.LastWriteTime to $DestFolder
    Move-Item -Path $SrcFolder"\"$_ -Destination $DestFolder
    $count = $count + 1

 Write-Host "Moved" $count "items."

The above code takes each item found in the Source Folder and checks LastWriteTime say for 13 months earlier, and moves the file to the Destination folder.

The command used to Move the files is Move-Item which takes -Path and -Destination as parameters.

We have the following tasks that requires to be done on a Windows Server 2012 R2 for this example using PowerShell:

  1. Archive Files from a Source Folder to Destination Folder (could be a Shared folder on the Network) based on time-stamp, only for files older than 2 years in this example.
  2. It takes 2 parameters, Year parameter is mandatory. Destination Folder is optional. Both Source and Destination are however hard-coded into the script.
  3. The script creates a folder with Year as folder-name at the Destination and Archive all the files for that year in the created folder.
  4. A log file is created in the same path on which the script is running under the Logs folder. All Archiving activity including any errors faced for any files are logged.
  5. The progress of the Archiving Files is also shown in the Console.
  6. Errors are handled like no files or folder found for the Year Parameter.
  7. The user running the script has to be an Administrator on the Machine. The Script has to be running in the Admin Mode.

Add-Type -AssemblyName System.Windows.Forms

$SourceFolder = "C:\TestSource"

if ($Year -gt $Date) 
     [System.Windows.Forms.MessageBox]::Show("Only Process the documents before Year $Date")

if($DestinationFolder -eq "")
  $DestinationFolder = "\\TestDestinationFolder"

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
[System.Windows.Forms.MessageBox]::Show("Please run powershell application as administator")

$DirectoryChain=(Get-ChildItem -Path $SourceFolder -Recurse)
$DirectoryChain |
ForEach-Object {

$FileYear = (Get-Date($_.LastWriteTime)).Year

      if($FileYear -eq $Year){

        ########Creating Log File############
        if(!(Test-Path -Path ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt"))
           Write-Host "Starting Data Archiving Process for $Year" -BackgroundColor Green        
           New-Item -Path ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt" -ItemType File -Value "Archival Process Started at $(Get-Date)
            if(!(Test-Path -Path ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt")){[System.Windows.Forms.MessageBox]::Show("Log File could not created and exiting script")
         try {

           if(Test-Path -Path "$DestinationFolder\$FileYear")
               Move-Item -LiteralPath $_.FullName -Destination "$DestinationFolder\$FileYear" -ErrorAction Ignore
               "Moved '$_' to $DestinationFolder\$FileYear successfully at $(Get-Date)" | add-content ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt"
               New-Item -Path "$DestinationFolder\$FileYear" -ItemType Directory -ErrorAction Ignore
               Move-Item -LiteralPath $_.FullName -Destination "$DestinationFolder\$FileYear"
               "Moved '$_' to $DestinationFolder\$FileYear successfully at $(Get-Date)" | add-content ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt"

           Write-Progress -Activity "Archival Document Process" -Status "Archiving Document $_  $i" -PercentComplete $PercentageStat
           #Start-Sleep -Seconds 2

             "Error in moving object $_.FullName" | add-content ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt"


######Checking for existence of log file and appending comment in log file"########
if(Test-Path -Path ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt")
Archival Processs Finished at $(Get-date)" | add-content ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt"

Write-Host "Data Archiving Process Finished, Total files/folders Archived $i" -BackgroundColor Green

Write-Host "Archival Processs Finished at $(Get-date), Please check the log file Archive $(($time).ToString("MM-dd-yyyy HH-MM")).Txt on Location $(Get-Item -Path ".\")" -BackgroundColor Green -ForegroundColor Blue

If(!(Test-Path -Path ".\Logs"))
      New-Item -Path .\ -ItemType Directory -Name "Logs"
      Move-Item -Path ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt" -Destination ".\Logs"
      Write-Host "Log File .\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt has been moved to $(Get-Item -Path ".\Logs")" -BackgroundColor Green -ForegroundColor White 
      Move-Item -Path ".\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt" -Destination ".\Logs"
      Write-Host "Log File .\Archive $(($time).ToString("MM-dd-yyyy hh-mm tt")).Txt has been moved to $(Get-Item -Path ".\Logs")" -BackgroundColor Green -ForegroundColor White 

Write-Host "No files or folder found for $Year" -BackgroundColor Green -ForegroundColor White

The script can be run in PowerShell Console Admin mode as below:

./Archive_files.ps1 -Year 2016

Optional Parameter $Destination Folder can be ignored as it is hard-coded in the script. You can pass it if the Destination folder is different.

Modify config files using PowerShell

Suppose you need to hide the password in your clear text connection strings at a particular back-up path or any other path in config files. This can be achieved using PowerShell with the following code.

$configFiles = Get-ChildItem "C:\Path\Backup" *.config -rec
foreach ($file in $configFiles)
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "pwd=(\w+);", "pwd=****;" } |
    Set-Content $file.PSPath

Write-Verbose "Password changed!"

The above script will replace the string “pwd=(\w+);” with “pwd=****;” in the *.config files matching the regular expression.

I’m using the following parameters for the Get-ChildItem command:

-Path “C:\Path\Backup” 

-Include *.config for including config files

-rec for Recursion to get items in all child containers

Enable disable Windows Service and Scheduled Tasks with PowerShell

Often we may need to enable/disable Windows Services and Scheduled tasks on a Windows Server.

Below is the snippet to Enable Windows Service and Scheduled task with PowerShell:

$tasknames = "Test Task1","Test task2" $servicename = "Test Service1","Test Service2" foreach($task in $tasknames) {  ##disabling tasks on server  $taskstatus = Get-ScheduledTask -TaskName $task  if($taskstatus.State -eq "Disabled")   {    Enable-ScheduledTask -TaskName $task -Verbose   }   elseif($taskstatus.State -eq "Ready")   {   Write-Host "Task: $task already running"   }      } ##### Service checks and execution  foreach($service in $servicename)  {  $servicestatus = Get-Service $service  if($servicestatus.Status -eq "Stopped")   {    Start-Service $service  -Verbose    }    elseif($servicestatus.Status -eq "Started")    {    Write-host "Service: $service already Started"    }   } 

The below snippet shows how to disable the Scheduled tasks and Windows Service:

$tasknames = "Test Task1","Test task2" $servicename = "Test Service1","Test Service2" foreach($task in $tasknames) {  ##disabling tasks on server  $taskstatus = Get-ScheduledTask -TaskName $task  if($taskstatus.State -eq "Ready")   {    Disable-ScheduledTask -TaskName $task -Verbose   }   elseif($taskstatus.State -eq "Disabled")   {   Write-Host "Task: $task already disabled"   }      } ##### Service checks and execution  foreach($service in $servicename)  {  $servicestatus = Get-Service $service  if($servicestatus.Status -eq "Running")   {    Stop-Service $service -Force -Verbose    }    elseif($servicestatus.Status -eq "Stopped")    {    Write-host "Service: $service already stopped"    }   }  

You can save the above scripts in .ps1 format for PowerShell and call them e.g. using a .bat file.

Good old dir and copy commands

This is a true troubleshooting story!

Today, one of the users of my application wanted to know if we can find out the original title of a ticket created in the Application. Although, we do not store any such logs for modifications, while on the verge of giving up, I remembered we archive the e-mails received by the Windows Service application that processes the e-mails and archives them at a location on the Server on which it is installed. The e-mail Subject line is stored as the ticket title. These tickets which are created by the Windows Service can be viewed in the Web Application.

Since the folder with the archiving e-mails have a lot of ’em, simply doing a Windows Search is a time killer! So I remembered my way through the good old DOS commands.

Since the .eml file has the ticket number, I used the dir command to search for the e-mail name and copy command to copy it to another location quickly.

Firstly cd to the location where the archived e-mails are stored on the Server:

So e.g. if the ticket number is 123456

dir *123456* /s

The /s searches for the File name inside the two wildcard characters asterisk “*” with the dir command.

Then if the file name is e.g. TICKET123456 – abc.eml then use copy command as follows within the same directory:

copy "TICKET123456 - abc.eml" c:\Temp

So, with the e-mail having the original Subject Line preserved, I could share the original ticket title.