Monday, 21 October 2019

Automapper unit test cases

using System;
using System.Collections;
using System.Threading.Tasks;
using PersonEntityMatchService.Business;
using PersonEntityMatchService.Business.Mappers;
using PersonEntityMatchService.Domain.Requests;
using PersonEntityMatchService.Domain.Responses;

namespace PersonEntityMatchService.Unit.Tests.Business
{
    using AutoMoqCore;
    using NUnit.Framework;
    using System.Collections.Generic;
    using Moq;
    using Clients;
    using Clients.Requests;
    using Clients.Responses;

    [TestFixture(Category = "UnitTest")]
    public class PersonMatchHandlerTests
    {
        private AutoMoqer _mocker;

        [SetUp]
        public void Setup()
        {
            _mocker = new AutoMoqer();
        }

        [Test]
        public void GetPersonMathcScoreTest()
        {
            var expectedMatches = new[]
            {
                new MatchEntity
                {
                    matchGroups = new[]
                    {
                        new Domain.Responses.MatchGroup
                        {
                            matchDescription = "test",
                            scoreStandalone = 50,
                            scoreIncremental = 10,
                            type = "suspect"
                        }
                    },
                    matchScore = 50
                }
            };
            var returnList = new List<MdaMatchEntity>();
            _mocker.GetMock<IMdaClient>()
                .Setup(x => x.GetMatchResponse(It.IsAny<MdaRequest>()))
                .Returns(Task.FromResult<IEnumerable<MdaMatchEntity>>(returnList));
            _mocker.GetMock<IMdaRequestMapper>()
                .Setup(x => x.MapToMdaRequest(It.IsAny<PersonEntity>()))
                .Returns(new MdaRequest());
            _mocker.GetMock<IMatchEntityMapper>()
                .Setup(x => x.MapToMatchEntities(It.IsAny<IEnumerable<MdaMatchEntity>>()))
                .Returns(expectedMatches);
            var target = _mocker.Resolve<PersonMatchHandler>();
            var actualMatches = target.GetPersonMatchScore(new PersonEntity());
            Assert.AreEqual(expectedMatches, actualMatches.Result);
        }

        [Test]
        public void GetPiiMathcScoreTest()
        {
            var expectedMatches = new[]
            {
                new PiiMatchEntity
                {
                    Ssn=new Ssn()
                    {
                        value="SSnABC"
                    },
                    DoB=new Domain.Responses.DoB
                    {
                        value="DOB123"
                    },
                    matchGroups = new[]
                    {
                        new Domain.Responses.MatchGroup
                        {
                            matchDescription = "test",
                            scoreStandalone = 50,
                            scoreIncremental = 10,
                            type = "suspect"
                        }
                    },
                    matchScore = 50
                }
            };
            var returnList = new List<MdaMatchEntity>();
            _mocker.GetMock<IMdaClient>()
                .Setup(x => x.GetMatchResponse(It.IsAny<MdaRequest>()))
                .Returns(Task.FromResult<IEnumerable<MdaMatchEntity>>(returnList));
            _mocker.GetMock<IMdaRequestMapper>()
                .Setup(x => x.MapToMdaRequest(It.IsAny<PersonEntity>()))
                .Returns(new MdaRequest());
            _mocker.GetMock<IMatchEntityMapper>()
                .Setup(x => x.MapToMatchPiiEntities(It.IsAny<IEnumerable<MdaMatchEntity>>()))
                .Returns(expectedMatches);
            var target = _mocker.Resolve<PersonMatchHandler>();
            var actualMatches = target.GetPiiMatchScore(new PersonEntity());
            Assert.AreEqual(expectedMatches, actualMatches.Result);
        }

    }
}


namespace PersonEntityMatchService.Unit.Tests
{
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using NUnit.Framework;
    using Domain.Responses;

    [TestFixture(Category = "UnitTest")]
    public class PiiMatchEntityContractTests : TestBase
    {
        [Test]
        public void Should_serialize_Entity()
        {
            var entities = ResponseEntity();

            var expected = GetJToken("POST_PiiMatch_Response.json");

            var actual = JToken.Parse(JsonConvert.SerializeObject(entities));

            Assert.True(JToken.DeepEquals(actual, expected), "Expected should match actual when serializing.");
        }

