Tuesday, December 29, 2020

Apple Phishing Email - Re: [Ticket #:xxxxx] M‌or‌e Inf‌o‌rma‌t‌i‌on Update Requ‌i‌red‌

For the record, the Apple Phishing email is going around with subject Re: [Ticket #:xxxxx] M‌or‌e Inf‌o‌rma‌t‌i‌on Update Requ‌i‌red‌


What to do?  Report them, goto bottom of page.



From : i‌C‌l‌ou‌d ‌‌I‌‌D <securityaccount.xxxx@za1h5xrgprmsb.com>

Subject :  Re: [Ticket #:xxxxx] M‌or‌e Inf‌o‌rma‌t‌i‌on Update Requ‌i‌red‌

‌‌‌A‌c‌c‌o‌u‌n‌t l‌o‌c‌k‌e‌d notifi‌‌‌cation





Phishing Links

  1. https://gladysstore.us7.list-manage.com/track/click?u=xxx&id=xxx&e=xxxx

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.

  3. The best way is to look at message source, see below.

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing URLs at Google now 

If you have recievied this email take further action now by click these links

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Report Phishing Email To Apple

  1. After writing and reporting these phishing attempts to Apple (abuse@icloud.com), they just blocked my email address after 5 such notifications. Sham on Apple, denial is not a strategy. Just like your products don't need antivirus, what a joke. Be aware folks. 


Wednesday, December 23, 2020

DOS Command Line - Timethis.exe is a Microsoft utility that times how long a command runs

Timethis.exe - Windows 2000 Resource Kit Utility

Utility  Description
 
Timethis.exe - Time This  

Time This times how long it takes the system to run a given command. You provide as a parameter the name of the command you want to run and time. Time This runs the specified command, then reports the start and finish time for the command, and how long it took to run, in HH:MM:SS.TTT format.


Windows 2000 Resource Kit Utility is no longer available for download, but you can get it at wayback machine (internet archive)

http://web.archive.org/web/20031218225021/http://download.microsoft.com:80/download/win2000platform/timethis/1.00.0.1/NT5/EN-US/timethis_setup.exe

The installer did not work for me, but you can get the timethis.exe by unzip the file successively.

...\timethis_setup\timethis\compmgmt\TIMETHIS.EXE

copy to C:\windows

Usage: 

c:\> timethis dir

Output:

C:>timethis dir
...
TimeThis :  Command Line :  dir
TimeThis :    Start Time :  Wed Dec 23 12:29:38 2020
TimeThis :      End Time :  Wed Dec 23 12:29:39 2020
TimeThis :  Elapsed Time :  00:00:00.077

Sunday, December 20, 2020

C# .NET The most common flaw type in .NET applications was information leakage

Information leakage was most common flaw type for .NET. To review, Information Leakage is a type of security flaw that can allow malicious user s to reveal confidential information from within an application.

Here's a primer - Information Leakage Tutorial (veracode.com).





















Source of image, full PDF - state-of-software-security-volume-11-flaw-frequency-by-language.pdf (veracode.com)

Thursday, December 17, 2020

Walmart Phishing Email with subject Answer and Win

 For the record, this is an Walmart phishing email attempt that is recently going around, with subject "Re: Answer & Win


What to do?  Report them, goto bottom of page. 


From : Playstation5 <zulily62@e.zulily.com>
Subject : 
Re: Answer & Win




PHISHING LINKs;

1. Hover over image
https://storage.googleapis.com/sdffsdfsd/clickply.html

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.
  3. The best way is to 

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing

If you have received this email take further 

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Wednesday, December 16, 2020

Amazon phishing email with subject Re: Invoice Payment Transaction : RenewaI Prime Membership was canceIed - Your payment scheduIed renew on

For the record, this is an Amazon phishing email attempt that is recently going around, with subject "Re: Notification from Am‍a‍zon: Your account is on hold due unusual login was found on your activity - Action is required to continue shopping with Am‍a‍zon

What to do?  Report them, goto bottom of page. 


From : Amazon Prime <donoreplyxxxxxxxxxxx@panganturumaning.com>
Subject : 
Re: Invoice Payment Transaction : Renewal Prime Membership was canceled - Your payment scheduled renew on {Today's Date}



PHISHING LINKs;



How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.
  3. The best way is to 

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing

If you have recievied this email take further 

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Thursday, December 3, 2020

How to fix Outlook desktop app account problems with Outlook.com or Hotmail.com blocked, stopped, not working, authentication problems

Recently, my Outlook desktop app client started to have authentication problems for my hotmail.com / outlook.com emails and I though initial it was due to outdated setting see below. But it was not, that was not the cause of the problem. 

Update Thu 11-Feb-21 9:00pm - MetadataConsulting.ca: How to check Outlook desktop app account connection problems with Outlook.com or Hotmail.com blocked, stopped, not working, authentication problems

Seems using my Kasperky VPN has cause spam and fraud rules to triggered on Microsoft mail servers. So any IP address using this service are blocked.

MAIL FROM from SMTP Server : 550 5.7.1 Unfortunately, messages from [xxx.xxx.xxx.xxx] weren't sent. 
Please contact your Internet service provider since part of their network is on our block list (S3150). 
You can also refer your provider to http://mail.live.com/mail/troubleshooting.aspx#errors. 
[BN7NAM10FT050.eop-nam10.prod.protection.outlook.com]

(I wish they had a application level authentication token that would get around this.)

However, if you are connecting from different countries or IP addresses (if you are a mobile worker for example) you will like trigger the following warning.

outlook.office365.com is complaining of suspicious activity and has temporarily blocked access.  

Solution: Login into hotmail.com or outlook.com email via your browser and then your Outlook desktop client will work. 


Double check these new server settings as well. 

There are new server settings, and available here for reference :  https://support.microsoft.com/en-us/office/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

New server settings

Outlook.com

Hotmail.com

Live.com

IMAP Server: outlook.office365.com

Port: 993

Encryption: SSL/TLS

POP Server: outlook.office365.com

Port: 995

Encryption: SSL/TLS

SMTP Server: smtp.office365.com

Port: 587

Encryption: STARTTLS

Goto E-mail accounts and edit your existing connection to use the above setting, below is for POP/SMTP settings. Change to new setting in above table


Use TLS, if you cannot choose both under "More settings....."



Monday, November 30, 2020

How to import a config file into CoreFTP

Here's how to import a config file (.coreftp) that you download from CPanel into CoreFTP, the somehow preferred FTP client in CPanel. You think this would be part of the help file????

There is no function to import of the top level, most logically the File menu ? You have open the Site Manage located under top level Sites menu. In Site Manager windows, right-click into blank area (saved sites window) to reveal import capability. 

Personally, I find CoreFTP the worst ftp client, very un-intuitive design and ridiculously small fonts.




Friday, November 20, 2020

Am‍a‍zon Phishing email with subject Re: Notification from Am‍a‍zon: Your account is on hold due unusual login was found on your activity - Action is required to continue shopping with Am‍a‍zon

For the record, this is an Amazon phishing email attempt that is recently going around, with subject "Re: Notification from Am‍a‍zon: Your account is on hold due unusual login was found on your activity - Action is required to continue shopping with Am‍a‍zon

What to do?  Report them, goto bottom of page. 


From : Amazon <xxxxxxxxxxb@toko-ew.store>
Subject : 
Re: Notification from Am‍a‍zon: Your account is on hold due unusual login was found on your activity - Action is required to continue shopping with Am‍a‍zon









PHISHING LINKs;

1. Hover over image
http://xaelvz.qewoahzkz.pqtimakzds.com/xxxxx

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.
  3. The best way is to 

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing

If you have recievied this email take further 

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Wednesday, November 18, 2020

Outlook desktop app account settings for Hotmail.com broken and have been updated

As of  November 17, 2020 my Outlook desktop app client started to have authentication problems for my hotmail.com / outlook.com emails and I though initial it was due to outdated setting see below. But that was not it.

Seems my VPN is randomly choosing countries on start-up to pass thru even though I selected Canada only by default. However, if you are connecting from different countries or IP addresses (if you are a mobile worker for example) you will like trigger the following warning.

Update 11-Feb-21 - How to check Outlook desktop app account connection problems with Outlook.com or Hotmail.com blocked, stopped, not working, authentication problems


outlook.office365.com is complaining of suspicious activity and has temporarily blocked access.  


Solution : Login into outlook.com with hotmail.com or outlook.com through your browser into your account will work in your Outlook client. 


Double check these new server settings as well. 

There are new server settings, and available here for reference :  https://support.microsoft.com/en-us/office/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

New server settings

Outlook.com

Hotmail.com

Live.com

IMAP Server: outlook.office365.com

Port: 993

Encryption: SSL/TLS

POP Server: outlook.office365.com

Port: 995

Encryption: SSL/TLS

SMTP Server: smtp.office365.com

Port: 587

Encryption: STARTTLS

Goto E-mail accounts and edit your existing connection to use the above setting, below is for POP/SMTP settings. Change to new setting in above table


Use TLS, if you cannot choose both under "More settings....."



C# .NET How to get the literal .NET string, the internal storage representation of a C# string

From my last post we were dealing with the are gotcha's introduced when processing null character ('\0') which you might incorrectly deduce is a white-space character.

But in fact, in C# '\u0000' is a null character, but has no special meaning in C#. It just a null character in a string. It is considered not white-space but a control character. It's not considered a null either or string terminator as it is in C. To view control characters in VS Code, see my blog post and in Notepad++ see post.

In fact, you can look a the .NET internal storage of a string using the following code, and it rather expensive and slow to do. But in case you need it, especially when dealing with registry values that are riddled with '\0' you need it. 

  
Source Code

using System;
using System.Diagnostics;
using System.IO; 
using System.CodeDom;
using System.CodeDom.Compiler; 
					
public static class Program
{
	public static string ToLiteral(this string input)
	{
		using (var writer = new StringWriter())
		{
			using (var provider = CodeDomProvider.CreateProvider("CSharp"))
			{
				provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);

				return writer.ToString();
			}
		}
	}

	public static void Main()
	{
		 Stopwatch sw = new Stopwatch();

            string emptytest = "1 \0 \0 \u0001 \0 \0\r\n\tSOS\n1 0 0 1 0 0 1\r\nIn distress\r\n1 0 0 1 0 0 1\r\nUnicode \\u0081 on the next line\n\n\u0081";
            sw.Start();
            string output = emptytest.ToLiteral(); 
            sw.Stop();
		
        Console.WriteLine(emptytest);    
		Console.WriteLine("---- Literal -----");    
		Console.WriteLine(output + " in " + sw.ElapsedTicks + " ticks");

	}
}

When do you use it, leave a comment below.

Monday, November 16, 2020

C# .NET How to remove blank lines from a string faster, dealing with null '\0' character confusion

Typically, in C# code you would use a 

str.Split(TrimNewLineChars, StringSplitOptions.RemoveEmptyEntries);

to remove empty white-space lines and is effective. But a faster way is to use StringReader and process each line. 

But there are gotcha's introduced when processing null character ('\0') which you might deduce from the above to be a white-space character. But in fact, in C# '\u0000' is a null character, but has no special meaning in C#. It just a null character in a string. It is considered
not white-space but a control character. It's not considered a null either or string terminator as it is in C. To view control characters in VS Code, see my blog post and in Notepad++ see post.

In fact, you can look a the .NET internal storage of a string using, see my next post on this.

using (var writer = new StringWriter())
{
    using (var provider = CodeDomProvider.CreateProvider("CSharp"))
    {
        provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);

        return writer.ToString();
    }
}

Lesson Learning :

Counter-intuitively 
StringSplitOptions.RemoveEmptyEntries considers null character ('\0') whitespace, not a control character.




Source Code

using System;
using System.Text; 
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
					
    public static class Program
    {

        public static string RemoveAllWhitespace(this string str)
        {
            var len = str.Length;
            var src = str.ToCharArray();
            var dstIdx = 0;
            for (var i = 0; i < len; i++)
            {
                char ch = src[i];
                if (!char.IsWhiteSpace(ch) && ch != '\0')
                    //ch!='\0')
                    src[dstIdx++] = ch;
                     
            }
            return new string(src, 0, dstIdx);
        }


        public static string TrimStartUnicode(this string str)
        {
            var len = str.Length;
            var src = str.ToCharArray();
            var dstIdx = 0;
            for (var i = 0; i < len; i++)
            {
                char ch = src[i];
                if (!char.IsWhiteSpace(ch) && !char.IsControl(ch) ) 
                {
                    src[dstIdx++] = ch;
                    break;
                }
            }
            return new string(src, 0, dstIdx);
        }

        private static readonly char[] TrimNewLineChars = Environment.NewLine.ToCharArray();
        public static string RemoveEmptyLines(this string str)
        {
            if (str == null)
            {
                return null;
            }
            var lines = str.Split(TrimNewLineChars, StringSplitOptions.RemoveEmptyEntries);

            var sb = new StringBuilder(str.Length);
            foreach (var line in lines)
            {
                if (!String.IsNullOrWhiteSpace(line))
                    sb.AppendLine(line);
            }

            return sb.ToString();
        }

        //Tue 12-May-20 2:08am  - 
        public static String RemoveAllBlankLinesIssue(this string value)
        {

            StringBuilder output = new StringBuilder(value.Length);
            using (StringReader sr = new StringReader(value))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
					//\0 has no special meaning in c# it's just a null character contained in a string.
                    if (line == '\0'.ToString()) //is line length of 1
                    {

                        Console.WriteLine("is char '\\0' empty or null = " + string.IsNullOrEmpty("\0").ToString());
                        Console.WriteLine("is char '\\0' whitespace or null = " + String.IsNullOrWhiteSpace("\0").ToString());

                    }
                    if (line.Contains('\u0080'.ToString()))
                    {
                        Console.WriteLine("is char '\\0080' empty or null = " + string.IsNullOrEmpty("\u0080").ToString());
                        Console.WriteLine("is char '\\0080' whitespace or null = " + String.IsNullOrWhiteSpace("\u0080").ToString());

                    }

                    if (!String.IsNullOrWhiteSpace(line) && !string.IsNullOrEmpty(line))
                        output.AppendLine(line);
                }

            }
            return output.ToString();
        }

        //Tue 12-May-20 2:08am  - 
        public static String RemoveAllBlankLinesFinal(this string value)
        {
                         
            StringBuilder output = new StringBuilder(value.Length);
            using (StringReader sr = new StringReader(value))
            {
                string line;
                string temp; 
                while ((line = sr.ReadLine()) != null)
                {
                    temp = line.TrimStartUnicode();  
                    
                    if (!string.IsNullOrWhiteSpace(temp) && !string.IsNullOrEmpty(temp))
                        output.AppendLine(line);
                }

            }
            return output.ToString();
        }



        public static String RemoveAllBlankLinesRegex(this string s)
        {
            return Regex.Replace(s, @"^\s+$[\r\n]*", string.Empty, RegexOptions.Multiline);
            //return Regex.Replace(s, @"^(?:[\t ]*(?:\r?\n|\r))+", string.Empty, RegexOptions.Multiline); 
            //return Regex.Replace(s, @"(?<=(?:\r?\n){2}|\A)(?:\r?\n)+", string.Empty, RegexOptions.Multiline); 
            //return Regex.Replace(s, @"(?<=(?:\r?\n){2}$\w)(?:\r?\n)+", string.Empty, RegexOptions.Multiline); 
            //return Regex.Replace(s, @"^\s*(\r\n|\V)", string.Empty, RegexOptions.Multiline); //does not work

        }

        public static void Main()
        {
            string output = string.Empty;

            Stopwatch sw = new Stopwatch();

            string emptytest = "Tell me and I forget.\n \n     \nTeach me and I remember.     \r\n \r\n\r\nInvolve me and I learn.  \r     \r\r\0\r\r   Pad Unicode \\u0080 next line\n\n\u0080\r\rby Benjamin Franklin.\r\n";

            sw.Start();
            output = emptytest.RemoveEmptyLines();
            sw.Stop();
            Console.WriteLine(output + " in " + sw.ElapsedTicks + " ticks");

            Console.WriteLine();
            Console.WriteLine("-------- StringReader Issue ----------------");
            sw.Reset();
            sw.Start();
            output = emptytest.RemoveAllBlankLinesIssue();
            sw.Stop();
            Console.WriteLine(output + " in " + sw.ElapsedTicks + " ticks");


            Console.WriteLine();
            Console.WriteLine("-------- StringReader Final ----------------");
            sw.Reset();
            sw.Start();
            output = emptytest.RemoveAllBlankLinesFinal();
            sw.Stop();
            Console.WriteLine(output + " in " + sw.ElapsedTicks + " ticks");

            Console.WriteLine();
            Console.WriteLine("-------- Regex ----------------");

            sw.Reset();
            sw.Start();
            output = emptytest.RemoveAllBlankLinesRegex();
            sw.Stop();

            Console.WriteLine(output + "\n in " + sw.ElapsedTicks + " ticks");

            

        }
    }

