Serialize Partial DataContract - wcf

I have a DataContract that looks like:
[DataContract(Name = User.Root, Namespace = "")]
public class RegisterUser
{
[DataMember(Name = User.EmailAddress)]
public string EmailAddress { get; set; }
[DataMember(Name = User.UserName)]
public string UserName { get; set; }
[DataMember(Name = User.Password)]
public string Password { get; set; }
[DataMember(Name = User.FirstName)]
public string FirstName { get; set; }
[DataMember(Name = User.LastName)]
public string LastName { get; set; }
[DataMember(Name = User.PhoneNumber)]
public string PhoneNumber { get; set; }
[DataMember(Name = "RequestMessage")]
public string RequestMsg { get; set; }
}
And I would like to get the elements out of it. So instead of
<ROOT> <Element1/>...</ROOT>. I would just like to get <Element1/> (for partial xsd validation).
I thought I could use this function:
public static string Serialize<T>(T obj)
{
DataContractSerializer ser = new DataContractSerializer(obj.GetType());
String text;
using (MemoryStream memoryStream = new MemoryStream())
{
ser.WriteObject(memoryStream, obj);
byte[] data = new byte[memoryStream.Length];
Array.Copy(memoryStream.GetBuffer(), data, data.Length);
text = Encoding.UTF8.GetString(data);
}
return text;
}
and just pass it
string str = Serialize(test.EmailAddress);
That works great but the xml looks like:
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">myemail.com</string>"
I lost the DataMember info. How can I retain that as well?

Use WriteObjectContent instead of WriteObject:
http://msdn.microsoft.com/en-us/library/ms573853.aspx

Related

map string filed to generic list in automapper based on .net core

