mono rises unexpected compiler errors - mono

I have the following class
public class LockRequest
{
public int Id { get; set; }
public string TypeName { get; set; }
public bool Ok { get; set; }
public LockRequest ( int id, string t)
{
Id = id;
TypeName = t;
}
}
Then, it's referenced in a delegate, as follows
private static void ReceiveLockRequest<LockRequest>(PacketHeader header, Connection connection, LockRequest input )
{
LockRequest lr = new LockRequest(1, "SomeTypeName" );
Console.WriteLine( String.Format ( "{0} ", input.TypeName) );
}
When compiling, both lines from the delegate rises compiler errors.
The line with the "new()", produces "Cannot create an instance of the type class 'LockRequest' because it does not have the 'new()' constraint.
The line which would show some of the input data gives "The type 'Lockrequest' does not contains a definition for 'TypeName' and no extension method 'TypeName' ... etc".
Could someone explain why is this behaviour?
My dev environment is Ubuntu 10.04 (64 bits) and Monodevelop 2.8.6.3
TIA
Could add some info.
I changed the name of the class, and the thing compiled. The whole class is to be serialised by ProtoBuf, so it must be decorated with attributes. Here are is a sample
[ProtoContract]
public class Foo
{
[ProtoMember(1)]
public int { get; protected set; }
[ProtoMember(2)]
public string TypeName { get; protected set; }
...
Just after I added the attributes, mono stop compiling. Same erors raise again.
To test it, I commented the attributes, do a Clean All, an recompile. The errors raise again, as if MonoDevelop cached them.
I need some help more than after the initial post.
2013-10-31
Thank you, Jester. It´s an event handler, from NetworkCommDotNet library.
My faults:
1) The first error (members not recognized) raises from the fact that (somewhat astobishing) the "input" argument comes as a plain object. Casting it in another method does the trick.
2) The error regarding the instanciation: the delegate definition in the library have a where clause wich states that T must be class, but no the new() constraint.

That's not a delegate, that's a generic method.
It's not clear what you want to do and why do you need a generic method.
If you really do, then try something along the lines of:
private static void ReceiveLockRequest<T>(PacketHeader header, Connection connection, T input) where T:LockRequest
PS: your development environment is very old, consider upgrading.

Related

RavenDB SaveChanges() not saving properties on derived class ([DataMember] used in other class)

I've recently upgraded to build 2230, and things are working just fine. However, I just updated the RavenDB .NET client assemblies and now I'm having this issue.
This code has been in place for a year or so. This is how I'm saving:
public void Save(EntityBase objectToSave)
{
using (IDocumentSession session = GetOptimisticSession())
{
session.Store(objectToSave, objectToSave.Etag);
session.SaveChanges();
}
}
And this is the object I'm saving.
public class InstallationEnvironment : EntityBase
{
public string Name { get; set; }
public int LogicalOrder { get; set; }
}
Now the base class:
public class EntityBase : NotifyPropertyChangedBase
{
public string Id { get; set; } // Required field for all objects with RavenDB.
}
The problem is that the base class property (Id) is getting persisted in RavenDB, but the derived properties (Name, LogicalOrder) are not.
Why would only the base class properties be saved in RavenDB?
Got it. Through trial and error, I noticed that one derived property was being saved (on a different class than the one shown in my question), and that property was decorated with the [DataMember] attribute. I just recently added it because I'm creating a WCF service for my app, and I started by using that attribute on one property for testing.
As Ayende states here, you have to use [DataMember] on all properties, or on none of them. If [DataMember] exists on a property, all others will be ignored.
Note: This was a problem for me even though [DataMember] was specified on a property in a different class. It seems like if I use [DataMember] anywhere, I have to use it for everything.

DataContract classes uninitialized at client side

