How do you choose an ideal hash function for GetHashCode - gethashcode

What hash function would work for a set of ints that range from say 0-10000? The built-in stuff is a collide-a-thon in this scenario.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
using Xunit.Abstractions;
namespace Solution.Tests
{
public class HashCodeCollisions
{
public HashCodeCollisions (int field1, int field2, int field3, int field4)
{
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
}
public int Field1 { get; set; }
public int Field2 { get; set; }
public int Field3 { get; set; }
public int Field4 { get; set; }
public override int GetHashCode () => HashCode.Combine (Field1, Field2, Field3, Field4);
}
public class CreateHashCodeCollisions
{
public CreateHashCodeCollisions (ITestOutputHelper output)
{
Console.SetOut (new Converter (output));
}
[Fact]
public void Find_HashCode_Collisions ()
{
HashSet<int> crashTestDummy = new HashSet<int> ();
int n = 100; // needs to work for 0-10000
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
for (int l = 0; l < n; l++)
{
int hashCode = new HashCodeCollisions (i, j, k, l).GetHashCode ();
bool added = crashTestDummy.Add (hashCode);
if (!added)
{
Console.WriteLine (string.Format ("{0} {1} {2} {3} => {4}", i, j, k, l, hashCode));
}
}
}
}
}
}
}
public class Converter : TextWriter
{
ITestOutputHelper _output;
public Converter (ITestOutputHelper output)
{
_output = output;
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
public override void WriteLine (string message)
{
_output.WriteLine (message);
}
public override void WriteLine (string format, params object[] args)
{
_output.WriteLine (format, args);
}
public override void Write (char value)
{
}
}
}

Related

Entity Framework saving in the write DBSet from abstract elements

