K09
K09

Reputation: 201

MSMQ Unable to cast object of type

I get the below error message when reading a MSMQ message...

Unable to cast object of type 'System.ServiceModel.MsmqIntegration.MsmqMessage`1[MSMQLibrary.MyEvents+Dashboard_Message]' to type 'Dashboard_UserDetail'.

Error occurs here...

MyEvents.Dashboard_UserDetail messageTest =   
    (MyEvents.Dashboard_UserDetail)dashboardMessage;

Why is this?

[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
public void ProcessMSMQMessage(MsmqMessage<MyEvents.Dashboard_Message> msg)
{
    switch (msg.Body.GetType().Name)
    {
        case "DashboardTest":
            MyEvents.Dashboard_UserDetail messageTest = 
                (MyEvents.Dashboard_UserDetail)dashboardMessage;
            using (UpdateDashboardQueriesDataContext updateDashboardQueriesDataContext = new UpdateDashboardQueriesDataContext())
            {
                updateDashboardQueriesDataContext.UpdateData(messageTest.ID, messageTest.StartDate);
            }
            break;
        }
    }


public class MyEvents
{
    [Serializable]
    [DataContract]
    public class Dashboard_Message
    {
        public Dashboard_Message();
    }

    [Serializable]
    [DataContract]
    public class Dashboard_UserDetail : DashboardEvents.Dashboard_Message
    {
        public Dashboard_UserDetail();
        public Dashboard_UserDetail(string thisID, DateTime thisPeriod);

        public DateTime Period { get; set; }
        public string ID{ get; set; }
    }    
}

Upvotes: 1

Views: 151

Answers (1)

tom redfern
tom redfern

Reputation: 31760

Because you haven't told the service to expect your derived type in the request. The service expects type Dashboard_Message in the message but instead it is receiving an object with type Dashboard_UserDetail.

You have to use ServiceKnownType attribute to specify that your service should expect other types in the request.

Upvotes: 1

Related Questions