Monday, November 9, 2020

.NET Conference 2020 - Make you own .NET bot profile pic

 

Make your own .NET bot profile pic - https://mod-dotnet-bot.net/

Shoppers Drug Mart Phishing email with subject Open Immediately

For the record, this is an Shoppers Drug Mart phishing email attempt that is recently going around, with subject "Open Immediately" What to do?  Report them, goto bottom of page. 


From : Shoppers Drug Mart <ambafrance.us.org@gmail.com>
Subject : Open Immediately


Shoppers Drug Mart - Please respond!








PHISHING LINKs;

1. Hover over image
https://www.elyurl.com/gnChX 

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.
  3. The best way is to 

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing

If you have recievied this email take further 

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Sunday, November 8, 2020

Amazon Prime Phishing Email with subject Amazon Prime - Your opinion matters

For the record, this is an Amazon Prime phishing email attempt that is recently going around, with subject "Amazon-Prime" What to do?  Report them, goto bottom of page. 


From : ACT NOW! <vbjAmarketingoperations@cms.experian.com>
Subject : amazon-prime


Your Opinion Matters






PHISHING LINKs;

1. Hover over image 
https://u13047169.ct.sendgrid.net/ls/click?upn=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.
  3. The best way is to 

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing

If you have recievied this email take further 

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Thursday, November 5, 2020