        [Test]
        public void Should_deserialize_Entity()
        {
            var entities = GetJToken("POST_PiiMatch_Response.json");

            var expected = ResponseEntity();

            var actual = JsonConvert.DeserializeObject<List<PiiMatchEntity>>(entities.ToString());

            var comparer = new ObjectsComparer.Comparer<List<PiiMatchEntity>>();

            Assert.True(comparer.Compare(actual, expected), "Expected should match actual when deserializing.");
        }

        private static List<PiiMatchEntity> ResponseEntity()
        {
            return new List<PiiMatchEntity>
            {
                new PiiMatchEntity{
                    Ssn=new Ssn()
                    {
                        value="/wEBReHevtjQYqAYuGis+AX0qWELTg4SkguSAXo6iE8j2927gVZLAyfosBrTYNKrIuagGrF/WlPBgobEAgjvaJ8i5uTKmGEjmweg2DvILux/wymO9hiLjUTW/wIVKkxPpVpeMJEfRuF3ejSbbgO2SChINn/mejqITyPb3bu+yKZp4nVrUub7728TFDlgx9MuqwmXx/NqQIkmKf/I0ThiQZXRhkYYqUNUwoejrhl0hqyPoLyPuHXm9sMeEZr8GHAiW3GGYUcY"
                    },
                    DoB=new DoB()
                    {
                        value="/wEBXxoST1IkLAuhdVuJ2QZsHad3mwDhaxKXAXo6iE8j29272zuTofDocz41YlG3R6zEbC9MHYXsxOdHAgjvaJ8i5uTKcv+3xrEkchQZvDo9b4saercM38kzFM1dv+wl4X6LnQeDegOo+Fd+q3y2u7h3ZqSJejqITyPb3bts/OpIHCkZYWC7FR0wG+xalm1iY+IdkzdoJR8ferrzAeQD3y9lu47NZ86X5DAXh+bh3MVZACGpd4DtEA0rWmXy0DFz+uGL8TuG"
                    },
                    uri = "/Entity?filter=EntityId eq '2f2bfe8add3041d8abfe8add30e1d854'",
                    matchScore = 80,
                    matchGroups = new[]
                    {
                        new MatchGroup
                        {
                            type = "suspect",
                            matchDescription = "Suspect individual match by fuzzy first name, fuzzy last name, email, and postal code",
                            scoreStandalone = 60,
                            scoreIncremental = 10
                        },
                        new MatchGroup
                        {
                            type = "suspect",
                            matchDescription = "Suspect individual match by first name, last name, email and postal code",
                            scoreStandalone = 70,
                            scoreIncremental = 10
                        }
                    }
                }
            };
    }
}
}



using System;
using System.IO;
using Newtonsoft.Json.Linq;
using NUnit.Framework;

namespace PersonEntityMatchService.Unit.Tests
{
    public class TestBase
    {
        [SetUp]
        public void Setup()
        {
            // Method intentionally left empty.
        }

        [TearDown]
        public void TearDown()
        {
            // Method intentionally left empty.
        }

        protected static JToken GetJToken(string fileName)
        {
            return JToken.Parse(File.ReadAllText(Path.Combine($"{AppDomain.CurrentDomain.BaseDirectory}/TestData", fileName)));
        }
    }
}


[
  {
    "Ssn": {
      "value": "/wEBReHevtjQYqAYuGis+AX0qWELTg4SkguSAXo6iE8j2927gVZLAyfosBrTYNKrIuagGrF/WlPBgobEAgjvaJ8i5uTKmGEjmweg2DvILux/wymO9hiLjUTW/wIVKkxPpVpeMJEfRuF3ejSbbgO2SChINn/mejqITyPb3bu+yKZp4nVrUub7728TFDlgx9MuqwmXx/NqQIkmKf/I0ThiQZXRhkYYqUNUwoejrhl0hqyPoLyPuHXm9sMeEZr8GHAiW3GGYUcY"
    },
    "DoB": {
      "value": "/wEBXxoST1IkLAuhdVuJ2QZsHad3mwDhaxKXAXo6iE8j29272zuTofDocz41YlG3R6zEbC9MHYXsxOdHAgjvaJ8i5uTKcv+3xrEkchQZvDo9b4saercM38kzFM1dv+wl4X6LnQeDegOo+Fd+q3y2u7h3ZqSJejqITyPb3bts/OpIHCkZYWC7FR0wG+xalm1iY+IdkzdoJR8ferrzAeQD3y9lu47NZ86X5DAXh+bh3MVZACGpd4DtEA0rWmXy0DFz+uGL8TuG"
    },
    "uri": "/Entity?filter=EntityId eq '2f2bfe8add3041d8abfe8add30e1d854'",
    "matchGroups": [
      {
        "type": "suspect",
        "matchDescription": "Suspect individual match by fuzzy first name, fuzzy last name, email, and postal code",
        "scoreStandalone": 60,
        "scoreIncremental": 10
      },
      {
        "type": "suspect",
        "matchDescription": "Suspect individual match by first name, last name, email and postal code",
        "scoreStandalone": 70,
        "scoreIncremental": 10
      }
    ],
    "matchScore": 80
  }
]

