Handling custom datacontract serialization in WCF Rest endpoint - wcf

I want to uses XML attributes instead of elements in xmlrequest and xmlresponse, I implemented IXmlSerializable as follows:
public partial class Id : IXmlSerializable
{
/// <remarks/>
[XmlAttribute]
public string lmsId;
/// <remarks/>
[XmlAttribute]
public string unitId;
/// <remarks/>
[XmlAttribute]
public string lmsPresId;
/// <remarks/>
[XmlAttribute]
public string callId;
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
//implement if remote callers are going to pass your object in
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("lmsId", lmsId.ToString());
writer.WriteAttributeString("unitId", unitId.ToString());
writer.WriteAttributeString("lmsPresId", lmsPresId.ToString());
writer.WriteAttributeString("callId", callId.ToString());
}
}
But my service help is showing request and response as unknown
I tried even XmlSerializerFormat
[System.ServiceModel.MessageContract]
public partial class Id
{
/// <remarks/>
[XmlAttribute, MessageBodyMember]
public string lmsId;
/// <remarks/>
[XmlAttribute, MessageBodyMember]
public string unitId;
/// <remarks/>
[XmlAttribute, MessageBodyMember]
public string lmsPresId;
/// <remarks/>
[XmlAttribute, MessageBodyMember]
public string callId;
}
then I am getting everything in the xml as xmlElements instead of XmlAttributes But I am getting all the data as elements instead of Xmlattributes.

Related

Shopify with Newtonsoft (JSON.NET) issue