I have a DomainModel and a DTO like this :
public class PostEntity: IEntity
{
[Required]
public string Description { get; set; }
public int Id { get; set; }
[Required]
public string Slug { get; set; }
[Required]
public string Tags { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
public PostStatus Status { get; set; }
public User Writer { get; set; }
public int WriterId { get; set; }
}
public class PostDto
{
public int Id { get; set; }
public string Description { get; set; }
public string Slug { get; set; }
public string Tags { get; set; }
public string Title { get; set; }
public DateTime CreatedOn { get; }
public List<string> TagList { get; set; }
public PostDto()
{
TagList = new List<string>();
}
}
PostEntity'Tags contains some tags seperated by ",", now I want to split tags value by "," and convert it to List, to do this, I've tried this but I get the below compilation error
CreateMap<PostEntity, PostDto>().ForMember(dest => dest.TagList, cc => cc.MapFrom(src => src.Tags.Split(",").ToList()));
I get this error :
An expression tree may not contain a call or invocation that uses optional arguments
I can't reproduce your error, it seems to work fine.
Below is an example where the TagList is correctly mapped
The code I used :
MapperConfiguration MapperConfiguration = new MapperConfiguration(configuration =>
{
configuration
.CreateMap<PostEntity, PostDto>().ForMember(dest => dest.TagList, cc => cc.MapFrom(src => src.Tags.Split(',').ToList()));
});
IMapper mapper = MapperConfiguration.CreateMapper();
PostEntity postEntity = new PostEntity
{
Tags = "Tag1,Tag2,Tag3,Tag4"
};
var mappedObject = mapper.Map<PostEntity, PostDto>(postEntity);
Please bear in mind that Expression.Call API does not support optional parameters. So, you should Replace Split(',') with
Split(',', System.StringSplitOptions.None)
or
Split(',', System.StringSplitOptions.RemoveEmptyEntries)
doing so you won't see that error again.

json string downloaded with mising values c# webclient

I'm conding a rent car asp.net mvc application and I have a strange problem.
I used the skyscanner api to get the available cars list but the json string downloaded is always missing the attribute cars or there is cars that exist and are available.
string datacar = "";
String ch = "http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/" + ids + "/" + ide + "/" + dstart + "T" + tstart + "/" + dend + "T" + tend + "/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1";
Uri url = new Uri(ch);
// Uri url2 = new Uri("http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/27539733/27539733/2016-09-10T17:45/2016-09-17T17:45/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1");
CarModel model = new CarModel();
// for (int i = 0; i <= 20; i++)
// {
using (WebClient wc = new WebClient())
{
wc.Headers.Set("Content-Type", "application/json");
datacar = wc.DownloadString(url);
//datacar = wc.DownloadString(url2);
model = JsonConvert.DeserializeObject<CarModel>(datacar);
}
and here it is the carModel defintion
namespace carrent.Models
{
public class SubmittedQuery
{
public string market { get; set; }
public string currency { get; set; }
public string locale { get; set; }
public string pickup_place { get; set; }
public string dropoff_place { get; set; }
public string pickup_date_time { get; set; }
public string drop_off_date_time { get; set; }
public string driver_age { get; set; }
}
public class Image
{
public int id { get; set; }
public string url { get; set; }
}
public class CarClass
{
public int id { get; set; }
public int sort_order { get; set; }
public string name { get; set; }
}
public class DebugItem
{
public string type { get; set; }
public string title { get; set; }
public string content { get; set; }
}
public class CarModel
{
public SubmittedQuery submitted_query { get; set; }
public List<object> cars { get; set; }
public List<object> websites { get; set; }
public List<Image> images { get; set; }
public List<CarClass> car_classes { get; set; }
public List<DebugItem> debug_items { get; set; }
}
}
Ps: the strange thing in this problem is when I initialize an url (the url2) the code run perfectly
please guys help me to get the solution and thanks

Can't correctly add associated objects into Entity Framework Context

I have and entity framework project exposed via a data service:
public class VersionContext : DbContext
{
public DbSet<VersionTreeEntry> VersionTreeEntries { get; set; }
public DbSet<PluginState> PluginStates { get; set; }
public static void SetForUpdates()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<VersionContext, Configuration>());
}
}
public class VersionTreeEntry
{
public VersionTreeEntry()
{
Children = new List<VersionTreeEntry>();
PluginStates = new List<PluginState>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public virtual ICollection<VersionTreeEntry> Children { get; set; }
public virtual ICollection<PluginState> PluginStates { get; set; }
public virtual VersionTreeEntry Ancestor { get; set; }
/// <summary>
/// Links to the ProtoBufDataItem Id for the session state.
/// </summary>
public int DataId { get; set; }
public string Notes { get; set; }
[Required]
public DateTime TimeStamp { get; set; }
[MinLength(1, ErrorMessage = "Tag cannot have a zero length")]
[MaxLength(20, ErrorMessage = "A tag name cannot contain over 20 characters")]
public string Tag { get; set; }
public bool IsUiNodeExpanded { get; set; }
[Required]
public string Version { get; set; }
[Required]
public string SessionName { get; set; }
}
public class PluginState
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string PluginName { get; set; }
[Required]
public byte[] Data { get; set; }
}
As far as I can see, the data classes are defined correctly. I try to create some new objects and add them into the context, with their relations intact:
var session = new Session();
session.SessionName = "My new session";
VersionTreeEntry versionTreeEntry = new VersionTreeEntry();
versionTreeEntry.SessionName = session.SessionName;
versionTreeEntry.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
versionTreeEntry.TimeStamp = DateTime.Now;
_versionContext.AddToVersionTreeEntries(versionTreeEntry);
foreach (var plugin in session.Plugins)
{
using (var ms = new MemoryStream())
{
plugin.SaveState(ms);
PluginState state = new PluginState();
state.PluginName = plugin.PluginName;
state.Data = ms.ToArray();
versionTreeEntry.PluginStates.Add(state);
}
}
_versionContext.SaveChanges();
The problem is that the PluginState instances never actually get added to the database. If I add code to add them manually to the context, they do get added, but the foreign key pointing back to the VersionTreeEntry is null.
Again, this is a WCF DataService rather than vanilla EF, any idea what might be wrong?
Cheers
Posting the answer here from the comment section.
Agreed. The best way to do this is to call the following API:
_versionContext.AddRelatedObject(versionTreeEntry, "PluginStates", state);
Thanks
Pratik

How to filter audio podcasts from iTunes Search API?

