Labview: error 1057 when casting to more specific object - oop

I have two classes in C# compiled into a library to be imported into a LabView project.
public class Upper
{
public sbyte Signed8 { get; set; }
public char Unicode16 { get; set; }
public short Signed16 { get; set; }
public int Signed32 { get; set; }
public long Signed64 { get; set; }
public int UpperDoSomething() { return Signed32; }
}
and
public class Lower : Upper
{
public byte Unsigned8 { get; set; }
public ushort Unsigned16 { get; set; }
public uint Unsigned32 { get; set; }
public ulong Unsigned64 { get; set; }
public uint LowerDoSomething() { return Unsigned32; }
}
I keep getting error 1057:
"Type mismatch: Object cannot be cast to the specific type"
To spare anyone from downloading the file, analyzing the component "to more specific class":
Upper is connected to reference class
An unitialized Lower class is connected to target class
A property node is connected to specific class reference
(side note) for anyone who downloads the vi, there is a property connected to an indicator to not have any loose wires

You are calling the constructor of the Upper, then trying to case it to a Lower, which it isn't an instance of.
The tsc block (and generally casting to a descendant in OOP) is useful when you've passed subclass instances through code treating it as the parent class, but then have an operation that requires the subclass type. It has to have been created as an instance of the subclass though.

Related

How to map object type field in Nhibernate Auto Mapping

When trying to map, I got this error:
Association references unmapped class: System.Object
My class:
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
public virtual object Item { get; set; }
}
And the convention:
public class MyUsertypeConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance.Type.Name == "Object")
instance.CustomType<string>();
}
}
Kindly suggest how to map?
As a simple (quick, naive) solution - I would suggest to create and map real string property. And then let your setter and getter (or some AOP or listener) to do the "to/from string conversion":
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
public virtual object Item
{
get { return ... my conversion from string; }
set { ItemString = ...my conversion to string; }
}
public virtual string ItemString { get; set; }
}
A smart and preferred (but a bit more challenging) is to create CustomType - which will hide that conversion and support REUSE. Check e.g. here
NHibernate Pitfalls: Custom Types and Detecting Changes
Creating and Testing a Custom NHibernate User Type
Not a satisfactory answer. It doesn't work with class that is generated from xsd by using XML. You can try the following:
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
private object itemField;
public object Item
{
get { return this.itemField; }
set { this.itemField = value; }
}
}

WCF with abstract base class with implemented interfaces does not serialize properly?

