Class property says "File not Found" ... before even being initialized? - c#

I am having the weirdest problem right now ...
I am working on a program that tries to instantiate types (DbContext derivatives) from another project. Because the DbContexts don't simply accept standard parameters but only interfaces from that other projects I had to take some of the other project's assemblies and reference them so I could create dummy-types that implement the interfaces.
The main one is this:
class ContextConfigurationDummy:IContextConfiguration
{
#region privates
private ILogger GetLoggerDummy() => new LoggerDummy();
private ITenantSchemaResolver GetSchemaResolverDummy() => new SchemaResolverDummy();
private CultureInfo GetUserCulture() => new CultureInfo("en-US");
private DatabaseMetadata GetDbMetadata() => new DatabaseMetadata();
private IEntityValidatorFactory GetValidatorFactory() => new ValidatorFactoryDummy();
#endregion
public DbConnection GetDbConnection() => new SqlConnection(#"[insert connection string]");
public RuminantDummy GetRuminant() => new RuminantDummy();
public Func<CultureInfo> UserCulture { get; set; }
public Func<DbConnection> Connection { get; set; }
public Func<IDatabaseMappingRuminant> Ruminant { get; set; }
public Func<DatabaseMetadata> DatabaseMetadata { get; set; }
public IEntityValidatorFactory ValidatorFactory { get; set; }
public Func<ITenantSchemaResolver> TenantSchemaResolver { get; set; }
public Func<ILogger> Logger { get; set; }
public ContextConfigurationDummy()
{
UserCulture = GetUserCulture;
Connection = GetDbConnection;
Ruminant = GetRuminant;
DatabaseMetadata = GetDbMetadata;
ValidatorFactory = GetValidatorFactory();
TenantSchemaResolver = GetSchemaResolverDummy;
Logger = GetLoggerDummy;
}
}
The original interface is this:
public interface IContextConfiguration
{
Func<CultureInfo> UserCulture { get; set; }
Func<DbConnection> Connection { get; set; }
Func<IDatabaseMappingRuminant> Ruminant { get; set; }
Func<DatabaseMetadata> DatabaseMetadata { get; set; }
IEntityValidatorFactory ValidatorFactory { get; set; }
Func<ITenantSchemaResolver> TenantSchemaResolver { get; set; }
Func<ILogger> Logger { get; set; }
}
Everything was working just fine, I didn't look at that part of the code for a while, did quite a few changes to the rest (including to the project itself to adapt it for continuous integration), when I was done I started testing again and, when calling the constructor of ContextConfigurationDummy, I was faced with this:
Note how the debugger has not even tried to evaluate it yet! A "normal" error would be that the value is null and after it tries to evaluate it there would be some kind of exception. Not here. There isn't even any file being loaded in this class. Same error for all the following fields
I figured I had to have broken something while working on the project structure, so I remade the entire project, took only the code, re-referenced the assemblies, left everything at default ... and had the exact same error again. So, it has to be the code right?
Well, I reverted to an old commit through git, ran the program, everything working as it should. Great. Checked the code - the relevant parts are exactly the same, except for the Namespaces which were slightly adapted. So, not the code either?
I went back to my current commit and after trying different kinds of ways to reference the external assemblies I tried something else once again: Just for lulz I went into my Main, the Start of the program and tried to instantiate the class with exactly the same line I used to originally instantiate it: var dummy = new ContextConfigurationDummy();
It works. Everything as expected, my class just instantiates normally.
But as if this wasn't weird enough, I'll do you one better:
After calling the method in the main I kept the program running. I got back to the spot where I originally called new ContextConfigurationDummy(). Back into the constructor and ... it works there as well. Took the line out the main - doesn't work. Back in - works again.
I'm beyond stumped, please help. (and don't tell me to clean my solution, I've done so a hundred times and literally remade the entire thing) .

I'm effectively comibining answers from my own experiences and some google-fu here but.
.NET Version
Make sure you're using the same .NET version. I've had it where I've created a new project with an old .NET version and it's screwed me completely with the same issue.
Assembly Names
Make sure none of your dlls share the same name with the assembly you're bringing in. If you have two MyAssembly.dlls it could be looking for the wrong one / version. Additionally if you've updated the other project at some point, check that all your references are using the same version of a brought in dll.
Nuget Packages
Have you updated any Nuget packages in your project that are required by the other assembly also? (I've had this many times with my unit tests) if so you'll either need to update the other projects nuget packages to the same verison, or possibly add an App.Config file to tell it to use the newer version.
I've never had the same assembly names issue, but I've had the nuget package issue and the .net version issue quite a few times (It's something you just don't think about)

Related

Azure Pipeline cannot build File scoped project

I have built a solution that builds well on local and runs well on direct deploy. When I want to deploy via Pipeline I get errors like this:
Classname.cs(4,35): Error CS1514: { expected
If the structure is
namespace PostgreDataAccess.Models
{
public class ClassName
{
public string prop1 { get; set; }
public string prop2 { get; set; }
}
}
it has no problem, but If I try
namespace PostgreDataAccess.Models;
public class ClassName
{
public string prop1 { get; set; }
public string prop2 { get; set; }
}
I have series of the quoted error.
I have so many classes like this, how can I solve this problem at once without having to edit over 103 class?
Thanks
"Classname.cs(4,35): Error CS1514: { expected" This is very likely due to the new "permissions" on updated versions of C#. Is it in C# 8.0? Where namespace no longer needs the "{}"? I can't remember... But likely you built your code on the pipeline with a compiler, that works on C# 6.0 but you are locally using the newest version of C# 8.0. Either revert you namespace definitions back to pre- 8.0 OR update the pipeline compiler, like #DavidG recommended. 8.0 can still understand the syntax of 6.0 but not vice versa.

Visual studio for Mac looks into different class than referenced

After accidentally hitting rename of my skv_match class to skv_player class I have issue with my ReadMatches method. The Visual studio keeps telling me, there is no definition of methods in class skv_player when I use class skv_match instead (after I renamed the class back to skv_match).
I am desperate and don't know if I am doing something wrong or Visual studio for Mac is. Does anybody know how to solve this or did I miss something in the code?
I tried to restart the app and laptop, rebuild and clean project. I also tried deleting the figuring classes, creating them again and pasting the original content in them.
public string ReadMatches()
{
var matches = _context.skv_match.AsNoTracking();
StringBuilder sb = new StringBuilder();
if (matches == null)
{
return "No matches found";
}
else
{
foreach (var skv_match in matches)
{
sb.Append($"Match id: {skv_match.id }\r\n");
sb.Append($"Match results: {skv_match.home_team}");
sb.Append($"{skv_match.home_score }:");
sb.Append($"{skv_match.visitor_score } ");
sb.Append($" {skv_match.visitor_team }\r\n");
}
}
return sb.ToString();
}
public class skv_match
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public int id { get; set; }
public string home_team { get; set; }
public string visitor_team { get; set; }
public int home_score { get; set; }
public int visitor_score { get; set; }
}
I get error: "'skv_player' does not contain a definition for 'home_team' and no accessible extension method 'home_team' accepting a first argument of type 'skv_player' could be found (are you missing a using directive or an assembly reference?)" and same for other methods
I expect the app to just take this without any errors, yet I get error that class I am not referencing misses methods. Before I accidentally hit rename the class everything worked just fine.
Ok my apologies to everyone who took time trying to help me. There was issue in Entity framework DbContext. I don't know if I was just tiredly stupid, or mentioned missclick changed it.
For anyone trying to solve this issue, try Right click on the declaration and "Go to declaration". It will point you to the part where you define it.
To be specific, I clicked on part skv_match at var matches = _context.skv_match.AsNoTracking();

TPH EF6.0: Cannot calculate the value of expression

I have 3 classes inherited from an abstract base class:
abstract class PortTaskStep{
public Guid TaskID { get; set; }
[ForeignKey("TaskID")]
public virtual PortChangeTask PortChangeTask { get; set; }
public virtual String CompleteStep() { return string.Empty;}
}
class PortTaskStep_Add:TaskStep{}
class PortTaskStep_Modify:TaskStep{}
class PortTaskStep_Delete:TaskStep{}
public class HncNetScanContext : DbContext
{
public DbSet<PortTaskStep> PortTaskSteps { get; set; }
}
When I try to get data from table 'PortTaskSteps', the query returns :
cannot calculate the value of the expression
Some more details:
public class PortChangeTask{
public ICollection<PortTaskStep> PortTaskSteps { get; set; }
public Boolean CompleteTask(){
foreach (var portTaskStep in PortTaskSteps)
{
portTaskStep.CompleteStep();
}
}
}
The Domain assembly contains the classes mentioned above are referenced by a web project and a web site. And when I debug the function in the web site, everything goes well.However, when I debug the same function in the web project, the results is null.
The Snapshot
For another scene tested in the Web Project:
As shown in the Snapshot, I try to get "PortTaskSteps". And the result is null. However, after I uncomment the "textQuery", the result is a list of PortTaskStep.
The Snapshot
I think something is going wrong in webconfig or environment of the Web Project, however, I cannot figure out the point...:(
How can I resolve the problem?
Thanks!
Perhaps the right translation might be "Could not evaluate expression". If so, then most likely it's the problem with Visual Studio. Try to delete all your breakpoints from solution and reinsert them. If that doesn't help you, check this link: Visual Studio 2013 'Could not evaluate Expression' Debugger Abnormality.
If the problem for you appears always on both retrieving data and trying to see it in the debug mode then you might want to check your configuration (maybe you've missed mapping or something important for this table).

Modifying model causes project not to build

I'm working with code that was started by someone other than me, so I'm not entirely familiar with the structure. However, I decided I needed to change one of the variables in one of the models. I needed to switch it from
[ForeignKey("JobFunctionDemandId")]
public virtual JobFunctionDemand JobFunctionDemand { get; set; }
public int JobFunctionDemandId { get; set; }
to
[ForeignKey("SpecificRequirementId")]
public virtual SpecificRequirement SpecificRequirement { get; set; }
public int SpecificRequirementId { get; set; }
I thought this would be a relatively small change. I realized, however, that these variables correspond to tables in a database, and so I switched all instances of JobFunctionDemand and JobFunctionDemandId to SpecificRequirement and SpecificRequirementId respectively. However, now when I try to run the Update-Database command in the package manager console, I get the error "The project 'ProjectName' failed to build."
I'm guessing the issue here is that I'm modifying the structure of an existing database, but I'm not really sure how to fix it.

How do I design a specific super class

I am trying to refactor a solution to bring on board another project.
I have a Core project where common classes across projects reside.
I've tried to simpify my question by using 2 imaginary projects: Holidays and Weather...
I have a file load process setup for the Holidays project which has the following 2 classes:
public class Job
{
public virtual string CreatedBy { get; set; }
public virtual DateTime? CreatedDate { get; set; }
public virtual Security Security { get; set; }
protected IList<File> _files = new List<File>();
public virtual IEnumerable<File> Files
{
get { return _files; }
}
}
public class File
{
public virtual string FileName { get; set; }
public virtual FileType FileType { get; set; }
public virtual FileStatusType FileStatusType { get; set; }
public virtual Job Job { get; set; }
}
The file load process for the Weather project has exactly the same structure as Holidays, except that the Jobs class does not have a Security property.
My question is, is it possible to somehow move both classes into the Core project to allow both projects to use them?
Obviously Weather does not need the Security property, so I was thinking I would have a Core.Job class without Security, and then extend the Core.Job in Holidays.Job.
But once I do that, in the Core.File class, what Job is it referring to? As it sits in the Core project it must be the Core.Job.
So would I then need to have Job and File sit in Holidays, and Weather (and any other future projects) use the Core.Job and Core.File?
I don't want the Core project to have any references to sub projects.
I am using NHibernate, and so have mapping files - adding to the complexity.
Hope this is clear enough
Thanks
You can certainly do this, but I am not sure whether it brings you true benefit:
Does the Core itself work with the base Job in any way? If it does not, implementing Job separately in each project may help you keep coupling loose, even though I'd a little redundant. In code I wrote, I have sometimes introduced unnecessary dependencies by extracting interfaces without adding true benefit. This is why I am a bit precautious.
In case Core does acutal work with it, the part to refactor into the common base Job is perhaps the interface it works with.
You may think of an interface instead of a base class. Security may semantically belong to another interface. Moreover, you hand over a lot of control over your classes to the Core.
Do you ever hand a job from one project to another (or are they mapped to the same DB table via NHibernate?)? If you don't, an internal redundant class may be fine too.
Not very clear why confuse on the soluton offered by you (assuming that I right understood you)
//Core DLL
public class Job
{
public virtual string CreatedBy { get; set; }
public virtual DateTime? CreatedDate { get; set; }
protected IList<File> _files = new List<File>();
public virtual IEnumerable<File> Files
{
get { return _files; }
}
}
in the Hollidays you have
public class HollidayJob : Job
{
public virtual Security Security { get; set; }
}
in Weather simply use a type Job, if it selfsufficient.
In this case you refer CoreDLL from Holliday project and Weather. When you serialize it via NHibernate it for HollidayJob save one field more, but when Weather reads the same table it skips that field, as don't know anything, and don't actually care abotu it.
Hope this helps.

Categories