Walmart Phishing Email - WeIcome To WaImart #502 Congrats you've been selected

For the record, this is an Walmart phishing email attempt that is recently going around, with subject "WeIcome To WaImart #502 Congrats you've been selected" What to do?  Report them, goto bottom of page. 


From : Welcome <xxxxx-xxxxxxx-noReply@fndjtvuh.tu.edu.sa> 
Subject : WeIcome To WaImart #502 


Congrats you've been selected





PHISHING LINKs;

1. Hover over image 
https://qsdfsf_sdfsdfsdf_sdf_sdf.storage.googleapis.com/qs56df7#qNlkW.aspx?d9WQQSccd0JFcw91kcdc8kcJcxKmHcVX8cbbb3m

How to tell this is a Phishing email ?

  1. Check email address in full, if it's not from originating company then it's phishing.
  2. Hover over all links in email, if it's not from the  company's website then forget it.
  3. The best way is to 

How to examine Email Message Source ?

Now lets look at message source
  1. Outlook.com->Actions->View Message Source. 
  2. Gmail.com->More (down arrow to top right)->Show original.
Check for suspicious links, anything that does not originate from apple.com.


Report Phishing Email (not as Spam)

  1. Outlook.com->Junk (at Top)->Phishing Scam
  2. Gmail.com->More (down-arrow to top right)->Report Phishing 

