Unable to generate a temporary class (result=1) CS0200 - c#

I have a class which is being serialized/deserialized which works fine on most machines, but doesn't work on others (I have not been able to discern the difference, though on the boxes that present an issue I see other issues which have hints of "security/permission" issue [specifically my app can create a folder, but then can't write files to it... weird, but not the main issue]).
The error I get is:
Unable to generate a temporary class (result=1).
error CS0200: Property or indexer 'Namespace.Object.ParentOrganizations' cannot be assigned to -- it is read only
The following is the property:
public List<long> ParentOrganizations
{
get
{
return m_OrganizationIDs;
}
internal set
{
m_OrganizationIDs = value;
}
}
And if I change the "set" to public it does work, but I want to know why I have to do this on only a few specific boxes... so I can help assess why this and the other weird issues are occurring. I figure fixing a single weird issue at a time in my app is more of a hassle (and likely wrong) versus finding and resolving a system configuration issue.
UPDATE: Giving localMachine\Everyone full permissions to the executing folder resolves this issue as well, but is not a good long-term solution.

Assuming you are using one of the Common serializers, you are facing the problem that the serializer self is simply not able to set the ParentOrganizations property because the internal access modifier limit the access to all callers that are not inside the same Assembly then the property is. This causes the serializer ( that is located in an other asseambly ) to throw this exception because he is not allowed to access the property.

Related

What's the easiest way to create a managed visualiser in C#?

