Auto Mapper Constructor initialization Mapping Issue - asp.net

I have the following Mapping configurations:-
Initialized Data:-
private static IEnumerable<Source> InitializeData()
{
var source= new[]
{
new Source("John", "Doe", "1111111111"),
new Source("Jack", "Handsome", "2222222222"),
new Source("Joe", "Mackenze", "3333333333")
};
return source;
}
Source Model:
public class Source
{
private string First { get; set; }
private string Last { get; set; }
private string Phone { get; set; }
public Source(string first, string last, string phone)
{
First = first;
Last = last;
Phone = phone;
}
}
Destination Model
public class Destination
{
public string First { get; set; }
public string Last { get; set; }
public string Phone { get; set; }
}
Main
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
cfg.CreateMap<Source, Destination>().ReverseMap();
});
var mapper = new Mapper(config);
var source= InitializeData();
var people = mapper.Map<IEnumerable<Destination>>(source);
foreach (var p in people)
{
Console.WriteLine("Name: {0}-{1} Phone: {2}", p.First, p.Last, p.Phone);
}
Console.ReadLine();
}
Problem descriptions:
I have been struggled to understand the AutoMapper mapping between source and destination models.
My source model has a constructor to initialize or accept data from outside. It works fine when I removed the source constructor from the model that's mean flat mapping works fine but constructor initialization has the issue. When I debug in VS2019, it shows the number of records but all fields are empty/null.
What is wrong with the above mapping. I have gone through the AutoMapper reference docs but do not get a hold on this issue.
I highly appreciate your help!

Try calling AssertConfigurationIsValid. Check http://docs.automapper.org/en/latest/Configuration-validation.html.
Your Source properties are private. I assume you meant public.

Related

ASP.NET GET request always returns blank

I'm trying to make an endpoint to return a JSON response. I've tried narrowing it down to just the object and all I receive is {} or [{}] as a response. After debugging I confirmed that the object was being created correctly but when returning the response it was always blank. Below is simplified code but still has the same issue. Any ideas what I'm doing wrong?
[Route("{application}")]
[HttpGet]
public IActionResult Get(string application)
{
List<RequestedSetting> requestedSettings = new List<RequestedSetting>();
RequestedSetting rs = new RequestedSetting("foo", "bar");
requestedSettings.Add(rs);
return Json(requestedSettings);
}
public class RequestedSetting
{
public string Name;
public string Value;
public RequestedSetting(string name, string value)
{
Name = name;
Value = value;
}
}
I've also tried this:
[Route("{application}")]
[HttpGet]
public List<RequestedSetting> Get(string application)
{
List<RequestedSetting> requestedSettings = new List<RequestedSetting>();
RequestedSetting rs = new RequestedSetting("foo", "bar");
requestedSettings.Add(rs);
return requestedSettings;
}
Fields are not supported for serialisation in System.Text.Json. see the docs for more info.
Instead, change your class to use properties:
public class RequestedSetting
{
public string Name { get; set; }
public string Value { get; set; }
public RequestedSetting(string name, string value)
{
Name = name;
Value = value;
}
}

SQLite.NET PCL returning 0 in all instances of autoincrement primary key