Thursday, 17 October 2019

Entity framework dynamic query generation

using (var cmd = _unitOfWork.DbContext.Database.Connection.CreateCommand())
            {
                if (cmd.Connection.State != ConnectionState.Open)
                    cmd.Connection.Open();

                cmd.CommandText = _queryBuilder.SelectOnTable(level1RepoFieldsTable, selectColumns)
                    .WhereConditions(searchFields?.ToCompareConditions(repositoryFields).ToList())
                    .OrderBys(sortFields == null
                        ? new List<OrderBy>
                        {
                            new OrderBy {Column = Constants.IdentityColumn, Direction = OrderByDirection.Descending}
                        }
                        : sortFields.ToOrderBys(repositoryFields).ToList())
                    .CreateRawSql();

                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        var recordId = dataReader.GetColumnValue<int>(Constants.IdentityColumn);

                        if (recordId == 0)
                            continue;

                        var tdxRecord = _tdxRecordRepository.FindBy(x => x.Id == recordId)
                            .FirstOrDefault();

                        if (tdxRecord != null)
                        {
                            tdxRecord.RecordFields = dataReader.GetRecordFields(repositoryFields).ToList();
                            tdxRecords.Add(tdxRecord);
                        }

                        if (getFirstMatchingRecord) break;
                    }
                }
            }

Entity Framework Unity/ repository pattern

public interface IUnitOfWork
    {
        DbContext DbContext { get; }
        int Save();
    }

public class UnitOfWork : IUnitOfWork
    {
        public UnitOfWork(DbContext dbContext)
        {
            DbContext = dbContext;
        }

        public DbContext DbContext { get; }

        public int Save()
        {
            return DbContext.SaveChanges();
        }
    }


public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
    private readonly DbContext _dbContext;

public GenericRepository(IUnitOfWork unitOfWork)
{
_dbContext = unitOfWork.DbContext;
}

public IQueryable<TEntity> GetAll()
{
IQueryable<TEntity> query = _dbContext.Set<TEntity>();
return query;
}

public IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
{
IQueryable<TEntity> query = _dbContext.Set<TEntity>().Where(predicate);
return query;
}

public TEntity Add(TEntity entity)
{
return _dbContext.Set<TEntity>().Add(entity);
}

public void Delete(TEntity entity)
{
_dbContext.Set<TEntity>().Remove(entity);
}

public void Update(TEntity entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
}

public void Save()
{
_dbContext.SaveChanges();
}

        public IEnumerable<TEntity> AddRange(IEnumerable<TEntity> entities)
        {
            return _dbContext.Set<TEntity>().AddRange(entities);
        }
    }



public class TdxRepositoryService : ITdxRepositoryService
    {
        /// <summary>
        /// The generic repository for <see cref="TdxRepository"/>
        /// </summary>
        private readonly IGenericRepository<TdxRepository> _tdxGenericRepository;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="tdxGenericRepository">The generic repository for <see cref="TdxRepository"/></param>
        public TdxRepositoryService(IGenericRepository<TdxRepository> tdxGenericRepository)
        {
            _tdxGenericRepository = tdxGenericRepository;
        }

        /// <inheritdoc />
        public IEnumerable<TdxRepository> GetRepositories(bool includeInactive)
        {
            var tdxRepositories = includeInactive
                ? _tdxGenericRepository.GetAll()
                : _tdxGenericRepository.GetAll().Where(x => x.Active);
           
            return tdxRepositories
                .ToList();
        }

        /// <inheritdoc />
        public TdxRepository GeTdxRepositoryById(int repositoryId)
        {
            return _tdxGenericRepository
                .FindBy(x => x.Id == repositoryId)
                .FirstOrDefault();
        }

///<inheritdoc/>
public TdxRepository GeTdxRepositoryByName(string repositoryName)
{
return _tdxGenericRepository
.FindBy(x => x.Name.LOWER() == repositoryName.ToLower())
.FirstOrDefault();
}
}