I have the following class I'd like to send from my WCF (C#) service to my client (WPF):
[DataContract]
public class OutputAvailableEventArgs
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Message { get; private set; }
[DataMember]
public bool IsError { get; private set; }
public OutputAvailableEventArgs(int id) : this(id, false, "") { }
public OutputAvailableEventArgs(int id, string output) : this(id, false, output) { }
public OutputAvailableEventArgs(int id, bool isError, string output)
{
ID = id;
IsError = isError;
Message = output;
}
}
It's used by the service as follows:
var channel = OperationContext.Current.GetCallbackChannel<IClientCallback>();
channel.OutputAvailable(new OutputAvailableEventArgs(1, false, "some message"));
At the client side, the members get their default values.
I tried marking them with IsRequired attribute but now the OutputAvailable at the client is not called. The code at the service side seems to run smoothly (I didn't notice anything with the debugger).
How can I transfer a DataContract class with WCF while maintaining the members' values?
(I saw solutions that suggested to use OnSerialized and OnDeserialized but I don't need just a default constructor.)
I saw many different solutions for this problem. For other people's sake I'll write some of them down + what worked for me:
It seems that in some cases specifying the items' order solves the problem. Please see this SO question for full details.
If it's some default initialization you're after, you can use OnSerialized and OnDeserialized methods to call your initialization methods.
I also tried using the IsRequired attribute on my DataMembers but still didn't get my objects.
What worked for me was adding NameSpace property in the DataContract attribute. Apparently, In order to have the contracts be considered equal, you must set the Namespace property on the DataContract to the same value on both sides.

RhinoMocks exceptions when stubbing out Equals method

I've a problem setting up a test for an Equals method on an object.
The object in question is defined by this interface:
public interface IHours {
ITimeOfDay OpenAt { get; set; }
ITimeOfDay CloseAt { get; set; }
DateTime ValidFrom { get; set; }
DateTime ValidTo { get; set; }
bool isCovered(DateTime time);
}
and it contains references to ITimeOfDay defined such:
public interface ITimeOfDay {
DateTime Time { get; set; }
int Hour { get; }
int Minute { get; }
int Second { get; }
}
Now I want the Equals of the Hours : IHours to check the OpenAt and CloseAt IHours. To set this up I try to stub those property-values out, and just return true and false depending on what my particular test needs them to be.
[SetUp]
public virtual void SetUp() {
mocks = new MockRepository();
defaultHours = getHours();
otherHours = getHours();
}
[TearDown]
public virtual void TearDown() {
mocks.ReplayAll();
mocks.VerifyAll();
}
[Test(Description = "Equals on two Hours should regard the fields")]
public void Equals_TwoValueEqualledObjects_Equal() {
var openAt = mocks.Stub<ITimeOfDay>();
var closeAt = mocks.Stub<ITimeOfDay>();
closeAt //this is line 66, referenced in the error stacktrace
.Stub(o => o.Equals(null))
.IgnoreArguments()
.Return(true);
openAt
.Stub(c => c.Equals(null))
.IgnoreArguments()
.Return(true);
mocks.ReplayAll();
defaultHours.OpenAt = openAt;
otherHours.OpenAt = openAt;
defaultHours.CloseAt = closeAt;
defaultHours.CloseAt = closeAt;
Assert.That(defaultHours, Is.EqualTo(otherHours));
Assert.That(defaultHours.GetHashCode(), Is.EqualTo(otherHours.GetHashCode()));
}
But I get this cryptic error when I run it:
System.InvalidOperationException: Type 'System.Boolean' doesn't match the return type 'System.Collections.Generic.IList`1[NOIS.Model.Interfaces.IAircraft]' for method 'IAircraftType.get_Aircrafts();'
at Rhino.Mocks.Expectations.AbstractExpectation.AssertTypesMatches(Object value)
at Rhino.Mocks.Expectations.AbstractExpectation.set_ReturnValue(Object value)
at Rhino.Mocks.Impl.MethodOptions`1.Return(T objToReturn)
at Nois.Test.Model.Entities.HoursTest.Equals_TwoValueEqualledObjects_Equal() in HoursTest.cs: line 66
The IAircraftType interface is a part of the same namespace, but nowhere in the test, interface or implementing class is it referenced. I do not understand why it interferes. There is no reference to it as far as I can gather.
I am using
- Rhino.Mocks v3.5.0.1337
- NUnit.Framework v2.5.0.8332
Anyone have any idea?
Yeah this is complicated - the error is crazy, this has nothing to do with IAircraft. Essentially the issue is that an interface is not a class and hence does not inherit from object. In other words - closeAt does not have an Equals method to stub out.
As a matter of fact, its probably a bit of a language flub that you can even call Equals() explicitly on an object cast to an interface.
Two ways to fix this then
Don't mock the interface, mock the implementation mocks.Stub() - this does have an equals method that is virtual so your code will work.
Even better, add an Equals method to your interface. Once you do that you will be able to override it and since all classes inherit from object you won't have to implement it explcitly ever (unless you want to).
In other words
var intrface = MockRepository.GenerateStub<IInterface>();
intrface.Stub(x => x.Equals(null)).IgnoreArguments().Return(true);
Breaks when
public interface IInterface {
}
but works when
public interface IInterface {
bool Equals(object obj);
}
Unless I'm missing something, Time of Day should be a simple immutable object. So I'd just implement it as a small, tested value class. Then you can use the real Equals method.

WCF object parameter loses values

I'm passing an object to a WCF service and wasn't getting anything back. I checked the variable as it gets passed to the method that actually does the work and noticed that none of the values are set on the object at that point. Here's the object:
[DataContract]
public class Section {
[DataMember]
public long SectionID { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Text { get; set; }
[DataMember]
public int Order { get; set; }
}
Here's the service code for the method:
[OperationContract]
public List<Section> LoadAllSections(Section s) {
return SectionRepository.Instance().LoadAll(s);
}
The code that actually calls this method is this and is located in a Silverlight XAML file:
SectionServiceClient proxy = new SectionServiceClient();
proxy.LoadAllSectionsCompleted += new EventHandler<LoadAllSectionsCompletedEventArgs>(proxy_LoadAllSectionsCompleted);
Section s = new Section();
s.SectionID = 4;
proxy.LoadAllSectionsAsync(s);
When the code finally gets into the method LoadAllSections(Section s), the parameter's SectionID is not set. I stepped through the code and when it goes into the generated code that returns an IAsyncResult object, the object's properties are set. But when it actually calls the method, LoadAllSections, the parameter received is completely blank. Is there something I have to set to make the proeprty stick between method calls?
Works just fine for me - could it be a silly typo??
In your OperationContract, you define LoadAllSections but in your client code, you attach an event handler to the proxy.GetAllSectionsCompleted event - maybe that's just the wrong handler? Shouldn't it be proxy.LoadAllSectionsCompleted ??
Marc
This seems odd, but it's what happens. I had another method on the service that returned a DataTable. Whenever a method tries to return a DataTable, the parameters passed in lose their values. Take out the method, and everything works. Odd.

NHibernate add unmapped column in interceptor

I'm trying to save a mapped entity using NHibernate but my insert to the database fails because the underlying table has a column that does not allow nulls and IS NOT mapped in my domain object. The reason it isn't mapped is because the column in question supports a legacy application and has no relevance to my application - so I'd like to not pollute my entity with the legacy property.
I know I could use a private field inside my class - but this still feels nasty to me. I've read that I can use an NHibernate interceptor and override the OnSave() method to add in the new column right before my entity is saved. This is proving difficult since I can't work out how to add an instance of Nhibernate.type.IType to the types parameter of my interceptor's OnSave.
My Entity roughly looks like this:
public class Client
{
public virtual int Id { get; set; }
public virtual int ParentId { get; set; }
public virtual string Name { get; set; }
public virtual string Phone { get; set; }
public virtual string Email { get; set; }
public virtual string Url { get; set; }
}
And my interceptor
public class ClientInterceptor : EmptyInterceptor
{
public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
{
if (entity is Client)
{
/*
manually add the COM_HOLD column to the Client entity
*/
List<string> pn_list = propertyNames.ToList();
pn_list.Add("COM_HOLD");
propertyNames = pn_list.ToArray();
List<Object> _state = state.ToList();
_state.Add(false);
state = _state.ToArray();
//somehow add an IType to types param ??
}
return base.OnSave(entity, id, state, propertyNames, types);
}
}
Does anyone have any ideas on how to do this properly?
I can't say for sure since I've never actually done this (like Stefan, I also prefer to just add a private property), but can you just add a NHibernate.Type.BooleanType to the types array?
List<IType> typeList = types.ToList();
typeList.Add(new BooleanType());
types = typesList.ToArray();
EDIT
Yes, it looks like you are right; the types have an internal constructor. I did some digging and found TypeFactory:
Applications should use static
methods and constants on
NHibernate.NHibernateUtil if the
default IType is good enough. For example, the TypeFactory should only
be used when the String needs to have a length of 300 instead of 255. At this point
NHibernate.String does not get you thecorrect IType. Instead use TypeFactory.GetString(300) and keep a
local variable that holds a reference to the IType.
So it looks like what you want is NHibernateUtil:
Provides access to the full range of
NHibernate built-in types. IType
instances may be used to bind values
to query parameters. Also a factory
for new Blobs and Clobs.
typeList.Add(NHibernateUtil.Boolean);
Personally I wouldn't do it so complicated. I would add the private property and assign it a default value - finished. You could also consider a default value in the database, then you don't need to do anything else.
private virtual bool COM_HOLD
{
get { return false; }
set { /* make NH happy */ }
}
Before writing a interceptor for that I would consider to write a database trigger. Because with the Interceptor you are "polluting" your data access layer. It could make it unstable and you could have strange problems.