I'm having an issue I can't figure out with a WCF service I'm building, where I am getting the error:
"Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data
contract which is not supported. Consider modifying the definition of
collection 'Newtonsoft.Json.Linq.JToken' to remove references to
itself"
I know the main solution is to uncheck the option to reuse that Newtonsoft reference in my service references, but I don't have that option listed to uncheck. I confirmed json.net is being referenced properly in my service.
The weird thing is I confirmed I am getting results when I leave this call
public List<T> CallService<T>(string query)
{
var data = new List<T>();
var fullyEscapedUri = _ShopUri.AbsoluteUri.EndsWith("/") ? _ShopUri : new Uri(_ShopUri + "/");
var uri = new Uri(fullyEscapedUri, typeof(T).Name);
if (!string.IsNullOrWhiteSpace(query))
{
var uriBuilder = new UriBuilder(uri) { Query = query };
uri = uriBuilder.Uri;
}
string url = String.Format("{0}{1}", _ShopUri, query);
var request = WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
string base64EncodedUsernameAndPassword = string.Format("{0}:{1}", _Username, _Password);
string authHeader = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(base64EncodedUsernameAndPassword)));
request.Headers["Authorization"] = authHeader;
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var jsonObj = JsonConvert.DeserializeObject(json, new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}) as JObject;
var jsonArray = jsonObj[_ObjectType] as JArray;
foreach (var jsonEmp in jsonArray)
{
var obj = JsonConvert.DeserializeObject<T>(jsonEmp.ToString());
data.Add(obj);
}
}
}
}
return data;
}
This method is in a custom class I wrote, so a couple of the variables appear as though they aren't definied - I'd be posted a sh*tton of code. But as you can see, I need this method to dynamically call any Shopify endpoint. In this example, the _ObjectType variable going in the first time is "orders."
Here is my order class definition:
public class Orders : ShopifyObject
{
[JsonProperty(PropertyName = "orders")]
public List<Order> orders;
}
public class Order : ShopifyObject
{
/// <summary>
/// The mailing address associated with the payment method. This address is an optional field that will not be available on orders that do not require one.
/// </summary>
[JsonProperty("billing_address")]
public Address BillingAddress { get; set; }
/// <summary>
/// The IP address of the browser used by the customer when placing the order.
/// </summary>
[JsonProperty("browser_ip")]
public string BrowserIp { get; set; }
/// <summary>
/// Indicates whether or not the person who placed the order would like to receive email updates from the shop.
/// This is set when checking the "I want to receive occasional emails about new products, promotions and other news" checkbox during checkout.
/// </summary>
[JsonProperty("buyer_accepts_marketing")]
public bool? BuyerAcceptsMarketing { get; set; }
/// <summary>
/// The reason why the order was cancelled. If the order was not cancelled, this value is null. Known values are "customer", "fraud", "inventory" and "other".
/// </summary>
[JsonProperty("cancel_reason")]
public string CancelReason { get; set; }
/// <summary>
/// The date and time when the order was cancelled. If the order was not cancelled, this value is null.
/// </summary>
[JsonProperty("cancelled_at")]
public DateTimeOffset? CancelledAt { get; set; }
/// <summary>
/// Unique identifier for a particular cart that is attached to a particular order.
/// </summary>
[JsonProperty("cart_token")]
public string CartToken { get; set; }
/// <summary>
/// A <see cref="ShopifySharp.ClientDetails"/> object containing information about the client.
/// </summary>
[JsonProperty("client_details")]
public ClientDetails ClientDetails { get; set; }
/// <summary>
/// The date and time when the order was closed. If the order was not clsoed, this value is null.
/// </summary>
[JsonProperty("closed_at")]
public DateTimeOffset? ClosedAt { get; set; }
/// <summary>
/// The customer's contact email address.
/// </summary>
[JsonProperty("contact_email"), Obsolete("ContactEmail is not documented by Shopify and will be removed in a future release.")]
public string ContactEmail { get; set; }
/// <summary>
/// The date and time when the order was created in Shopify.
/// </summary>
[JsonProperty("created_at")]
public DateTimeOffset? CreatedAt { get; set; }
/// <summary>
/// The three letter code (ISO 4217) for the currency used for the payment.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// A <see cref="ShopifySharp.Customer"/> object containing information about the customer. This value may be null if the order was created through Shopify POS.
/// </summary>
[JsonProperty("customer")]
public Customer Customer { get; set; }
/// <summary>
/// Applicable discount codes that can be applied to the order.
/// </summary>
[JsonProperty("discount_codes")]
public IEnumerable<DiscountCode> DiscountCodes { get; set; }
/// <summary>
/// The order's email address. Note: On and after 2015-11-03, you should be using <see cref="ContactEmail"/> to refer to the customer's email address.
/// Between 2015-11-03 and 2015-12-03, updates to an order's email will also update the customer's email. This is temporary so apps can be migrated over to
/// doing customer updates rather than order updates to change the contact email. After 2015-12-03, updating updating an order's email will no longer update
/// the customer's email and apps will have to use the customer update endpoint to do so.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// The financial status of an order. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided".
/// </summary>
[JsonProperty("financial_status")]
public string FinancialStatus { get; set; }
/// <summary>
/// An array of <see cref="Fulfillment"/> objects for this order.
/// </summary>
[JsonProperty("fulfillments")]
public IEnumerable<Fulfillment> Fulfillments { get; set; }
/// <summary>
/// The fulfillment status for this order. Known values are 'fulfilled', 'null' and 'partial'.
/// </summary>
[JsonProperty("fulfillment_status")]
public string FulfillmentStatus { get; set; }
/// <summary>
/// Tags are additional short descriptors, commonly used for filtering and searching, formatted as a string of comma-separated values.
/// </summary>
[JsonProperty("tags")]
public string Tags { get; set; }
/// <summary>
/// The URL for the page where the buyer landed when entering the shop.
/// </summary>
[JsonProperty("landing_site")]
public string LandingSite { get; set; }
/// <summary>
/// An array of <see cref="LineItem"/> objects, each one containing information about an item in the order.
/// </summary>
[JsonProperty("line_items")]
public IEnumerable<LineItem> LineItems { get; set; }
/// <summary>
/// The unique numeric identifier for the physical location at which the order was processed. Only present on orders processed at point of sale.
/// </summary>
[JsonProperty("location_id")]
public long? LocationId { get; set; }
/// <summary>
/// The customer's order name as represented by a number, e.g. '#1001'.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// The text of an optional note that a shop owner can attach to the order.
/// </summary>
[JsonProperty("note")]
public string Note { get; set; }
/// <summary>
/// Extra information that is added to the order.
/// </summary>
[JsonProperty("note_attributes")]
public IEnumerable<NoteAttribute> NoteAttributes { get; set; }
/// <summary>
/// Numerical identifier unique to the shop. A number is sequential and starts at 1000.
/// </summary>
[JsonProperty("number")]
public int? Number { get; set; }
/// <summary>
/// A unique numeric identifier for the order. This one is used by the shop owner and customer.
/// This is different from the id property, which is also a unique numeric identifier for the order, but used for API purposes.
/// </summary>
[JsonProperty("order_number")]
public int? OrderNumber { get; set; }
/// <summary>
/// The URL pointing to the order status web page. The URL will be null unless the order was created from a checkout.
/// </summary>
[JsonProperty("order_status_url")]
public string OrderStatusUrl { get; set; }
/// <summary>
/// Payment details for this order. May be null if the order was created via API without payment details.
/// </summary>
[JsonProperty("payment_details"), Obsolete("PaymentDetails has been deprecated and will be removed in a future release. This data is now available via the Transaction API.")]
public PaymentDetails PaymentDetails { get; set; }
/// <summary>
/// The list of all payment gateways used for the order.
/// </summary>
[JsonProperty("payment_gateway_names")]
public IEnumerable<string> PaymentGatewayNames { get; set; }
/// <summary>
/// The date that the order was processed at.
/// </summary>
[JsonProperty("processed_at")]
public DateTimeOffset? ProcessedAt { get; set; }
/// <summary>
/// The type of payment processing method. Known values are 'checkout', 'direct', 'manual', 'offsite', 'express', 'free' and 'none'.
/// </summary>
[JsonProperty("processing_method")]
public string ProcessingMethod { get; set; }
/// <summary>
/// The website that the customer clicked on to come to the shop.
/// </summary>
[JsonProperty("referring_site")]
public string ReferringSite { get; set; }
/// <summary>
/// The list of <see cref="Refund"/> objects applied to the order
/// </summary>
[JsonProperty("refunds")]
public IEnumerable<Refund> Refunds { get; set; }
/// <summary>
/// The mailing address to where the order will be shipped. This address is optional and will not be available on orders that do not require one.
/// </summary>
[JsonProperty("shipping_address")]
public Address ShippingAddress { get; set; }
/// <summary>
/// An array of <see cref="ShippingLine"/> objects, each of which details the shipping methods used.
/// </summary>
[JsonProperty("shipping_lines")]
public IEnumerable<ShippingLine> ShippingLines { get; set; }
/// <summary>
/// Where the order originated. May only be set during creation, and is not writeable thereafter.
/// Orders created via the API may be assigned any string of your choice except for "web", "pos", "iphone", and "android".
/// Default is "api".
/// </summary>
[JsonProperty("source_name")]
public string SourceName { get; set; }
/// <summary>
/// Price of the order before shipping and taxes
/// </summary>
[JsonProperty("subtotal_price")]
public decimal? SubtotalPrice { get; set; }
/// <summary>
/// An array of <see cref="TaxLine"/> objects, each of which details the total taxes applicable to the order.
/// </summary>
[JsonProperty("tax_lines")]
public IEnumerable<TaxLine> TaxLines { get; set; }
/// <summary>
/// States whether or not taxes are included in the order subtotal.
/// </summary>
[JsonProperty("taxes_included")]
public bool? TaxesIncluded { get; set; }
/// <summary>
/// Unique identifier for a particular order.
/// </summary>
[JsonProperty("token")]
public string Token { get; set; }
/// <summary>
/// The total amount of the discounts applied to the price of the order.
/// </summary>
[JsonProperty("total_discounts")]
public decimal? TotalDiscounts { get; set; }
/// <summary>
/// The sum of all the prices of all the items in the order.
/// </summary>
[JsonProperty("total_line_items_price")]
public decimal? TotalLineItemsPrice { get; set; }
/// <summary>
/// The sum of all the prices of all the items in the order, with taxes and discounts included (must be positive).
/// </summary>
[JsonProperty("total_price")]
public decimal? TotalPrice { get; set; }
/// <summary>
/// The sum of all the prices of all the items in the order, in USD, with taxes and discounts included (must be positive).
/// </summary>
[JsonProperty("total_price_usd"), Obsolete("TotalPriceUsd is not documented by Shopify and will be removed in a future release.")]
public decimal? TotalPriceUsd { get; set; }
/// <summary>
/// The sum of all the taxes applied to the order (must be positive).
/// </summary>
[JsonProperty("total_tax")]
public decimal? TotalTax { get; set; }
/// <summary>
/// The sum of all the weights of the line items in the order, in grams.
/// </summary>
[JsonProperty("total_weight")]
public long? TotalWeight { get; set; }
/// <summary>
/// The date and time when the order was last modified.
/// </summary>
[JsonProperty("updated_at")]
public DateTimeOffset? UpdatedAt { get; set; }
/// <summary>
/// The unique numerical identifier for the user logged into the terminal at the time the order was processed at. Only present on orders processed at point of sale.
/// </summary>
[JsonProperty("user_id")]
public long? UserId { get; set; }
/// <summary>
/// An array of <see cref="Transaction"/> objects that detail all of the transactions in
/// this order.
/// </summary>
[JsonProperty("transactions")]
public IEnumerable<Transaction> Transactions { get; set; }
}
I seem to be getting the error msg referenced above when it makes this GetOrders() call from the client:
ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
OrderService.OrderServiceClient service = new OrderService.OrderServiceClient();
var orders = service.GetOrders(String.Format("orders.json?created_at_min={0}&created_at_max={1}", min, max));
strong text
I've searched my client app for any and all references to Newtonsoft, but I am not finding anything or any clue that would suggest it's being called "recursively." I've deleted and re-added the service references, same issue.
Both the service and client are v4.6.1.
Any ideas?
Ben
EDIT: I can't trigger the error now for some reason, but when it did happen, I got this as the outer exception, followed by just the main error message with the inner exception:
Unhandled Exception: System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost:3000/OrderService.svc/GetOrders. This could be due to the service endpoint
binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down).
See server logs for more details.
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ShopifyServiceClient.OrderService.IOrderService.GetOrders(String query)
at ShopifyServiceClient.OrderService.OrderServiceClient.GetOrders(String query)
at ShopifyServiceClient.Program.Main(String[] args)
Deeper down....
System.Runtime.Serialization.InvalidDataContractException,
System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data
contract which is not supported. Consider modifying the definition of
collection 'Newtonsoft.Json.Linq.JToken' to remove references to
itself.
Here is the entry point of my service:
public class OrderService : IOrderService
{
public ReturnContract GetOffset()
{
return new ReturnContract { Offset = new DateTimeOffset(DateTime.Now) };
}
//non-async calls
public List<Order> GetOrders(string query)
{
OrderData orders = new OrderData(query);
return orders.CallOrders();
}
[DataContract]
[KnownType(typeof(DateTimeOffset))]
public class ReturnContract
{
[DataMember]
public DateTimeOffset? Offset { get; set; }
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
CallOrders() implementation and CallService<T> method that shows type Order going into the method:
internal class OrderData
{
private string _shopifyStore = Global.EcomShop;
private string _apiKey = Global.EcomShopAPIKey;
private string _apiPassword = Global.EcomShopAPIPassword;
private string _query;
internal OrderData(string query)
{
_query = query;
}
internal List<Order> CallOrders()
{
var orderService = new ShopifyService(_shopifyStore, _apiKey, _apiPassword, "orders");
var orders = orderService.CallService<Order>(_query);
return orders;
}
}
Well, in this case it turned out to be a JSON deserialization issue. When this has happened in the past, I've received the "object reference not set to an instance of an object" error. I thought this was weird since I did see Shopify objects coming back from the service.

Serialize enum to string with RestSharpJsonNetSerializer [duplicate]

This question already has answers here:
Why serializing Version with JsonPropertyAttribute doesn't work?
(1 answer)
parsing an enumeration in JSON.net
(1 answer)
How to tell Json.Net globally to apply the StringEnumConverter to all enums
(5 answers)
Closed 5 years ago.
I have my RestSharpJsonNetSerializer class below.
I am serializing an object that has several properties of enum types.
I am using properties below. But the resulting JSON still displays int values of enums, not their string values.
I guess I could be using wrong properties or need to add changes to my serializer class. Relatively new with this, so need some help please.
public class PTypeData
{
[JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
public Enums.Type Type {get;set;}
[JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
public Enums.Status Status {get;set;}
}
RestSharpJsonNetSerializer class:
public class RestSharpJsonNetSerializer : RestSharp.Serializers.ISerializer
{
private readonly Newtonsoft.Json.JsonSerializer _serializer;
/// <summary>
/// Default serializer
/// </summary>
public RestSharpJsonNetSerializer () {
ContentType = "application/json";
_serializer = new Newtonsoft.Json.JsonSerializer {
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Include
};
}
/// <summary>
/// Default serializer with overload for allowing custom Json.NET settings
/// </summary>
public RestSharpJsonNetSerializer (Newtonsoft.Json.JsonSerializer serializer){
ContentType = "application/json";
_serializer = serializer;
}
/// <summary>
/// Serialize the object as JSON
/// </summary>
/// <param name="obj">Object to serialize</param>
/// <returns>JSON as String</returns>
public string Serialize(object obj) {
using (var stringWriter = new StringWriter()) {
using (var jsonTextWriter = new JsonTextWriter(stringWriter)) {
jsonTextWriter.Formatting = Formatting.Indented;
jsonTextWriter.QuoteChar = '"';
_serializer.Serialize(jsonTextWriter, obj);
var result = stringWriter.ToString();
return result;
}
}
}
/// <summary>
/// Unused for JSON Serialization
/// </summary>
public string DateFormat { get; set; }
/// <summary>
/// Unused for JSON Serialization
/// </summary>
public string RootElement { get; set; }
/// <summary>
/// Unused for JSON Serialization
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// Content type for serialized content
/// </summary>
public string ContentType { get; set; }
}

RavenDB - Computed Properties

I have a document with a few computed properties. Properties that have no setter and can call other methods on my class to return a result, example:
public class Order
{
public string CustomerId { get; set; }
public string VehicleId { get; set; }
public DateTime OrderDate { get; set; }
public decimal CommissionPercent { get; set; }
public List<OrdersLines> OrderLines { get; set; }
public decimal Total
{
get { return GetOrderLinesTotal() + SomeDecimal + AnotherDecimal; }
}
public decimal GetOrderLinesTotal()
{
return OrderLines.Sum(x => x.Amount);
}
}
I use a simple index to search for Orders by customer, date and some properties on the Vehicle document using lucene query and a Transformer to create my view models. I've looked at Scripted Index Results and I'm not sure if it would apply in this case.
public class ViewModel
{
public string OrderId { get; set; }
public string CustomerName { get; set; }
public string VehicleName { get; set; }
public string Total { get; set; }
}
How do i get the computed value from the Total property when I query these documents?
I've simplified the GetOrderLinesTotal some what, in fact it is a complex method that takes a lot of other properties into account when calculating the total.
I only get the computed value that serialized when the document was created or updated.
I realized that this is more a of a document design problem rather than trying to do something RavenDB was not meant to do. I simplified my document and used a map/reduce to solve the problem.
I think your situation is similar to a problem I once encountered. I use a JsonIgnore attribute on my public get property and use a private backing field, which I include in serialisation using the JsonProperty attribute. You should be able to apply a similar idea hopefully:
/// <summary>
/// The <see cref="Team" /> class.
/// </summary>
public class Team
{
/// <summary>
/// The ids of the users in the team.
/// </summary>
[JsonProperty(PropertyName = "UserIds")]
private ICollection<string> userIds;
// ...[snip]...
/// <summary>
/// Gets the ids of the users in the team.
/// </summary>
/// <value>
/// The ids of the users in the team.
/// </value>
[JsonIgnore]
public IEnumerable<string> UserIds
{
get { return this.userIds; }
}
// ...[snip]...
}

NHibernate projection, AutoMapping, IPagedList, how to?

I have these entities and models:
ENTITIES:
public class BlogPost {
public virtual int Id { get; set; }
public virtual IList<Keyword> Keywords { get; set; }
public virtual IList<BlogComment> Comments { get; set; }
}
public class BlogComment {
public virtual int Id { get; set; }
public virtual BlogPost Post { get; set; }
}
public class Keyword {
public virtual int Id { get; set; }
public virtual IList<BlogPost> BlogPosts { get; set; }
}
VIEW-MODELS:
public class BlogPostModel {
public int Id { get; set; }
// instead of IList<BlogComment> I have this:
public int CommentsCount { get; set; }
public IList<KeywordModel> Keywords { get; set; }
}
public class KeywordModel {
public int Id { get; set; }
public IList<BlogPostModel> Posts { get; set; }
}
public class BlogCommentModel {
public int Id { get; set; }
public BlogPostModel Post { get; set; }
}
Now I want to load a paged-list of blog-posts with their keywords and comments count and map them by AutoMapper library to a IPagedList<BlogPostModel>. Can you help me please? I'm using the Mvc IPagedList available at nuget:
public interface IPagedList<out T> : IPagedList, IEnumerable<T> {
T this[int index] { get; }
int Count { get; }
IPagedList GetMetaData();
}
public interface IPagedList {
int PageCount { get; }
int TotalItemCount { get; }
int PageNumber { get; }
int PageSize { get; }
bool HasPreviousPage { get; }
bool HasNextPage { get; }
bool IsFirstPage { get; }
bool IsLastPage { get; }
int FirstItemOnPage { get; }
int LastItemOnPage { get; }
}
I test many ways and googled the issue, but I can't find any solution. Thanks for any suggestion.
I had the same problem, and found the way how to fix it, probably this approach will help you too.
public class GenericModelViewConverter<TModel, TView> : IModelViewConverter<TModel, TView>
where TModel : class
where TView : class
{
/// <summary>
/// Initializes a new instance of the <see cref="GenericModelViewConverter{TModel, TView}"/> class.
/// </summary>
public GenericModelViewConverter()
{
// It is not he best place to create the mapping here
Mapper.CreateMap<TView, TModel>();
Mapper.CreateMap<TView, TModel>().ReverseMap();
}
/// <summary>
/// Converts the view to model.
/// </summary>
/// <param name="view">The view as a source.</param>
/// <param name="model">The model as a destination value.</param>
/// <returns>The destination model.</returns>
public virtual TModel ConvertViewToModel(TView view, TModel model = null)
{
return model == null ? Mapper.Map<TView, TModel>(view) : Mapper.Map(view, model);
}
/// <summary>
/// Converts the model to view.
/// </summary>
/// <param name="model">The model as a source.</param>
/// <param name="view">The view as a destination.</param>
/// <returns>The destination view.</returns>
public virtual TView ConvertModelToView(TModel model, TView view = null)
{
return view == null ? Mapper.Map<TModel, TView>(model) : Mapper.Map(model, view);
}
/// <summary>
/// Converts the view to model.
/// </summary>
/// <param name="viewCollection">The collection of views.</param>
/// <returns>The collection of models.</returns>
public virtual IEnumerable<TModel> ConvertViewToModel(IEnumerable<TView> viewCollection)
{
return Mapper.Map<IEnumerable<TView>, HashSet<TModel>>(viewCollection);
}
/// <summary>
/// Converts the model to view.
/// </summary>
/// <param name="modelCollection">The collection of models.</param>
/// <returns>The collection of views.</returns>
public virtual IEnumerable<TView> ConvertModelToView(IEnumerable<TModel> modelCollection)
{
return Mapper.Map<IEnumerable<TModel>, HashSet<TView>>(modelCollection);
}
/// <summary>
/// Converts the model to view.
/// </summary>
/// <param name="modelCollection">The model collection.</param>
/// <returns>The collection of models.</returns>
public virtual IPagedCollection<TView> ConvertModelToView(IPagedCollection<TModel> modelCollection)
{
var list = modelCollection.ToList();
var resultList = ConvertModelToView(list);
return new PagedCollection<TView>(resultList, modelCollection.PageIndex, modelCollection.PageSize, modelCollection.TotalItemCount);
}
/// <summary>
/// Converts the view to model.
/// </summary>
/// <param name="viewCollection">The view collection.</param>
/// <returns>The collection of views.</returns>
public virtual IPagedCollection<TModel> ConvertViewToModel(IPagedCollection<TView> viewCollection)
{
var list = viewCollection.ToList();
var resultList = ConvertViewToModel(list);
return new PagedCollection<TModel>(resultList, viewCollection.PageIndex, viewCollection.PageSize, viewCollection.TotalItemCount);
}
}

Custom objects in WCF

I have following object, it works fine when I specify standart objects like int, string and not with custom object.
[DataContract(Namespace = "")]
public class StatusLog<TItem>
{
/// <summary>
/// Gets or sets the key.
/// </summary>
/// <value>
/// The key.
/// </value>
[DataMember]
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the action status.
/// </summary>
/// <value>
/// The action status.
/// </value>
[DataMember]
public ActionStatus ActionStatus { get; set; }
/// <summary>
/// Gets or sets the object.
/// </summary>
/// <value>
/// The object.
/// </value>
[DataMember]
public TItem Object { get; set; }
/// <summary>
/// Gets or sets the message.
/// </summary>
/// <value>
/// The message.
/// </value>
[DataMember]
public string Message { get; set; }
}
This works:
return new StatusLog { Id = Guid.NewGuid(), ActionStatus = ActionStatus.Deleted, Object = Convert.ToInt32(id), Message = "Node deleted successfully" };
This does not work:
new StatusLog {Id = Guid.NewGuid(), ActionStatus = ActionStatus.Created, Object = MyCustomObject};
Have a look at KnownType Attribute.
As flosk8 mentioned, the DataContractSerializer won't know what types to consider when deserializing your DataContract unless it is decorated with the KnownType attribute.
http://msdn.microsoft.com/en-us/library/ms730167.aspx
Try adding the following attribute to your DataContract:
[DataContract(Namespace = "")]
[KnownType(typeof(MyCustomObject))]
public class StatusLog<TItem>
{
// ... snip ...
}
You will need to add this attribute for each type that may need to be deserialized to the StatusLog.Object property. Additionally, each of these types need to be serializable.