Report Phishing

If you have recievied this email take further 

  1. https://www.google.com/safebrowsing/report_phish/


Report phishing at Microsoft and government agencies

  1. http://www.microsoft.com/security/online-privacy/phishing-faq.aspx

Friday, October 30, 2020

C# .NET Validate Drive Letter with compiler optimization aggressive in-lining for large fall-through case statements

Here's a surprise,  range operator is beaten by a large set of serial cases statements! 




In the below code example which validates a drive letter,  by 

using System.Runtime.CompilerServices;

you can adorn the case-statement method to be compiled with  

[MethodImplAttribute(MethodImplOptions.AggressiveOptimization )] and/or

[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]

to surprising results.  I was surprised by v6. v5 and v6 win on alternative runs.

Full documentation here - https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.methodimploptions


Source Code

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
					
public static class Program
{
	 //Fri 30-Oct-20 2:17pm metadataconsulting.ca 
	 //https://metadataconsulting.blogspot.com/2020/10/C-NET-Validate-Drive-Letter-with-compiler-optimization-aggressive-in-lining-for-large-fall-through-case-statements.html
	 //-> this method does not exist on the interwebs, trivial?
	 //-> fun with compiler switches to optimize case statements 
	
	 public static bool isValidDriveLetter(this string drivewithcolon)
	 {
		 
		 if (drivewithcolon.Length == 2 && drivewithcolon[1] == ':')
		 {
			 drivewithcolon = drivewithcolon.ToUpper();
			 // this is surprisingly faster than the equivalent if statement
			 switch (drivewithcolon[0])
			 {
				 case 'A':
				 case 'B':
				 case 'C':
				 case 'D':
				 case 'E':
				 case 'F':
				 case 'G':
				 case 'H':
				 case 'I':
				 case 'J':
				 case 'K':
				 case 'L':
				 case 'M':
				 case 'N':
				 case 'O':
				 case 'P':
				 case 'Q':
				 case 'R':
				 case 'S':
				 case 'T':
				 case 'U':
				 case 'V':
				 case 'W':
				 case 'X':
				 case 'Y':
				 case 'Z':
					 return true;
				 default:
					 return false;
			 }
		 }
		 else
			 return false; 

	 }
     //range operator	
	 public static bool isValidDriveLetterV2(this string drivewithcolon)
	 {
		 		 
		 if (drivewithcolon.Length == 2 && drivewithcolon[1] == ':')
		 {
			 drivewithcolon = drivewithcolon.ToUpper();
			 if (drivewithcolon[0] >= 'A' && drivewithcolon[0] <= 'Z') 
			 	return true;
			 else 
				 return false; 
		 }
		 else
			 return false; 

	 }
	