I have a background in C++ and recently I started working in C#.
I have written following pieces of code (in Visual Studio):
var list_Loads = database.GetData<Load>().ToList();
var test_list = list_Loads.Where(o => (o.Name.Substring(0, 3) == "123")).ToList();
When I run the program and I move my mouse over both lists, first I get the count, which is very useful, but when I ask for the entries, this is what I get:
0 : namespace.Load
1 : namespace.Load
2 : namespace.Load
...
Not very useful, as you can imagine :-)
So my question: how can I show the Name attributes of those objects?
I thought: no problem. I have a background in native visualisers, so it should be rather easy to turn this into useful information, but then it comes:
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Then I found another solution, which comes down to: "Write an entire C# project, debug, test and install it and it might work" (see documentation on "Custom visualisers of data" on the Microsoft website).
I almost choked in my coffee: writing an entire project, just for altering the view of an object??? (While, in C++, you just create a simple .natvis file, mention the classname and some configuration, launch .nvload and that's it.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
By the way, when I try to load a natvis file in Visual Studio immediate window, this is what I get:
.nvload "C:\Temp_Folder\test.natvis"
error CS1525: Invalid expression term '.'
What am I doing wrong?
Thanks in advance
OP (my emphasis):
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
If you just want to specify [DebuggerDisplay] on a type, you don't have to have access to the source code. You can make use of [assembly:DebuggerDisplay()] and control how a type appears in the debugger. The only downside is that [assembly:DebuggerDisplay()] naturally only affects the current assembly whose code your mouse is hovering over. If you wish to use the customised display in other assemblies that you own, then you must repeat the [assembly:DebuggerDisplay()] definition.
Here's an easy before-and-after example with DateTime. I picked DateTime because we generally don't have access to the source code and it has some interesting properties:
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
...which on my machine defaults to:
Maybe I'm fussy and I just want to see:
Day of the week and
Day of the year
...I can do that via:
using System.Diagnostics;
[assembly: DebuggerDisplay("{DayOfWeek} {DayOfYear}", Target = typeof(DateTime))]
...which results in:
Example:
namespace DebuggerDisplayTests
{
public class DebuggerDisplayTests
{
public DebuggerDisplayTests()
{
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
}
}
.
.
.
}
Overrides
[assembly:DebuggerDisplay()] can also be used as a means to override pre-existing [DebuggerDisplay] on a 3-rd party type. Don't like what style they have chosen? Is the type showing far too much information? Change it with [assembly:DebuggerDisplay()].

AuthnContextDeclRef Issue

I'm using the latest C# SAML2 library (4.3.1), and have been able to use it successfully with Okta; however, when trying to integrate with another identity provider, I'm getting the following error:
ArgumentException: IDX13300: 'System.String' must be an absolute Uri, was: 'System.Uri'
It seems to be complaining about the saml:AuthnContextDeclRef attribute, which has the value:
ncid/secure/form/30min/uri
I'm not sure, but I think maybe this attribute is expected to be an absolute Uri by the library. The customer says this value comes from their contract and is the same for everyone, so it can't be changed. They have other applications successfully integrated (they mentioned some are using ComponentSpace). Is there any setting I can change or fix you can provide for this to work? I've looked through the available settings and nothing looks like it is relevant. The only thing I can think to do at this point is to try another SAML library.
UPDATE:
So I was able to track the issue down to the Declaration Reference attribute not being an absolute Uri. This validation is in the Microsoft.IdentityModel.Tokens.Saml2.Saml2AuthenticationContext class which represents a portion of the Saml2 token. I agree that the best solution would be to change the Declaration Reference to an absolute Uri, but since the customer says they can't or won't change the value, I needed a solution.
I was able to download the ITFoxtec.Identity.Saml2 source code and make a few tweaks so it uses a custom Saml2Serializer that overrides the ReadAuthenticationContext method and skips the part that sets the Declaration Reference on the Authentication Context. ITFoxtec doesn’t use this property… in fact, it has code that sets it to null if it has a value, so preventing the property from getting set in the first place shouldn’t cause any issues, and it allows the SAML token to be read without triggering the validation error.
It sounds correct that the AuthnContextDeclRef value should be an absolute Uri.
Her an example of how to set a AuthnContextClassRef value:
RequestedAuthnContext = new RequestedAuthnContext
{
Comparison = AuthnContextComparisonTypes.Minimum,
AuthnContextClassRef = new string[]
{
//"https://data.gov.dk/concept/core/nsis/loa/Low"
"https://data.gov.dk/concept/core/nsis/loa/Substantial",
//"https://data.gov.dk/concept/core/nsis/loa/High"
},
}

XmlException in WCF deserialization: "Name cannot begin with '<'" - in automatic property backing fields

I have started experiencing errors in WCF deserialization today - in code which has been unchanged and working for months.
The issue is that I am getting runtime XmlExceptions saying 'Name cannot begin with the '<' character'. I have debugged into the .NET source, and it seems the error is in deserializing return objects from our WCF service calls. These objects are defined using automatic properties, and it seems the backing fields are given names like <MyProperty>k_BackingField, which is where the XmlException is coming from.
I've seen a couple of other references online where the solution people accept is "I changed my code to not use automatic properties", which isn't really acceptable to me, as I would have 100s of objects to change, (with 1000s of properties amongst them). Also, this same code was working fine when I ran it last week, and doesn't seem to affect all serialized DTOs, only some.
To make it even more frustrating, it seems mildly intermittent. On occasion this morning, there has been no exception thrown...!
Questions;
Why has this problem suddenly appeared in unchanged code and unchanged framework source?
How do I fix this without modifying all the DTOs to use fully implemented properties?
UPDATE: After a day or so of working fine, this issue has reappeared - no reason I can find why it would work/not work/work again, but here we are.
I have tracked the problem down further to be related to some code I have on my ServiceContracts using the ServiceKnownType attribute, which is used to define known types for serialization. It seems that although the types being reported with errors are not even part of the service call I am making at the time, that this error is occurring on types which are part of this known types 'publishing' behaviour.
The problem occurs when I use some proxy creation code to apply some service behaviours;
IOperationBehavior innerBehavior = new PreserveReferencesOperationBehavior(
description, this.preserveReferences, this.maxItemsInObjectGraph);
innerBehavior.ApplyClientBehavior(description, proxy);
I cannot debug the ApplyClientBehavior code as it is part of System.ServiceModel (or can I?), but something in that method is trying to validate all types I have published using my ServiceKnownType attribute, and breaking on some of them with this XmlException. I have NO IDEA why some of the types are failing - and only for some of their properties.
This is an example of the types which are getting errors reported against them;
[Serializable]
public class MyDataObject
{
public ActivitySession(string id)
{
this.Id = id;
this.IsOpen = true;
}
public string Id { get; set; }
public bool IsValid { get; set; }
}
The exception reported an error against Id -> <Id>k_BackingField cannot start with '<'
So nothing controversial in that class, and no inheritance to consider. It's not even part of a service contract, only it was previously published as a known type for serialization.
This is getting quite esoteric now, so I'm not expecting an answer, but just updating where the problem is at.
I think I have found more information to help explain this issue, (at least in so far as why the error is appearing on certain types only).
The DTOs which are getting exceptions reported against them are;
published as part of my [ServiceKnownType] attribute
marked with [Serializable]
NOT marked with [DataContract]
Adding the [DataContract] attribute to the type resolves this issue. I have no idea why, and still no idea why this error is intermittent in when it happens, but consistent in what it affects.
I looked at this question also: WCF Service Reference - Getting "XmlException: Name cannot begin with the '<' character, hexadecimal value 0x3C" on Client Side
regarding this exception:
System.Xml.XmlException: 'Name cannot begin with the '<' character,
hexadecimal value 0x3C.'
Check if you load any xml files that they are valid (e.g. do not contain typo's like < or >
If you are using services + WCF, have a look at your Service interfaces (the interfaces with ServiceContract). This will be a good starting point. Now check to see if you have any DTO parameters in methods from the interface. Go to these DTO's and see if these DTO classes have [Serializable] or [DataContract] or similar attributes. If these classes also contain automatic properties, change them the properties to the notation with your own backing field like:
private Foo _Bar;
public Foo Bar { get { return _Bar; } set { _Bar = value; } }
If you are lucky you will see the errors go away!
There seems to be a problem with automatic properties where the automatically generated backing field has a name similar to e.g. <>something, <>d_whatever or things like that. These names start with '<' character, resulting in that error.
In case of services and WCF, your service interfaces and callbacks (with datacontract) are a good place to start replacing the automatic properties. At least it gives you an idea where to start instead of replacing thousands of automatic properties.
Additionally try to catch FirstChanceExceptions by adding this code at the start of your application and write the messages to the console.
This will help a lot to see if the number of "Name cannot begin with the '<' character" messages is reduced or not.
AppDomain.CurrentDomain.FirstChanceException +=
(object source, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e) =>
{
Console.WriteLine("FirstChanceException event raised in {0}: {1}",
AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
};
https://learn.microsoft.com/en-us/dotnet/framework/app-domains/how-to-receive-first-chance-exception-notifications
This is what I found so far. Hope it helps.
I have a workaround in place now, however it's not something I can rely on -> the DTOs which are causing the problem have been removed from the [ServiceKnownType] publisher, which makes the error go away.
I'm wondering if the problem is to do with the member names I am getting exceptions on. So far I have seen it complain about;
Id
Address
UserName
It would be reasonable to expect those particular property names are in use somewhere else in the serialization or service model, causing them to be compiled differently, I guess.
I was hitting this issue today (first-chance exception, no apparent problem otherwise). In my case NetDataContractSerializer (NDCS) was serializing IFieldData[] (from CSLA.NET library). NDCS can serialize arrays, it is also able to serialize objects that don’t have [DataContract] attribute applied to it. In that case the serializer infers the contract – all public read/write properties and fields of the type are serialized. It is documented here: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-data-contracts
So in my case, one of the objects in the array had a reference to Fraction (my own class) defined as follows:
public sealed class Fraction
{
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public double Value { get; private set; }
}
It is causing WCF to throw the "Name cannot begin..." exception, which is caused by the fact that the automatic properties are using generated private fields named like <Numerator>k__BackingField. If you add [DataContract] attribute to the class, then you must explicitly mark what needs to be serialized by [DataMember] attribute. That makes the exception go away. The serializer is not touching the private fields anymore.
In my opinion, it is a bug in WCF. The inferred contract should be only using the public surface of the class, which does not have any naming problems. It should not be snooping on private fields (compiler-generated or not).
My answer supports/supplements what RJ Lohan and juFo said earlier and I upvoted their answers.
The best way to figure out which field is giving you the problem is to inspect the StackTrace as the error comes up:
The answer, in my case, was to change the auto property to have explicitly declared backing fields to avoid the possibility of this naming. So
public string ScreenName { get; set; }
becomes:
private string _screenName;
public string ScreenName { get { return _screenName; } set { _screenName = value; } }
For anyone else having this issue: If you have XmlException checked in Visual Studio's exception settings, it'll throw even if the exception will get handled in System.Runtime.Serialization. I spent a good 20 or so hours trying to work out why my code had suddenly stopped working when I turned on all exceptions - it wasn't actually a fatal exception, it was just ~1200 caught XmlExceptions.

How to pass sfx settings to the SevenZipSfx class

Does anyone know how to pass the sfx settings for the SevenZipSfx class located at http://sevenzipsharp.codeplex.com/. I need to specify what file to run, etc. I just took one of the samples e.g
;!#Install#!UTF-8!
RunProgram="setup.exe /s"
GUIMode="2"
;!#InstallEnd#!
and set it via the sfx.ModuleFileName property but its fails with null exception when I call the
sfx.MakeSfx(#"C:\a.7z", #"C:\test.exe"); inside the GetSettingsStream(...) as the settings.key is null
I don't think this is the correct way but can't seem to locate where its reading the settings from. I don't want to hard code this in the source.

NHibernate throwing "Unable to resolve property:", but property doesn't exist *ANYWHERE* in project

I'm getting a weird issue with nHibernate... I'm getting this exception:
Unable to resolve property: _Portal
when I try to commit an object graph. The strange thing is that when I search through the entire solution, I don't seem to have this particular property ANYWHERE within the project?!
Has anyone run into this particular case, and if so, what did they do to resolve?
I've ran into the same issue after upgrading nHibernate to 3.3 (from 3.1), as well as associated libraries (including FluentNhibernate). I have a parent object with a child collection, and when modifying the child collection, it would throw the same exception you received (with the nonexistant "_Namespace" property name, where "Namespace" was the first section of my actual namespace).
In our case, switching to SaveOrUpdate() is not an option, as we actually have a version of this object loaded in session as well, so we need Merge().
I don't know what other similarities there might be. For us it's a parent object with a child collection, using FluentNhibernate. Mapping on the parent object is Cascade.AllDeleteOrphan() for the child, and for the child to the parent, Cascade.None().
Unfortunately I can't find any other reports of this bug, so the solution for us was to just revert back to nHibernate 3.1 (and the associated binaries, like FluentNhibernate and Iesi.Collections). That's the only change, and then it works fine again.
Update on bug logged in JIRA [3234].
There is a bug logged for this in JIRA. The issue has not received any priority yet. Perhaps if you are experiencing this issue you can create an account and vote for the bug to be fixed.
https://nhibernate.jira.com/browse/NH-3234
Update on workaround posted for bug JIRA [3234].
As per Ondrej's comment on the bug, overriding the default merge listener on the session configuration with this code solves the issue for now. I am sure with the workaround posted it will be fixed officially soon.
public class UniDirectionalMergeFixListener : DefaultMergeEventListener
{
protected override IDictionary GetMergeMap(object anything)
{
var cache = (EventCache)anything;
var result = IdentityMap.Instantiate(cache.Count);
foreach (DictionaryEntry entry in cache)
result[entry.Value] = entry.Key;
return result;
}
}
So I solved my issue, but I'm not sure why this was the resolution.
In my project, I've abstracted out the use of nHibernate to be in its own project (*.Objects.nHibernate is the namespace). I did this because the client I work with doesnt' typically like using nHibernate, and I'm trying to get them onboard with using it.
What was happening is that this project has a few data models that are append only in the system... e.g., we never do an update. So, my "Repository" has to take that into account.
In my Commit() function within the repository, I serialize the object graph and then deserialize it to make a copy of the object for saving. What I was doing was saying to the session "_Session.Merge(...)", when I needed to say "_Session.SaveOrUpdate(...)" to get things to commit to the database properly... unsure why that made a difference, but that was the answer to the past two days.
Thx. for your help Rippo & Nickolay!
The workaround for this issue is to derive from DefaultMergeEventListener and override the following method like so:
protected override IDictionary GetMergeMap(object anything)
{
var cache = (EventCache) anything;
var result = IdentityMap.Instantiate(cache.Count);
foreach (DictionaryEntry entry in cache)
{
result[entry.Value] = entry.Key;
}
return result;
}
Then simply use this custom event listener when you construct your SessionFactory. I have posted additional details to the related NHibernate bug report: NH-3234
Few things to check:-
Do you have a backing field called _Portal on your domain?
Also does the WORD portal exist anywhere within your solution?
Do a clean solution and see what DLL's are left in any of your BIN folders.
Is your NHibernate configuration being serialized after it has been built? If so check you are using the latest version.
HTH
One more idea. NHibernate allow you to specify in mapping how to access your backing field or property. For example <property access="nosetter.pascalcase-underscore" name="Timestamp" /> will make NHibernate to set value through field _Timestamp. Do you have such access specifiers in your mapping?

Categories