By searching for podcasts with the iTunes API (http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html) the result contains both audio and video podcasts. Is there any way to retrieve only audio podcasts from the API?
Thanks in advance :-)
From the documentation it doesn’t seem as if filtering audio and video podcasts is possible; however, you could loop through the resulting items and check whether each item is audio or video for filtering. You can do that be finding additional information from the RSS feed or by making another call to iTunes using the subscribePodcast url (see example).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using System.IO;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//Searching for Windows Weekly
string url = "https://itunes.apple.com/search?term=Windows%20Weekly&media=podcast&attibute=audio";
string json = FetchHTML(url);
JavaScriptSerializer s = new JavaScriptSerializer();
var result = s.Deserialize(json);
var audioOnly = new List();
foreach (var item in result.Results)
{
if (!IsVideo(item.TrackId))
{
audioOnly.Add(item);
}
}
foreach (var au in audioOnly)
{
Console.WriteLine(au.TrackName);
}
Console.ReadLine();
}
static bool IsVideo(string id)
{
string req = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/subscribePodcast?id=" + id + "&wasWarnedAboutPodcasts=true";
string xml = FetchHTML(req,true);
bool isVideo = false;
var re = XElement.Load(new StringReader(xml)).Elements("dict").Elements("dict");
bool next = false;
foreach (var e in re.Elements())
{
if (next)
{
//This is the is video value
isVideo = e.Name.LocalName.Trim().ToLower() == "true";
next = false;
break;
}
if (e.Value == "is-video")
{
next = true;
}
}
return isVideo;
}
static string FetchHTML(string url,bool doItAsITunes = false)
{
string htmlCode = "";
using (WebClient client = new WebClient())
{
if (doItAsITunes)
{
client.Headers.Add("user-agent", "iTunes/9.1.1");
}
htmlCode = client.DownloadString(url);
}
return htmlCode;
}
}
public class SearchResult
{
public SearchResult()
{
Results = new List();
}
public int ResultCount { set; get; }
public List Results { set; get; }
}
public class Item
{
public Item()
{
GenreIDs = new List();
Genres = new List();
}
public string WrapperType { set; get; }
public string Kind { set; get; }
public string ArtistID { set; get; }
public string CollectionID { set; get; }
public string TrackId { set; get; }
public string ArtistName { set; get; }
public string CollectionName { set; get; }
public string TrackName { set; get; }
public string CollectionCensoredName { set; get; }
public string TrackCensoredName { set; get; }
public string ArtistViewUrl { set; get; }
public string FeedUrl { set; get; }
public string TrackViewUrl { set; get; }
public string PreviewUrl { set; get; }
public string ArtworkUrl60 { set; get; }
public string ArtworkUrl100 { set; get; }
public float CollectionPrice { set; get; }
public float TrackPrice { set; get; }
public string CollectionExplicitness { set; get; }
public string TrackExplicitness { set; get; }
public string DiscCount { set; get; }
public string DiscNumber { set; get; }
public string TrackCount { set; get; }
public string TrackNumber { set; get; }
public string TrackTimeMillis { set; get; }
public string Country { set; get; }
public string Currency { set; get; }
public string PrimaryGenreName { set; get; }
public List GenreIDs { set; get; }
public List Genres { set; get; }
}
}
Yes. In regular serach you get everything:
https://itunes.apple.com/search?term=jack+johnson
But you can add some params to request for example (for your case)
&entity=song
So the request will be:
https://itunes.apple.com/search?term=jack+johnson&entity=song
For more look at Searching seaction in this docs

Does Order Matter in the XML Read by the DataContractSerializer?

I have the following code:
[DataContract(Namespace = "")]
public class User
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string FullName { get; set; }
}
//Deserialization test
public void Test()
{
//CASE 1.
//string xml = "<User><UserName>john</UserName>" +
// "<FullName>John Lennon</FullName></User>";
//CASE 2.
string xml = "<User><FullName>John Lennon</FullName>" +
"<UserName>john</UserName></User>";
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
User user = null;
using (MemoryStream stream = new MemoryStream(byteArray))
{
DataContractSerializer serializer =
new DataContractSerializer(typeof(User), "User", "");
user = (User)serializer.ReadObject(stream);
}
}
In case 1, FullName property isn't deserialized, but in case 2 it is deserialized properly. Why?
Because order is significant. Alphabetic order is used unless you specify the order in your DataMember attributes.
This is explained in this MSDN article.
In general, it's a good practice to always explicitly specify Order on your DataMember attributes:
[DataMember(IsRequired=true, Order=0)]
public string FullName { get; set; }
[DataMember(IsRequired=true, Order=1)]
public string UserName { get; set; }