net web app in witch database first and in my models they made the join tables as models. The thing that i want to do is that when i save ore edit a normal model i want to be able to update the relationships ass well. The problem is that i have a lot of repetitive code.For instance:
for (int i = 0; i < formationVM.Traits_.Length; i++)
{
_context.FormationTraits.Add(new FormationTrait(formationVM.Formation_, await _context.Traits.FirstOrDefaultAsync(q => q.Id == formationVM.Traits_[i])));
}
for (int i = 0; i < formationVM.Factions_.Length; i++)
{
_context.FactionFormations.Add(new FactionFormation(await _context.Factions.FirstOrDefaultAsync(q => q.Id == formationVM.Factions_[i]), formationVM.Formation_));
}
for (int i = 0; i < formationVM.Items_.Length; i++)
{
_context.ItemFormations.Add(new ItemFormation(await _context.Items.FirstOrDefaultAsync(q => q.Id == formationVM.Items_[i]), formationVM.Formation_));
}
So i want to make a single function that dose all the 3 repetitive task.
I thought of using abstraction in order to do this.
public interface IJointModel
{
public int IdLeft { get; set; }
public int IdRight { get; set; }
public IModel_ GetIdNavigationLeftModel();
public void SetIdNavigationLeftModel(IModel_ modelLeft);
public IModel_ GetIdNavigationRightModel();
public void SetIdNavigationRightModel(IModel_ modelRight);
public void saveYourself(TotalWarWanaBeContext context);
}
public interface IModel_
{
public int Id { get; set; }
}
public partial class Formation : IModel_
public partial class Trait :IModel_
public partial class FormationTrait : IJointModel{
public FormationTrait(Formation formation, Trait trait)
{
this.IdFormationNavigation = formation;
this.IdTraitNavigation = trait;
this.IdRight = trait.Id;
this.IdLeft = formation.Id;
}
[ForeignKey("IdFormationNavigation")]
[Column("IdFormation")]
public int IdLeft { get; set; }
[ForeignKey("IdTraitNavigation")]
[Column("IdTrait")]
public int IdRight { get; set; }
public virtual Formation IdFormationNavigation { get; set; }
public virtual Trait IdTraitNavigation { get; set; }
#region "Get_set_IJoinModel"
public IModel_ GetIdNavigationLeftModel()
{
return this.IdFormationNavigation;
}
public IModel_ GetIdNavigationRightModel()
{
return this.IdTraitNavigation;
}
public void SetIdNavigationLeftModel(IModel_ modelLeft)
{
this.IdFormationNavigation = (Formation)modelLeft;
}
public void SetIdNavigationRightModel(IModel_ modelRight)
{
this.IdTraitNavigation = (Trait)modelRight;
}
#endregion
public void saveYourself(TotalWarWanaBeContext context)
{
context.FormationTraits.Add(this);
}
}
The end goal is so that i can make the function
private void saveRelation(string jointableType/* ore something like this*/, IModel anyModel, int[] idLeftModels){
for(int i = 0; i < idLeftModels.Length; i++){
IJointModel jointModel = new IJointModel.TypeOf(jointTableType);
jointModel.setIdNavigationLeftModel = anyModel;
jointModel.setItNavigtionRightModel = _context.DbSetofTypeINeed.where(t => t.id = idLeftModels[i];
jointModel.SaveYourself();
}
How can I make the function saveRelation save in the database any Model that inherits from IJoinModel. Sorry if the title is miss representative but i didn't know how to phrase it

Reset ReactiveUI ObservableAsPropertyHelper Value

I am building a simple DateTime calculator using a ReactiveUI ReactiveObject viewmodel.
It has a calculate command that calculates a value and correctly updates the result backed by an ObservableAsPropertyHelper<DateTime?> field.
I also have a ReactiveUICommand that is supposed to reset all of the UI values.
The problem that I am running into is how to reset the readonly "Result" value.
public class VM : ReactiveObject
{
private readonly ObservableAsPropertyHelper<DateTime?> _result;
[Reactive]
public DateTime Start { get; set; } = DateTime.Now;
[Reactive]
public int Days { get; set; } = 1;
public DateTime? Result => _result.Value;
public ReactiveCommand<Unit, DateTime?> CalculateCommand { get; }
public ReactiveCommand<Unit, Unit> ResetCommand { get; }
public VM()
{
CalculateCommand = ReactiveCommand
.CreateFromTask<Unit, DateTime?>((_, cancellationToken) => CalculateAsync(cancellationToken));
_result = CalculateCommand.ToProperty(this, nameof(Result));
// everything above this works.
ResetCommand = ReactiveCommand.Create(() =>
{
Start = DateTime.Now;
Days = 1;
// how do I reset "_result" or "Result" back to null???
});
}
private Task<DateTime?> CalculateAsync(CancellationToken _)
{
// to be replaced by an API call later.
return Task.FromResult<DateTime?>(Start.AddDays(Days));
}
}
How do I reset a value backed by an instance of ObservableAsPropertyHelper?
Figured this out myself:
namespace WpfApp4;
using System.Reactive.Linq;
using System.Threading.Tasks;
using ReactiveUI;
using System;
using System.Reactive;
public class MainViewModel : ReactiveObject
{
public ReactiveCommand<Unit, DateTime?> StartCommand { get; }
public ReactiveCommand<Unit, DateTime?> ResetCommand { get; }
private DateTime _start = DateTime.Now;
private int _processingDays = 1;
private readonly ObservableAsPropertyHelper<DateTime?> _result;
public DateTime? Result => _result.Value;
public DateTime Start
{
get => _start;
set => this.RaiseAndSetIfChanged(ref _start, value);
}
public int ProcessingDays
{
get => _processingDays;
set => this.RaiseAndSetIfChanged(ref _processingDays, value);
}
public MainViewModel()
{
StartCommand = ReactiveCommand.CreateFromTask<DateTime?>(() => Task.FromResult<DateTime?>(Start.AddDays(ProcessingDays)));
ResetCommand = ReactiveCommand.Create<DateTime?>(execute: () => null);
_ = ResetCommand.Subscribe(onNext: (_) =>
{
Start = DateTime.Now;
ProcessingDays = 1;
});
_result = StartCommand.Merge(ResetCommand).ToProperty(this, nameof(Result));
}
}

EF Core and Collection ordering by specified column: move up and down

What is a best way to implement ordering in collection?
Need to support operations like move up and move down.
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public int Priority { get; set; }
public List<Item> Items { get; set; }
}
This is a console applciation which demonstrates how to move up and down elements of a list.
I hope it helps you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
public enum MoveDirection
{
Up,
Down
}
static class Program
{
static void Main(string[] args)
{
List<string> MyList = new List<string>
{
"Value 1", "Value 2", "Value 3"
};
DisplayList(MyList);
Console.WriteLine("----------------");
Move(MyList, 1, MoveDirection.Down);
DisplayList(MyList);
Console.WriteLine("----------------");
Move(MyList, 2, MoveDirection.Up);
DisplayList(MyList);
Console.ReadLine();
}
public static void Move(List<string> list, int iIndexToMove, MoveDirection direction)
{
if (direction == MoveDirection.Up && iIndexToMove > 0)
{
var old = list[iIndexToMove - 1];
list[iIndexToMove - 1] = list[iIndexToMove];
list[iIndexToMove] = old;
}
else if(direction == MoveDirection.Down && iIndexToMove < list.Count() - 1)
{
var old = list[iIndexToMove + 1];
list[iIndexToMove + 1] = list[iIndexToMove];
list[iIndexToMove] = old;
}
}
public static void DisplayList(List<string> list)
{
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
}

Entity Framework: Entity with composite key as PK/FK throws exception

On escalado, throws the exception. It throws with or wihtout Include.
static void Main(string[] args)
{
try
{
using (var context = new CKContext())
{
var servReprosWithIncludes = context.ServicioRepro
.Include(p => p.Categoria)
.ToList();
var escalado = context.EscaladoPrecio
//.Include(p => p.Servicio)
.ToList();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
InvalidOperationException: The value of a property that is part of an object's key does not match the corresponding property value stored in the ObjectContext. This can occur if properties that are part of the key return inconsistent or incorrect values or if DetectChanges is not called after changes are made to a property that is part of the key.
The mapping of EscaladoPrecio:
public class EscaladoPrecioMapping : EntityTypeConfiguration<EscaladoPrecio>
{
public EscaladoPrecioMapping()
{
base.HasKey(p => new { p.Desde, p.Hasta, p.ServicioReproId });
base.HasRequired(p => p.Servicio)
.WithMany()
.HasForeignKey(p => p.ServicioReproId);
base.ToTable("PreciosServicioReprografia");
}
}
The entity ServicioRepro is a part from TPT hierarchy. Looks like:
public class ServicioRepro : Producto
{
public bool IncluirPrecioClick { get; set; }
public bool IncluirPrecioPapel { get; set; }
public bool HayPapel { get; set; }
public bool HayImpresion { get; set; }
public bool PrecioPorVolumen { get; set; }
//public virtual ICollection<EscaladoPrecio> EscaladoPrecio { get; set; }
public virtual CategoriaServicioRepro Categoria { get; set; }
public virtual ServicioReproFacturacionType ServicioReproFacturacionType { get; set; }
}
On this entity you can't see the key, because the base entity Producto have it.
The entity EscaladoPrecio have 3 PK: desde, hasta and Servicio. Servicio is PK and FK.
The entity looks like (methods, overrides and members have been removed to reduce the code):
public class EscaladoPrecio : IComparable<EscaladoPrecio>, IComparable<int>, IComparable, IEntity
{
#region Declarations
private int _desde;
private int _hasta;
private double _precio;
private int _cada;
#endregion Declarations
#region Constructor
public EscaladoPrecio()
: this(1, 1, 0, 0)
{ }
public EscaladoPrecio(int desde, int hasta, double precio)
: this(desde, hasta, precio, 0)
{ }
public EscaladoPrecio(int desde, int hasta, double precio, int cada)
{
_desde = desde;
_hasta = hasta;
_precio = precio;
_cada = cada;
}
#endregion Constructor
#region Properties
public int Desde
{
get
{
return _desde;
}
set
{
_desde = value;
}
}
public int Hasta
{
get
{
return _hasta;
}
set
{
_hasta = value;
}
}
public double Precio
{
get
{
return _precio;
}
set
{
_precio = value;
}
}
public int Cada
{
get
{
return _cada;
}
set
{
_cada = value;
}
}
#endregion Properties
private int _ServicioReproId;
public int ServicioReproId
{
get
{
if (Servicio != null)
{
_ServicioReproId = Servicio.Id;
return Servicio.Id;
}
else
return 0;
}
set
{
_ServicioReproId = value;
}
}
public virtual ServicioRepro Servicio { get; set; }
}
Why throws the exception?
Why are you doing this:
public int ServicioReproId
{
get
{
if (Servicio != null)
{
_ServicioReproId = Servicio.Id;
return Servicio.Id;
}
else
return 0;
}
set
{
_ServicioReproId = value;
}
}
Your part of the key property ServicioReproId is returning 0 here potentially although it has been loaded (and stored in the context) with a value != 0 (probably). I think this part of the exception is refering to this problem: "This can occur if properties that are part of the key return inconsistent or incorrect values."
Better leave it an automatic property:
public int ServicioReproId { get; set; }
try to initialice his virtual property in the constructor of the class EscaladoPrecio()

Why is reading a Dapper IEnumerable(dynamic) an order of magnitude slower than reading an IEnumerable(IDataRecord)?

In comparing Dapper with the Enterprise Library Data Access Access block for getting data via stored procedure. I see an overall performance benefit of about 40% when using Dapper, which is somewhat surprising.
However, when comparing iteration and getting data from an IEnumerable(IDataRecord) vs. IEnumerable(dynamic), IEnumerable(IDataRecord) is approximately an order of magnitude faster. Is this behavior well understood and to be expected or is there something not right here?
The results:
IEnumerable(IDataRecord)
IEnumerable(dynamic) - using dapperObject.propertyName
Now the interesting part, when using dapperObject["propertyName"], the performance is on par with IDataRecord. Not at all what I would have expected.
The relevant portion of the profiling code
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper.DataAccess;
using System.Data;
using tophat;
namespace Dapper.TestRunner
{
class Program
{
static void Main(string[] args)
{
var connectionString = "data source=WEBDBdev3,1866; User id=hsbmhw;Password=gEner4Y&M;Persist Security Info='true'; initial catalog=myhomeworks;";
//The following uses Tophat to create a singleton connection instance.
Database.Install<SqlServerConnectionFactory>(connectionString, ConnectionScope.ByRequest);
DapperTest();
DapperTest2();
EnterpriseLibraryIDataRecordTest();
}
private static void DapperTest()
{
for (int i = 0; i < 100; i++)
{
IEnumerable<dynamic> users = MyRepository.GetUsersDapper();
PopulateBusinessObjectsDynamic(users);
}
}
private static void DapperTest2()
{
for (int i = 0; i < 100; i++)
{
IEnumerable<dynamic> users = MyRepository.GetUsersDapper();
PopulateBusinessObjectsDynamic2(users);
}
}
private static void EnterpriseLibraryIDataRecordTest()
{
for (int i = 0; i < 100; i++)
{
IEnumerable<IDataRecord> users = MyRepository.GetUsersEntlib();
PopulateBusinessObjectsIDataRecord(users);
}
}
private static void PopulateBusinessObjectsDynamic(IEnumerable<dynamic> users)
{
foreach (var user in users)
{
BusinessObject bo = new BusinessObject(user);
}
}
private static void PopulateBusinessObjectsDynamic2(IEnumerable<dynamic> users)
{
foreach (var user in users)
{
BusinessObject bo = new BusinessObject(user);
}
}
private static void PopulateBusinessObjectsIDataRecord(IEnumerable<IDataRecord> users)
{
foreach (var user in users)
{
BusinessObject bo = new BusinessObject(user);
}
}
}
public class BusinessObject
{
public DateTime CreateDate { get; set; }
public String CreateDateString { get; set; }
public String FirstName { get; set; }
public bool IsApproved { get; set; }
public bool IsLockedOut { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public String LastName {get;set;}
public String Organization{get;set;}
public int OrganizationId{get;set;}
public int PersonId{get;set;}
public String ProfileLastUpdatedBy{get;set;}
public DateTime ProfileLastUpdatedDate{get;set;}
public String RoleName{get;set;}
public long RowNumber{get;set;}
public int TotalCount{get;set;}
public Guid UserId{get;set;}
public string UserName {get;set;}
public string UserStatus{get;set;}
public BusinessObject(dynamic user)
{
CreateDate=user.CreateDate;
CreateDateString = user.CreateDateString;
FirstName = user.FirstName;
IsApproved = user.IsApproved;
IsLockedOut = user.IsLockedOut;
LastActivityDate= user.LastActivityDate;
LastLoginDate = user.LastLoginDate;
LastName = user.LastName;
Organization = user.organization;
OrganizationId=user.organization_id;
PersonId = user.party_id;
ProfileLastUpdatedBy = user.ProfileLastUpdatedBy;
ProfileLastUpdatedDate = user.ProfileLastUpdatedDate;
RoleName = user.RoleName;
RowNumber = user.RowNumber;
TotalCount = user.TotalCount;
UserId = user.UserId;
UserName= user.UserName;
UserStatus = user.UserStatus;
}
public BusinessObject(bool x, dynamic user)
{
CreateDate = user["CreateDate"];
CreateDateString = user["CreateDateString"];
FirstName = user["FirstName"];
IsApproved = user["IsApproved"];
IsLockedOut = user["IsLockedOut"];
LastActivityDate = user["LastActivityDate"];
LastLoginDate = user["LastLoginDate"];
LastName = user["LastName"];
Organization = user["organization"];
OrganizationId = user["organization_id"];
PersonId = user["party_id"];
ProfileLastUpdatedBy = user["ProfileLastUpdatedBy"];
ProfileLastUpdatedDate = user["ProfileLastUpdatedDate"];
RoleName = user["RoleName"];
RowNumber = user["RowNumber"];
TotalCount = user["TotalCount"];
UserId = user["UserId"];
UserName = user["UserName"];
UserStatus = user["UserStatus"];
}
public BusinessObject(IDataRecord user)
{
CreateDate = (DateTime)user["CreateDate"];
CreateDateString = (string)user["CreateDateString"];
FirstName = (string)user["FirstName"];
IsApproved = (bool)user["IsApproved"];
IsLockedOut = (bool)user["IsLockedOut"];
LastActivityDate = (DateTime)user["LastActivityDate"];
LastLoginDate = (DateTime)user["LastLoginDate"];
LastName = (string)user["LastName"];
Organization = (string)user["organization"];
OrganizationId = (int)user["organization_id"];
PersonId = (int)user["party_id"];
ProfileLastUpdatedBy = (string)user["ProfileLastUpdatedBy"];
ProfileLastUpdatedDate = (DateTime)user["ProfileLastUpdatedDate"];
RoleName = (string)user["RoleName"];
RowNumber = (long)user["RowNumber"];
TotalCount = (int)user["TotalCount"];
UserId = (Guid)user["UserId"];
UserName = (string)user["UserName"];
UserStatus = (string)user["UserStatus"];
}
}
}
You actually seem to be running the same test twice; the input (users) is the same, from here:
private static void DapperTest()
{
for (int i = 0; i < 100; i++)
{
IEnumerable<dynamic> users = MyRepository.GetUsersDapper();
PopulateBusinessObjectsDynamic(users);
}
}
private static void DapperTest2()
{
for (int i = 0; i < 100; i++)
{
IEnumerable<dynamic> users = MyRepository.GetUsersDapper();
PopulateBusinessObjectsDynamic2(users);
}
}
And the actual "what do we do" is the same, here:
private static void PopulateBusinessObjectsDynamic(IEnumerable<dynamic> users)
{
foreach (var user in users)
{
BusinessObject bo = new BusinessObject(user);
}
}
private static void PopulateBusinessObjectsDynamic2(IEnumerable<dynamic> users)
{
foreach (var user in users)
{
BusinessObject bo = new BusinessObject(user);
}
}
So... I have to conclude "a combination of JIT, data caching (at the database server) assembly loading/validation/fusion, connection pooling, and the dynamic cache features made the second test appear faster".
Note that the dynamic side of dapper is intended for ad-hoc usage only anyway. If you wanted the optimal face of dapper, you would use Query<T>, not dynamic.
In particular, AFAIK no build of dapper supports a string indexer on the dynamic API. The object implements IDictionary<string,object> for member access, but you would need to explicitly cast to that to use it - you can't do user["PropName"] if user is typed as dynamic (if I'm wrong, please tell me!).
As it happens, the unreleased "git" code (for the dynamic API) is noticeably faster than the current "nuget" implementation - but that is a bit of a tangent to this specific question.