On the service side I have an abstract base class like so:
[DataContract]
public abstract class EntityBase : IObjectState, IDatabaseMetaData
{
[NotMapped]
[DataMember]
public ObjectState ObjectState { get; set; }
#region IDatabaseMetaData Members
[DataMember] public DateTime InsertDatetime { get; set; }
[DataMember] public int InsertSystemUserId { get; set; }
[DataMember] public DateTime? UpdateDatetime { get; set; }
[DataMember] public int? UpdateSystemUserId { get; set; }
public virtual SystemUser InsertSystemUser { get; set; }
public virtual SystemUser UpdateSystemUser { get; set; }
#endregion
}
Here is an implementing class (data contract):
[DataContract(Namespace = Constants.MyNamespace)]
public class AccountClass : EntityBase
{
[DataMember] public int AccountClassId { get; set; }
[DataMember] public string AccountClassCode { get; set; }
[DataMember] public string AccountClassDesc { get; set; }
}
On the client side I have essentially duplicated contracts. Here is the Client.AccountClass:
public class AccountClass : ObjectBase
{
private int _accountClassId;
private string _accountClassCode;
private string _accountClassDesc;
public int AccountClassId
{
get { return _accountClassId;}
set
{
if (_accountClassId == value) return;
_accountClassId = value;
OnPropertyChanged(() => AccountClassId);
}
}
public string AccountClassCode
{
get { return _accountClassCode; }
set
{
if (_accountClassCode == value) return;
_accountClassCode = value;
OnPropertyChanged(() => AccountClassCode);
}
}
public string AccountClassDesc
{
get { return _accountClassDesc; }
set
{
if (_accountClassDesc == value) return;
_accountClassDesc = value;
OnPropertyChanged(() => AccountClassDesc);
}
}
}
..and here is the parts of ObjectBase that matter:
public abstract class ObjectBase : IObjectState, IDatabaseMetaData
{
public ObjectState ObjectState { get; set; }
#region IDatabaseMetaData Members
public DateTime InsertDatetime { get; set; }
public int InsertSystemUserId { get; set; }
public DateTime? UpdateDatetime { get; set; }
public int? UpdateSystemUserId { get; set; }
#endregion
}
When I debug the service in my WcfMessageInspector.BeforeSendReply, I can see the message correctly sending the IObjectState and IDatabaseMetaData values. However, on the client side, they are always null (or default values). I have tried using KnownTypes, applying the namespace to the abstract class. The only way I can serialize everything correctly is to get rid of the interfaces and base classes all together and put the properties directly on the Client/Server AccountClass object. What am I missing here? Thanks.
Update 1
This seems to be a namespace thing. If I move my EntityBase and ObjectBase into the same CLR Namespace, everything works (with no KnownType attributes). In my client contract's AssemblyInfo.cs file I have this:
[assembly: ContractNamespace(Constants.MyNamespace, ClrNamespace = "Project.Name.Client.Entities")]
I tried adding ContractNamespaces here to no avail. Like I said, unless the EntityBase and ObjectBase are in the same namespace, it won't work. However, this is a problem for me because it creates a circular reference, unless I move a lot of stuff around.
Any idea how I can see what the full data contract (namespaces, DataMembers, etc) looks like just before/after serialization on the client/server? I tried intercepting the OnSerializing event without much luck. Thanks again.
This was a namespace issue.
I explicitly add the correct namespace to all parties involved and everything works great. One thing I notice is that the ContractNamespace's ClrNamespace in your AssemblyInfo.cs file should match the AssemblyTitle. Also, putting more than one ContractNamespace in the AssemblyInfo.cs does nothing. For example, I was doing this:
[assembly: ContractNamespace(Constants.MyNamespace, ClrNamespace = "Company.Project.Client.Entities")]
[assembly: ContractNamespace(Constants.MyNamespace, ClrNamespace = "Company.Project.Client.Entities.Core")]
Any POCO in the Company.Project.Client.Entities.Core would not serialize correctly until I explicitly put the DataContract namespace on it like so
[DataContract(Namespace = Constants.MyNamespace)]
public class SomeObject
{
[DataMember] public string SomeProperty { get; set; }
//..etc
}
Alternatively, I could have restructured the project so SomeObject was in the Company.Project.Client.Entities namespace and that would have worked.
Finally, the most helpful thing to debugging this was looking at the WSDL, and then using a custom IDispatchMessageInspector to see the actual messages AfterReceiveRequest and BeforeSendReply. Hopefully this helps someone.

Parameter xxx of domain operation entry xxx must be one of the predefined serializable types

