Sunday, October 1, 2017

C# Linq ,Generics, Lamda expression and many more.

Introduction
I'll keep this space updating my most used c# stuff in here. This is work in progress to have list of all referenced code that is useful at times of implementation.

Linq Data Parallelism

var quotes =quotesForAllProducts();//e.g Get quotes for all products
Parallel.ForEach(products, item => Process(item,quotes));


private void Process(Product item,List<Quote> quotes)
      {
          
var quote= quotes?.SingleOrDefault
                  (p =>
                      p.Id.Trim().Equals(item.Id ?? 
string.Empty));
          
if (quote != null)
          {
              item.Cost = quote.TotalAmount.GetValueOrDefault();
              item.Code = quote.Code;
          }          
      }

System.Linq.ParallelEnumerable

Set object values for superset.
Packages = poducts.AsParallel().Select(p => new Package
                {
                    tId = p.tId,
                    vId = p.vId
                }).ToList(),

SelectMany

private void SetProductsSubSet(IList<Product> products)
    {
        _products= (
IEnumerable<ProductDetail>) products?.AsParallel().SelectMany(a => a.subLevel.Select(p => new ProductDetail
        {
            Id = a.Id,
            Type = a.Type,
        })) ?? 
new List<ProductDetail>();

    } 


Left Join DefaultIfEmpty()

public List<Product> AddHospitalAndExtrasProduct()
       {
           
return
               (
from A in Main
               
join B in SubB on A.ID equals B?.Id into MainAndSubB
                   
from ResultSetA in MainAndSubB.DefaultIfEmpty()
               
join B in SubC on A.ID equals C?.Id into MainAndSubC
                   
from ResultSetC in MainAndSubC.DefaultIfEmpty()
            select new Product
            {
                Id = Main.Id,
                Name = Main.Name,
                SubBId = ResultSetA != 
null ? ResultSetA .SubBId : string.Empty,
                SubCId = ResultSetC != 
null ? ResultSetC .SubCId : string.Empty,
            }).ToList();          
       }

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.