Monday, September 11, 2017

Use case IEquatable and Object.Equal

Introduction

One can use IEquatable for comparing two object values. This is useful when we have to check any duplicate enteries. Let me know if you have any better solution to implement the same use case scenario. I have address string in Address object.

String Comparisons

  • Handle whitespace between two words , letters.
  • Handle trailing and leading spaces
  • Handle casing of strings

//Private Member
private List<Address> _addresses;

//Method for update Address and duplicate checks
public string UpdateAddress(Address personAddress)
{
           
string requestCorrelationId = _client.GetCorrelationRequest();
           
var userContext = _sessionService.Get<UserContext>(SessionKeys.UserContext);
           
try
           {
               
if (IsDuplicateAddress(personAddress))
               {
return "Duplicate some Message"
}
}
}

//Private Method
private bool IsDuplicateAddress(Address personAddress)
{
    
return _addresses().Any(p => p.Equals(personAddress));
}

//Implement IEquatable
public partial class Address : IEquatable<Address>
  {
  
       
public string AddressLine1 { getset; }

       
public string AddressLine2 { getset; }

       
public string AddressLine3 { getset; }

       
public string Suburb { getset; }

       
public string State { getset; }

       
public string PostCode { getset; }

       
public string CountryCode { getset; }

       
public long? Id { getset; }


      public bool Equals(Address newAddress)
      {     
          
if (newAddress == nullreturn false;
          
return 
string.Equals(Regex.Replace(newAddress.AddressLine1 ?? 
string.Empty, @"\s"string.Empty), 
Regex.Replace(AddressLine1, @"\s"string.Empty), 
StringComparison.OrdinalIgnoreCase)
              && 
string.Equals(Regex.Replace(newAddress.AddressLine2 ?? 
string.Empty, @"\s"string.Empty), 
Regex.Replace(AddressLine2, @"\s"string.Empty), 
StringComparison.OrdinalIgnoreCase)
              && 
string.Equals(Regex.Replace(newAddress.AddressLine3 ?? 
string.Empty, @"\s"string.Empty), 
Regex.Replace(AddressLine3, @"\s"string.Empty), 
StringComparison.OrdinalIgnoreCase)
              && 
string.Equals(newAddress.CountryCode ?? 
string.Empty,CountryCode, 
StringComparison.OrdinalIgnoreCase)
              && 
string.Equals(newAddress.PostCode ?? 
string.Empty,PostCode, 
StringComparison.OrdinalIgnoreCase)
              && 
string.Equals(newAddress.State ?? 
string.Empty, State, 
StringComparison.OrdinalIgnoreCase)
              && 
string.Equals(Regex.Replace(newAddress.Suburb ?? 
string.Empty, @"\s"string.Empty), 
Regex.Replace(Suburb, @"\s"string.Empty), 
StringComparison.OrdinalIgnoreCase);
      }

      
public override bool Equals(object obj)
      {
          
if (ReferenceEquals(null, obj)) return false;
          
if (ReferenceEquals(this, obj)) return true;
          
if (obj.GetType() != GetType()) return false;
          
return Equals(obj as Address);
      }

      
public override int GetHashCode()
      {
          
unchecked
          {
              
var hashCode = AddressLine1?.GetHashCode() ?? 0;
              hashCode = (hashCode
*397) ^ (AddressLine2?.GetHashCode() ?? 0);
              hashCode = (hashCode
*397) ^ (AddressLine3?.GetHashCode() ?? 0);
              hashCode = (hashCode
*397) ^ (Suburb?.GetHashCode() ?? 0);
              hashCode = (hashCode
*397) ^ (State?.GetHashCode() ?? 0);
              hashCode = (hashCode
*397) ^ (PostCode?.GetHashCode() ?? 0);
              hashCode = (hashCode
*397) ^ (CountryCode?.GetHashCode() ?? 0);
              hashCode = (hashCode
*397) ^ Id.GetHashCode();
              
return hashCode;
          }
      }
  }

Wednesday, September 6, 2017

Myth Buster ReferenceEquals == Equals()

Introduction


ReferenceEquals and Equals and == are pretty much does the same thing.
  • It compares the object reference to SAME instance.
  • Even if the object reference is of the same type and have same value it returns false.


using System;

namespace ConsoleApplication1
{
    
class Program
    {
        
static void Main(string[] args)
        {
      
            
var c1 = new Car(1, "Matiz");
            
var c2 = new Car(1, "Matiz");
           
            
//COMPARES OBJECT REFERENCES OF DIFFERENT INSTANCES OF SAME TYPE
            
Console.WriteLine(c1.Equals(c2));//false
            
Console.WriteLine(ReferenceEquals(c1, c2));//false
            
Console.WriteLine(c1 == c2);//false
        
            
var c3 = c2;
            
//COMPARES OBJECT REFERENCES OF SAME INSTANCES OF SAME TYPE
            
Console.WriteLine(c3.Equals(c2));//true
            
Console.WriteLine(ReferenceEquals(c3, c2));//true
            
Console.WriteLine(c3 == c2);//true

            
Console.Read();
        }

        
private class Car
        {
            
private readonly int _id;
            
private readonly string _name;

            
public Car(int id, string name)
            {
                _id = id;
                _name = name;
            }
        }
    }
}


Tuesday, September 5, 2017

Asp.net MVC MetaDataType attribute

Introduction

Developers working on asp.net mvc with Entity framework, POCO model or swagger generated web api code generation, mvc metadatatype attribute comes very handy. Everyone should be aware of this construct and usage. I want to file this for my reference hence added small reference here.

Asp.net MVC MetaDataType attribute

Specifications:
  • Only applied to partial class
  • Can be used when you have to do additional validation on entity framework generated entity class or Swagger generated api code for client.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
//Class generated from Entity Framework Database First
public partial class YourModelClass
{
    public string YourProperty{get;set;}
}

//Your Partial Class
[MetadataType(typeof(YourModelClassMetaData))]
public partial class YourModelClass
{
}

//The class that add your attributes
public class YourModelClassMetaData
{
    //validation
    [Required]
    public object YourProperty{get;set;};
}

From <http://patrickdesjardins.com/blog/why-it-is-wrong-to-use-the-asp-net-mvc-metadatatype-attribute

Sunday, September 3, 2017

Static Readonly Constant Vs Const Constant

Constant Static ReadOnly vs Const

Sr.No
public  static readonly int iCentury=100;

public const int iCentury=100;
1
Runtime Constant

Compile Time Constant

2
Can intialize integral, floating ,string enum and NEW operator.
private static readonly DateTime _aheadOfMyTime=
new DateTime(2050,1,1,0,0,0);
Compile Time is eventually assigned with literals and can only be used with primitive datatype such as built in integral, floating point type,enum string. You can initialize compile time with new operator. They are limited to numbers and strings value

3
Unlike Const bit of performance overhead.

Better Performance and more efficient
4
Client A=> Assembly A[static readonly iCentury]
Client B=> Assembly A[Static readonly iCentury]

IL generated for client A and B will have reference readonly variable[iCentury] not value

Client A=> Assembly A[const iCentury]
Client B=> Assembly A[const iCentury]

IL generated for client A and B will have values of const not reference Variable
5
In terms of maintenance purpose readonly is more appropriate as client is not required to be compiled only assembly is compiled.

Whereas const require all assembly and dependent client to be build and compiled for each release
6
This is more suitable if constant is prone to change for each release
Not viable if constant value is changing for each release.


Sunday, August 13, 2017

Powershell ISE Cheat sheet

1# How to Comment Multi line code in ISE editor

Put cursor on start of code. Select Shift +Alt and move down arrow key to end of code line. Then press Shift +#

2# How to open/load web page ?

start-process -FilePath "www.google.com.ua"


Thursday, August 3, 2017

Sitecore XFrameOptionsHeaderModule and Chrome 60.0.3112.78 (official build) (64-bit) x-frame-options SAMEORIGIN Refused to display

Introduction

Chrome Side of story:-
X-Frame-Option Same origin issue appeared in Chrome version 60+ and it came surprising when browser started upgraded from lower version to this version. What if such issue appeared in production where your platform is dependent on third party service provider such as payment gateway through IFrame or any data layer that injects data to your system. Well the point is everything boils down to how secure you want to create a platform.

Your site- Domain ABC- Allow access to Domain XYZ[SameOrigin will not work]
Chrome version 60 and above enforce this and check this X-frame-options.

What happened next?
It started throwing below error in developer tool f12 - console

Refused to display https://abc' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
iframe-tunnel.js:60 GET https://xyz net::ERR_BLOCKED_BY_RESPONSE


Sitecore MVC Side of story:-

From sitecore 8.1 update 3 onwards sitecore introduce default module to add X-FRAME-OPTION Sameorigin using below module

One can check this in web.config file
 type="Sitecore.Web.XFrameOptionsHeaderModule, Sitecore.Kernel" name="SitecoreXFrameOptionsHeaderModule"/>
Reference


Probable Solution

using System.Web.Mvc;

namespace Test.Filters
{
    public class RemoveXFrameOptionsAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Headers.Remove("X-Frame-Options");
            base.OnResultExecuted(filterContext);
        }
    }