I am totally not getting this, because I have used this library in Xamarin apps for several years.
I have this base class that contains properties common in all db items:
public class BaseItem
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; } = 0; // SQLite ID
public long CreatedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
public long ModifiedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
}
Now, I derive from it:
[Table("CategoryTable")]
public class Category : BaseItem
{
public int CategoryTypeID { get; set; } = (int)CategoryType.Invalid;
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
Here's a simplified version of what I'm seeing:
public class DBWorld
{
ISQLiteService SQLite { get { return DependencyService.Get<ISQLiteService>(); } }
private readonly SQLiteConnection _conn;
public DBWorld()
{
_conn = SQLite.GetConnection("myapp.sqlite");
}
public void TestThis()
{
_conn.CreateTable<Category>();
var category = new Category();
category.Name = "This Should Work";
int recCount = connection.Insert(category);
// at this point recCount shows as 1, and category.ID shows as zero.
// I thought Insert was supposed to set the autoincrement primary key
// regardless, it should be set in the database, right? So...
var categoryList = connection.Query<Category>($"SELECT * FROM {DBConstants.CategoryTableName}");
// at this point categoryList[0] contains all the expected values, except ID = 0
}
}
I am obviously missing something, but for the life of me, I can't figure out what...
Like so many other bizarre things that happen in the Visual Studio Xamarin world, when I went back later, this worked the way all of us expect. I guess Visual Studio was just tired and needed to be restarted.

System.Text.Json Deserialize Fails

With this DTO:
public class QuestionDTO {
public Guid Id { get; set; }
public string Prompt { get; set; }
public List<Answer> Choices { get; set; }
public QuestionDTO() {
}
public QuestionDTO(Question question) {
this.Id = question.Id;
this.Prompt = question.Prompt;
this.Choices = question.Choices;
}
}
I was getting an error about Unable to Parse without a parameterless constructor. I have since fixed that, but now my objects are de-serialized empty:
using System.Text.Json;
var results = JsonSerializer.Deserialize<List<QuestionDTO>>(jsonString);
The jsonString contains 3 items with the correct data, and the deserialized list contains 3 items, but all the properties are empty.
The new json library is case sensitive by default. You can change this by providing a settings option. Here is a sample:
private JsonSerializerOptions _options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
private async Task SampleRequest()
{
var result = await HttpClient.GetStreamAsync(QueryHelpers.AddQueryString(queryString, queryParams));
_expenses = await JsonSerializer.DeserializeAsync<List<Common.Dtos.Expenses.Models.Querys.ExpensesItem>>(result, _options);
}

How do you set some properties and leave others as defaults using AutoFixture and AutoMoqCustomization?

I am new to AutoFixture so I hope you can help. How do you set some properties in an object but leave others as the AutoFixture default - while using XUnit's [Theory] attribute and an AutoDataAttribute.
For example, in the contrived Airport example below based on Jason Robert's Pluralsight course, when setting the property (or the Airport object) e.g.
f.Customize<Mock<IAirport>>(c => c.Do(m => m.SetupGet(i => i.code).Returns("NOO")));
the other properties are often null, or I have to manually set them rather than letting AutoFixture do it. I would prefer to have cleaner code where the fixtureFactory sets all the properties for the Airport so that the V2 unit test only passed in a single Airport parameter.
So, within the fixtureFactory
How do you set MULTIPLE properties?
How does one use the default AutoFixture values rather than leaving the uninitialized values as
null?
Thanks!
using AutoFixture;
using AutoFixture.AutoMoq;
using AutoFixture.Xunit2;
using Moq;
using System;
using Xunit;
namespace AirportTesterWithAutoFixture
{
public interface IAirport
{
string city { get; set; }
string code { get; set; }
string country { get; set; }
string name { get; set; }
void CallAirTrafficControl();
}
public class Airport : IAirport
{
public string name { get; set; }
public string city { get; set; }
public string code { get; set; }
public string country { get; set; }
public Airport()
{
}
public Airport(string name, string code, string country, string city)
{
this.name = name;
this.code = code;
this.country = country;
this.city = city;
}
public void CallAirTrafficControl()
{
if (this.country.Equals("Canada") && this.code.StartsWith("Y"))
{
// Send "Bonjour!"();
}
else
{
throw new Exception("Invalid code for Canada");
}
}
}
public class UnitTest1
{
[Fact]
public void V1_Validate_ExceptionThrown_ForInvalidCanadianAirportCode()
{
var fixture = new Fixture();
var sut = fixture.Create<Airport>();
// Overwrite code and country with invalid setting for Canada.
sut.country = "Canada";
sut.code = "NOT";
Assert.ThrowsAny<Exception>(() => sut.CallAirTrafficControl());
}
[Theory]
[AutoMoqInvalidAirportDataAttribute]
public void V2_Validate_ExceptionThrown_ForInvalidCanadianAirportCode(IAirport sut, string name, string city)
{
Airport airport = new Airport(name, sut.code, sut.country, city);
Assert.ThrowsAny<Exception>(() => airport.CallAirTrafficControl());
}
}
// https://stackoverflow.com/questions/58998834/how-to-use-ifixture-buildt-with-automoqcustomization-when-t-is-an-interface
public class AutoMoqInvalidAirportDataAttribute : AutoDataAttribute
{
public static Func<IFixture> fixtureFactory = () =>
{
IFixture f = new Fixture().Customize(new AutoMoqCustomization());
f.RepeatCount = 5;
// How do you set MULTIPLE properties?
// How does one use the default AutoFixture values rather than leaving the uninitialized values as null?
// Can one pass a custom property used earlier in the Fixture creation process to another custom property used later?
f.Customize<Mock<IAirport>>(c => c.Do(m => m.SetupGet(i => i.code).Returns("NOT")));
return f;
};
public AutoMoqInvalidAirportDataAttribute() : base(fixtureFactory)
{
}
}
}
AutoFixture does not populate mock properties by default, but it can be done. These blog posts describe how to do it:
https://blog.ploeh.dk/2013/04/05/how-to-configure-automoq-to-set-up-all-properties/
https://blog.ploeh.dk/2013/04/08/how-to-automatically-populate-properties-with-automoq/
Author of AutoFixture does not recommend this approach, however, as he considers declaration of properties in interfaces a design smell.
I could not find the original discussion about this topic unfortunately, but it is hidden somewhere on StackOverflow in the comments. Maybe you will be able to find it if you go through Mark Seemann's profile.

Unit Test a method that searches element in db

I wanted to do a Unit Test for a method in the following Class:
public class SearchInfo : IDisposable
{
public List<SearchResult> SerialResults { get; set; }
public List<SearchResult> TagResults { get; set; }
/// <summary>
/// Uses the Search string to filter a resultset by Serial and Tag
/// </summary>
/// <param name="search"></param>
public SearchInfo(string search)
{
SerialResults = new List<SearchResult>();
TagResults = new List<SearchResult>();
SerialResults.AddRange(FindSerial(search));
TagResults.AddRange(FindTags(search));
}
private static IEnumerable<SearchResult> FindTags(string search)
{
List<SearchResult> result;
using (var db = new TIPWebITDataContext())
{
result = (from i in db.tblTechInventories
where i.Tag.Equals(search)
select new SearchResult()
{
SearchType = "Tag",
Key = i.Tag,
KeyCaption = i.Tag,
Name = i.tblTechItem.ItemName
}).ToList();
}
return result;
}
private static IEnumerable<SearchResult> FindSerial(string search)
{
List<SearchResult> result;
using (var db = new TIPWebITDataContext())
{
result = (from i in db.tblTechInventories
where i.Serial.Contains(search)
select new SearchResult()
{
SearchType = "Searial",
Key = i.Tag,
KeyCaption = i.Serial,
Name = i.tblTechItem.ItemName
}).ToList();
}
return result;
}
#region Implementation of IDisposable
public void Dispose()
{
SerialResults = null;
TagResults = null;
}
#endregion
}
public class SearchResult
{
public string SearchType { get; set; }
public string Key { get; set; }
public string KeyCaption { get; set; }
public string Name { get; set; }
}
}
Note:
Method Name = FindTags() returns return result.
The method checks the entered tag is present in database or not. If it is available returns the result.
How will we unit test this method?
Have mocked the Repo
Have covered scenario of "THROWS EXCEPTION"
Question is how to unit test the scenario of ALL WENT WELL ie user;s makeModel matched with repository's makeModel
Strictly speaking, this is an integration test and not a unit test.
With a unit test, you would mock the DB interaction and simple test the logic in your code.
However, I appreciate that it is easier to test in this manner and do so myself. The way to deal with this would be to inject test data into your database that gives a consistent result and assert against that. This test data can be injected in TestSetup and removed if required in TestCleanup.

Resources