Linq Entity queries

1. Include key which get all records

 _repoFieldRepository
                .FindBy(x => x.TdxRepositoryId == repositoryId)
                .Include(x => x.RepositoryLevel);

MVC/ web api Action filter

public class ValidateModelStateFilter : ActionFilterAttribute
{

public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse((HttpStatusCode)422, actionContext.ModelState);
}
}

}

Sunday, 13 October 2019

Entity Framework

public class DisplayGroup
    {
 
        [Column("ID")]
        public int ID { get; set; }

[Column("PERTINENCE_GRP_ID")]
        public int? PertinenceGroupID { get; set; }

public virtual PertinenceGroup PertinenceGroup { get; set; }

}

public class DisplayGroupContent
{

[Column("ID")]
public int ID { get; set; }


[Column("PARENT_GROUP_ID")]
public int ParentGroupID { get; set; }


public virtual DisplayGroup ParentGroup { get; set; }

}

public class PertinenceGroup
{
[Column("ID")]
public int ID { get; set; }

public virtual ICollection<DisplayGroup> DisplayGroups { get; set; }

}


public class DisplayGroupConfiguration: EntityTypeConfiguration<DisplayGroup>
{

public DisplayGroupConfiguration()
{
ToTable("GDD_ENTITY_DSPLY_GRPS");
HasKey(x => x.ID);

HasMany(x => x.DisplayGroupContents).WithRequired(x => x.ParentGroup).HasForeignKey(x => x.ParentGroupID);

HasOptional(x => x.PertinenceGroup).WithMany().HasForeignKey(x => x.PertinenceGroupID);
}
}

public class DisplayGroupContentConfiguration : EntityTypeConfiguration<DisplayGroupContent>
{

public DisplayGroupContentConfiguration()
{
{
ToTable("GDD_DSPLY_GRP_CONTENTS");
HasKey(x => x.ID);

HasRequired(x => x.ParentGroup).WithMany().HasForeignKey(x => x.ParentGroupID);

}
}
}

public class PertinenceGroupConfiguration : EntityTypeConfiguration<PertinenceGroup>
{

public PertinenceGroupConfiguration() {
ToTable("GDD_PERTINENCE_GRPS");
HasKey(x => x.ID);

HasMany(x => x.DisplayGroups)
.WithOptional(x => x.PertinenceGroup)
.HasForeignKey(x => x.PertinenceGroupID);
}
}



CREATE TABLE "CSNCFG"."GDD_ENTITY_DSPLY_GRPS"
   ( "ID" NUMBER NOT NULL ENABLE,

"OWNER_TYPE_ID" NUMBER NOT NULL ENABLE,

"PERTINENCE_GRP_ID" NUMBER(10,0),

CONSTRAINT "GDD_ENTITY_DSPLY_GRPS_PK" PRIMARY KEY ("ID")

CONSTRAINT "GDD_ENTITY_DSPLY_GRPS_FK2" FOREIGN KEY ("PERTINENCE_GRP_ID")
  REFERENCES "CSNCFG"."GDD_PERTINENCE_GRPS" ("ID") ENABLE,

   )


CREATE TABLE "CSNCFG"."GDD_DSPLY_GRP_CONTENTS"
   ( "ID" NUMBER(10,0) NOT NULL ENABLE,

"PARENT_GROUP_ID" NUMBER(10,0) NOT NULL ENABLE,

"CHILD_GROUP_ID" NUMBER(10,0),

CONSTRAINT "GDD_DSPLY_GRP_CONTENTS_PK" PRIMARY KEY ("ID")

CONSTRAINT "GDD_DSPLY_GRP_CONTENTS_FK1" FOREIGN KEY ("PARENT_GROUP_ID")
  REFERENCES "CSNCFG"."GDD_ENTITY_DSPLY_GRPS" ("ID") ENABLE,

CONSTRAINT "GDD_DSPLY_GRP_CONTENTS_FK2" FOREIGN KEY ("CHILD_GROUP_ID")
  REFERENCES "CSNCFG"."GDD_ENTITY_DSPLY_GRPS" ("ID") ENABLE,

   )



 CREATE TABLE "CSNCFG"."GDD_PERTINENCE_GRPS"
   ( "ID" NUMBER(10,0),

CONSTRAINT "GDD_PERTINENCE_GRPS_PK" PRIMARY KEY ("ID")

   )