I get this webservice error sometimes on a SL5 + EF + WCF app.
"Parameter 'role' of domain operation entry 'AddUserPresentationModelToRole' must be one of the predefined serializable types."
here is a similar error, however his solution doesn't work for me.
I have the codegenned DomainService which surfaces the database entities to my client:
[EnableClientAccess()]
public partial class ClientAppDomainService : LinqToEntitiesDomainService<ClientAppUserEntitlementReviewEntities>
{
public IQueryable<Account> GetAccounts()
{
return this.ObjectContext.Accounts;
}
//..etc...
and my custom service which is surfacing a Presentation model, and db entities.
[EnableClientAccess]
[LinqToEntitiesDomainServiceDescriptionProvider(typeof(ClientAppUserEntitlementReviewEntities))]
public class UserColourService : DomainService
{
[Update(UsingCustomMethod = true)]
public void AddUserPresentationModelToRole(UserPresentationModel userPM, Role role, Reviewer reviewer)
{
...
}
public IDictionary<long, byte> GetColourStatesOfUsers(IEnumerable<RBSUser> listOfUsers, string adLogin)
{
//....
}
}
and the PresentationModel:
public class UserPresentationModel
{
[Key]
public long UserID { get; set; }
public byte UserStatusColour { get; set; }
public string MessageText { get; set; }
[Include]
[Association("asdf", "UserID", "UserID")]
public EntityCollection<Account> Accounts { get; set; }
public DateTime AddedDate { get; set; }
public Nullable<long> CostCentreID { get; set; }
public DateTime? DeletedDate { get; set; }
public string EmailAddress { get; set; }
public long EmployeeID { get; set; }
public string FirstName { get; set; }
public Nullable<bool> IsLeaver { get; set; }
public string LastName { get; set; }
public DateTime LastSeenDate { get; set; }
public string LoginDomain { get; set; }
public string LoginName { get; set; }
public byte WorldBuilderStatusID { get; set; }
}
Also cannot get the solution to reliably fail. It seems whenever I change the service slightly ie make it recompile, everything works.
RIAServices unsupported types on hand-built DomainService - seems to be saying the same thing, that decorating the hand built services with the LinqToEntitiesDomainServiceDescriptionProvider should work.
Possible answer here will post back here too with results.
From Colin Blair:
I am a bit surprised it ever works, I don't think I have seen anyone trying to pass additional entiities into a named update before. It might be a bug in RIA Services that it is working at all. What are you trying to accomplish?
Side note, you have a memory leak with your ObjectContext since it is not getting disposed of correctly. Is there a reason you aren't using the LinqToEntitiesDomainSerivce? It would take care of managing the ObjectContext's lifetime for you.
Results:
1) This makes sense. Have refactored out to more sensible parameters now (ints / strings), and all working.
2) Have brought together my 3 separate services into 1 service, which is using the LinqToEntitiesDomainSerivce. The reason I'd split it out before was the assumption that having a CustomUpdate with a PresentationModel didn't work.. and I had to inherit off DomainService instead. I got around this by making a method:
// need this to avoid compile errors for AddUserPresentationModelToRole.. should never be called
public IQueryable<UserPresentationModel> GetUserPresentationModel()
{
return null;
}

To those having the Object graph for type 'xxx' contains cycles

This is more of a share knowledge than anything else. Wasn't sure if I was supposed to make it a question.
So I have multiple issues with the following error Object graph for type 'xxx' contains cycles
There are many ways the internet says to fix it, for instance adding the IsReference=true attribute, creating your own custom attributes, etc.
For me I find the most simplest way is by just making the child parent object have a private setter.
ie.
public ParentObject objectName { get; private set; }
More in depth example.
public class Parent()
{
public Guid ID { get; set; }
public string Name { get; set; }
}
public class Child()
{
public Guid ID { get; set; }
public Parent Parent { get; private set; }
public int ChildProp { get; set; }
}
I'll give the credit to this post correct answer(in green), for helping me figure it out.
http://forums.asp.net

ria domain service is setting a client-side property on callback