	 [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
	 public static bool isValidDriveLetterV3(this string drivewithcolon)
	 {
		 
		 if (drivewithcolon.Length == 2 && drivewithcolon[1] == ':')
		 {
			 drivewithcolon = drivewithcolon.ToUpper();
			 // this is surprisingly faster than the equivalent if statement
			 switch (drivewithcolon[0])
			 {
				 case 'A':
				 case 'B':
				 case 'C':
				 case 'D':
				 case 'E':
				 case 'F':
				 case 'G':
				 case 'H':
				 case 'I':
				 case 'J':
				 case 'K':
				 case 'L':
				 case 'M':
				 case 'N':
				 case 'O':
				 case 'P':
				 case 'Q':
				 case 'R':
				 case 'S':
				 case 'T':
				 case 'U':
				 case 'V':
				 case 'W':
				 case 'X':
				 case 'Y':
				 case 'Z':
					 return true;
				 default:
					 return false;
			 }
		 }
		 else
			 return false; 

	 }	
	
	 [MethodImplAttribute(MethodImplOptions.AggressiveOptimization)]
	 public static bool isValidDriveLetterV4(this string drivewithcolon)
	 {
		 
		 if (drivewithcolon.Length == 2 && drivewithcolon[1] == ':')
		 {
			 drivewithcolon = drivewithcolon.ToUpper();
			 // this is surprisingly faster than the equivalent if statement
			 switch (drivewithcolon[0])
			 {
				 case 'A':
				 case 'B':
				 case 'C':
				 case 'D':
				 case 'E':
				 case 'F':
				 case 'G':
				 case 'H':
				 case 'I':
				 case 'J':
				 case 'K':
				 case 'L':
				 case 'M':
				 case 'N':
				 case 'O':
				 case 'P':
				 case 'Q':
				 case 'R':
				 case 'S':
				 case 'T':
				 case 'U':
				 case 'V':
				 case 'W':
				 case 'X':
				 case 'Y':
				 case 'Z':
					 return true;
				 default:
					 return false;
			 }
		 }
		 else
			 return false; 

	 }	
	
	
	 [MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
	 public static bool isValidDriveLetterV5(this string drivewithcolon)
	 {
		 
		 if (drivewithcolon.Length == 2 && drivewithcolon[1] == ':')
		 {
			 drivewithcolon = drivewithcolon.ToUpper();
			 // this is surprisingly faster than the equivalent if statement
			 switch (drivewithcolon[0])
			 {
				 case 'A':
				 case 'B':
				 case 'C':
				 case 'D':
				 case 'E':
				 case 'F':
				 case 'G':
				 case 'H':
				 case 'I':
				 case 'J':
				 case 'K':
				 case 'L':
				 case 'M':
				 case 'N':
				 case 'O':
				 case 'P':
				 case 'Q':
				 case 'R':
				 case 'S':
				 case 'T':
				 case 'U':
				 case 'V':
				 case 'W':
				 case 'X':
				 case 'Y':
				 case 'Z':
					 return true;
				 default:
					 return false;
			 }
		 }
		 else
			 return false; 

	 }	

	[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
	public static bool isValidDriveLetterV6(this string drivewithcolon)
	 {
		 if (drivewithcolon.Length == 2 && drivewithcolon[1] == ':')
		 {
			 drivewithcolon = drivewithcolon.ToUpper();		 
			 if (drivewithcolon[0] >= 'A' && drivewithcolon[0] <= 'Z') 
			 	return true;
			 else 
				 return false; 
		 }
		 else
			 return false; 

	 }
 	
	public static void Main()
	{
	    bool v1,v2,v3,v4,v5,v6 = false;  

		Stopwatch sw = new Stopwatch(); 

		sw.Start();
		v1= "Z:".isValidDriveLetter(); 
		sw.Stop();
		Console.WriteLine("is Z: valid drive letter ?{0}, v1 in {1} ticks.",v1.ToString(), sw.ElapsedTicks);
		
		sw.Reset(); 
		sw.Start();
		v2= "Z:".isValidDriveLetterV2(); 
		sw.Stop();
		Console.WriteLine("is Z: valid drive letter ?{0}, v2 in {1} ticks.",v2.ToString(), sw.ElapsedTicks);
	
	    sw.Reset(); 
		sw.Start();
		v3= "Z:".isValidDriveLetterV3(); 
		sw.Stop();
		Console.WriteLine("is Z: valid drive letter ?{0}, v3 in {1} ticks.",v3.ToString(), sw.ElapsedTicks);
	
	    sw.Reset(); 
		sw.Start();
		v4= "Z:".isValidDriveLetterV4(); 
		sw.Stop();
		Console.WriteLine("is Z: valid drive letter ?{0}, v4 in {1} ticks.",v4.ToString(), sw.ElapsedTicks);
	
		sw.Reset(); 
		sw.Start();
		v5= "Z:".isValidDriveLetterV5(); 
		sw.Stop();
		Console.WriteLine("is Z: valid drive letter ?{0}, v5 in {1} ticks.",v5.ToString(), sw.ElapsedTicks);
	
		sw.Reset(); 
		sw.Start();
		v6= "Z:".isValidDriveLetterV6(); 
		sw.Stop();
		Console.WriteLine("is Z: valid drive letter ?{0}, v6 in {1} ticks.",v6.ToString(), sw.ElapsedTicks);
		
		
	}
}