[RemoveXFrameOptions]
public class TestController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}
}
//or 
//this worked for us.
public class TestController : Controller
{
    [RemoveXFrameOptions]
    public ActionResult Index()
    {
        return View();
    }
}

https://stackoverflow.com/questions/35466242/removing-x-frame-options-header-for-a-specific-controller-only

Bit of background

Why x-frame-options SameOrigin thing? This is required to avoid CLICK JACKING.

https://www.codeproject.com/Articles/291562/Asp-net-web-application-Security-Review-Dos-Dont

My final Say

Sitecore should add this in their KB site to be more explicit so that customer is aware of such changes.

Thursday, July 20, 2017

IIS Log Parser and important troubleshooting queiries

Understand your IIS Log better

There are cases when even asp.net and sitecore application level logs doesn't provide much of an information.The reason behind is some request is just processed by IIS webserver but never executed at application server i.e sitecore or asp.net pipeline.

This is where HTTP.Sys , Failed Request Tracing and IIS logs comes into picture. This is not when you looking for memory leak or CPU utilization.But this is certain some of the pattern of page execution or 500 internal server exception indirectly contributes to memory leak or CPU utilization. Always visit your IIS logs post performance load test. This will help you align your performance results with incoming request made in IIS.

Long story short. Download log parser studio if you have IIS log to analyze. This is very handy tool.