I'm using RIA domain services, with entity framework 4 and silverlight 4. When I save changes, when the service call returns, some domain service functions are called wich sets a value to "" that should not be changed at all.
I have two entities
service.metadata.cs:
public partial class EntityA
{
[Key]
public Guid EntityA_Id { get; set; }
public string Name { get; set; }
public int EntityB_Id { get; set; }
[Include]
public EntityB entityB { get; set; }
}
public partial class EntityB
{
[Required]
public string Name { get; set; }
public int EntityB_Id { get; set; }
public EntityCollection<EntityA> entityA { get; set; }
}
On the client side I have a Extra property on EntityA to expose the Name property od EntityB. The server side and domain service never need to know about this property, its for GUI only.
public partial class EntityA
{
//Tags I have tried:
//[IgnoreDataMember]
//[XmlIgnore]
//[Ignore]
//[Exclude]
public string NameOf_EntityB
{
get
{
return this.entityB == null ? string.Empty : this.entityB.Name;
}
set
{
this.entityB.Name = value;
}
}
}
If I edit the entityA's name and call serviceContext.SubmitChanges(), when the call returns some domain service process is setting the EntityA.NameOf_EntityB = ""; So from a user point of view, they save one value and the other blanks out.
I need to stop this from happening. I have tried various data attributes, but they either don't work on the client side, or have no effect.
Any idea what to do to stop the domain service from changing this value?
here's the callstack right before the value is changed:
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.ObjectStateUtility.**ApplyValue**(object o, object value, System.Reflection.PropertyInfo propertyInfo, System.Collections.Generic.IDictionary<string,object> originalState, System.ServiceModel.DomainServices.Client.LoadBehavior loadBehavior) + 0x74 bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.ObjectStateUtility.ApplyState(object o, System.Collections.Generic.IDictionary<string,object> stateToApply, System.Collections.Generic.IDictionary<string,object> originalState, System.ServiceModel.DomainServices.Client.LoadBehavior loadBehavior) + 0x330 bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.Entity.ApplyState(System.Collections.Generic.IDictionary<string,object> entityStateToApply, System.ServiceModel.DomainServices.Client.LoadBehavior loadBehavior) + 0x68 bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.Entity.Merge(System.ServiceModel.DomainServices.Client.Entity otherEntity, System.ServiceModel.DomainServices.Client.LoadBehavior loadBehavior) + 0x5a bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.DomainContext.ApplyMemberSynchronizations(System.Collections.Generic.IEnumerable<System.ServiceModel.DomainServices.Client.ChangeSetEntry> changeSetResults) + 0x10e bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.DomainContext.ProcessSubmitResults(System.ServiceModel.DomainServices.Client.EntityChangeSet changeSet, System.Collections.Generic.IEnumerable<System.ServiceModel.DomainServices.Client.ChangeSetEntry> changeSetResults) + 0x262 bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.DomainContext.CompleteSubmitChanges(System.IAsyncResult asyncResult) + 0x1cb bytes
System.ServiceModel.DomainServices.Client!System.ServiceModel.DomainServices.Client.DomainContext.SubmitChanges.AnonymousMethod__5() + 0x2e bytes
Edit:
found a work around for now. In the callback of the ServiceContext.submitChanges() call I can call ServiceContext.RejectChanges() to undo the change that was made to EntityB. I don't trust this solution though as other changes could have been made before the async call returns and those changes would be rejected as well. The ideal solution would be to have that value ignored and NOT set at all
You may need to tell WCF RIA a little more about your entities with some attributes:
public partial class EntityA
{
[Key]
public Guid EntityA_Id { get; set; }
public string Name { get; set; }
public int EntityB_Id { get; set; }
[Include]
[Association("EntityA-EntityB", "EntityA_Id", "EntityB_Id", IsForeignKey=false)]
public EntityB entityB { get; set; }
}
public partial class EntityB
{
[Required]
public string Name { get; set; }
[Key]
public int EntityB_Id { get; set; }
public Guid EntityA_Id { get; set; }
[Include]
[Association("EntityA-EntityB", "EntityA_Id", "EntityB_Id", IsForeignKey=true)]
public EntityCollection<EntityA> entityA { get; set; }
}
Here's my solution:
private bool isExpanded = false;
public bool IsExpanded
{
get { return isExpanded; }
set
{
string stack = (new System.Diagnostics.StackTrace()).ToString();
if (!stack.Contains("ObjectStateUtility.ApplyState") && isExpanded != value)
{
isExpanded = value;
RaisePropertyChanged("IsExpanded");
}
}
}