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.