https://gallery.technet.microsoft.com/office/Log-Parser-Studio-cd458765

Query#1 Http.5xxx


SELECT TO_LOCALTIME( TO_TIMESTAMP( date, time ) ),
    cs-username,
    sc-status,
    sc-substatus,
    cs-uri-stem,
    time-taken as time_taken_MS,
    DIV(time-taken,60000) as timetaken_MM,
    cs-method, 
    cs-uri-query ,
    Count(*) AS Total
    From '[LOGFILEPATH]'
    Where sc-status = 500
    Group By cs-username, sc-status, cs-uri-stem, cs-uri-query,date,time,cs-method, cs-uri-query ,time-taken,sc-substatus



Query#2:/*  Count and sort all HTTP status codes */
Remember http status code below have apended http SUB STATUS CODE

SELECT TOP 25  
    STRCAT(TO_STRING(sc-status),  
    STRCAT('.', TO_STRING(sc-substatus))) As Status,  
    COUNT(*) AS Hits  
    FROM '[LOGFILEPATH]'  
GROUP BY Status  
ORDER BY Hits DESC 

Query#3 To find DDOS Attack

A distributed denial-of-service (DDoS)attack occurs when multiple systems flood the bandwidth or resources of a targeted system, usually one or more web servers. Such an attack is often the result of multiple compromised systems (for example, a botnet) flooding the targeted system with traffic.

/* Hits on a particular page by IP address */

select c-ip, count(c-ip) as requestcount 
from '[LOGFILEPATH]' 
where cs-uri-stem like '%/%' 
group by c-ip order by count(c-ip) desc