Azure Service Bus Queue - Serialization with BrokeredMessage - azure

Trying to submit a queue message with an object in the message body but receiving exception on the following line with BrokeredMessage
QueueClient queueClient = QueueClient.CreateFromConnectionString(_connectionString, _queuePathName);
var data = new ABSurvey
{
name = "somename",
version = 1,
language = "eng",
SelfSurvey = new Survey()
{
SurveyItems = new List<ISurveyItem>() { new SurveyItem(){IsSelected = true, ItemId = 1}},
SurveyPerception = Constants.Perception.Self
},
SelfConcept = new Survey()
{
SurveyItems = new List<ISurveyItem>() { new SurveyItem(){IsSelected = true, ItemId = 1}},
SurveyPerception = Constants.Perception.SelfConcept
}
};
BrokeredMessage message = new BrokeredMessage(data);
queueClient.Send(message);
Exception Message - Type '.Survey' with data contract name 'Survey:http://schemas.datacontract.org/2004/07/namespace' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
These are the models I have -
[DataContract]
public class ABSurvey
{
[DataMember] public string name;
[DataMember] public int version;
[DataMember] public string language;
[DataMember] public ISurvey SelfSurvey;
[DataMember] public ISurvey SelfConcept;
}
[DataContract]
public class SurveyItem : ISurveyItem
{
[DataMember]
public int ItemId { get; set; }
[DataMember]
public bool IsSelected { get; set; }
public SurveyItem()
{
ItemId = -1;
IsSelected = false;
}
}
[DataContract]
public class Survey : ISurvey
{
[DataMember]
public IList<ISurveyItem> SurveyItems { get; set; }
[DataMember]
public Constants.Perception SurveyPerception { get; set; }
public Survey()
{
SurveyItems = new List<ISurveyItem>();
}
}
public interface ISurvey
{
[DataMember]
IList<ISurveyItem> SurveyItems { get; set; }
[DataMember]
Constants.Perception SurveyPerception { get; set; }
}
public interface ISurveyItem
{
[DataMember]
int ItemId { get; set; }
[DataMember]
bool IsSelected { get; set; }
}
Please help locate the issues.

You are missing [KnownType] attributes on your data contract and that is why your message can't be serialized. Detailed explanation can be found hehe.
Simply add [KnownType] attributes to tell serializer which concrete implementation can be used:
[KnownType(typeof(Survey))]
[DataContract]
public class ABSurvey
{
[DataMember]
public string name;
[DataMember]
public int version;
[DataMember]
public string language;
[DataMember]
public ISurvey SelfSurvey;
[DataMember]
public ISurvey SelfConcept;
}
[KnownType(typeof(SurveyItem))]
[DataContract]
public class Survey : ISurvey
{
[DataMember]
public IList<ISurveyItem> SurveyItems { get; set; }
public Survey()
{
SurveyItems = new List<ISurveyItem>();
}
}

Related

How to fix 'model code generator' in asp.net mvc 5

I modelling a simple library management system that able to register user and the user can issue a book.
I want the asp.net IdentityUser to create one -to many relationShip with BookIssue Custom table. because I am new to asp.net mvc 5, I can not fix the problem please help me.
public class ApplicationUser : IdentityUser
{
public virtual ICollection<BookIssue> BookIssues { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Book> Books { get; set; }
public DbSet<BookIssue> BookIssues { get; set; }
public DbSet<Catagory> Catagories { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BookIssue>()
.HasRequired(n => n.ApplicationUser)
.WithMany(a => a.BookIssues)
.HasForeignKey(n => n.ApplicationUserId)
.WillCascadeOnDelete(false);
}
}
}
BookIssue Model:
public int BookIssueId { get; set; }
public int BookId { get; set; }
public int ApplicationUserId { get; set; }
public string Email { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public virtual Book Book { get; set; }
public virtual ApplicationUser ApplicationUser { get; set;
The generated error:
There was an error running the selected code generator. 'Unable to
retrieve metadata for Librart.Models.BookIssuee'.One or more
validation errors were detected during model generation:
Library.Models.IdentityUserLogin: EntityType 'IdentityUserRole' has no
key defined.Define the key for this EntityType.
Library.Models.IdentityUserRole: EntityType 'IdentityUserLogin' has no
key defined.Define the key for this EntityType.
And many other errors are generated.

Configuring AutoMapper in ASP.NET Core

I am trying to use automapper 8.0.0 to fill a list of WorkViewModel.
This list is getting data from the Work class out of the database using entity framework.
How ever it looks like something is going wrong with initializing as throwing follows error:
InvalidOperationException: Mapper not initialized
What am I doing wrong?
I have setup the following code!
Startup.cs
services.AddAutoMapper();
Function being called:
public async Task<IEnumerable<WorkViewModel>> GetAllAsync()
{
IList<Work> works = await _context.Work.ToListAsync();
IList<WorkViewModel> viewModelList = Mapper.Map<IList<Work>, IList<WorkViewModel>>(works);
return viewModelList;
}
Configuration:
public class MappingProfile : Profile
{
public MappingProfile()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<WorkViewModel, Work>();
});
}
}
WorkViewModel:
public class WorkViewModel
{
public int WorkID { get; set; }
public string Name { get; set; }
public byte[] Tumbmail { get; set; }
public string Discription { get; set; }
public string Client { get; set; }
public DateTime Date { get; set; }
public string PreviewLink { get; set; }
public string GitLink { get; set; }
public string DownloadLink { get; set; }
public int DetailID { get; set; }
public byte[] Banner { get; set; }
public string Documentation { get; set; }
public int CategoryID { get; set; }
public string Category { get; set; }
}
Work Model:
public class Work
{
[Key]
public int WorkID { get; set; }
[Display(Name = "Project Name")]
public string Name { get; set; }
[Display(Name = "Client name")]
public string Client { get; set; }
[Display(Name = "Description")]
public string Discription { get; set; }
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Display(Name = "Thumbmail")]
public byte[] Tumbmail { get; set; }
[Display(Name = "Preview Link")]
public string PreviewLink { get; set; }
[Display(Name = "Git Link")]
public string GitLink { get; set; }
[Display(Name = "DownloadLink")]
public string DownloadLink { get; set; }
public WorkCategory workCategory { get; set; }
public WorkDetailed WorkDetailed { get; set; }
}
Only adding services.AddAutoMapper(); to the ConfigureServices method would not work for you. You have to configure AutoMapper as follows:
public void ConfigureServices(IServiceCollection services)
{
// Auto Mapper Configurations
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddMvc();
}
And also don't forget to install the AutoMapper.Extensions.Microsoft.DependencyInjection nuget package.

Error 400.0 when returning DTO in Controller and Azure Mobile Client Sync Table

Since the object we need in the Mobile Client needs to access its related/associated objects, we decided to return an objectDTO instead of the object when the GetAllObjects method in the controller is called.
Using Postman to query the Backend Server results to the proper behaviour, the retrieved list has all the properties of the DTO.
Problem arises when using the Mobile Client. According to the logs, an "HTTP Error 400.0 - Bad Request" happened and "The request could not be understood by the server due to malformed syntax." is indicated under "More Information."
I dont know why this error happened. I updated the Object class in the Client App to match the ObjectDTO class in the server. For comparison:
ObjectDTO in Server
public class SaleDto
{
public string Id { get; set; }
public string ProductId { get; set; }
public string PromoterId { get; set; }
public string StoreId { get; set; }
public string PaymentMethodId { get; set; }
public bool CorporateSale { get; set; }
public DateTime? DateSold { get; set; }
public double PriceSold { get; set; }
public int QuantitySold { get; set; }
public string Remarks { get; set; }
public bool Deleted { get; set; }
public DateTimeOffset? CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public byte[] Version { get; set; }
public string ProductSku { get; set; }
public string ProductPartNumber { get; set; }
public string StoreName { get; set; }
public string PaymentMethodName { get; set; }
}
Object Model in Client App
public class Sale
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "productId")]
public string ProductId { get; set; }
[JsonProperty(PropertyName = "promoterId")]
public string PromoterId { get; set; }
[JsonProperty(PropertyName = "storeId")]
public string StoreId { get; set; }
[JsonProperty(PropertyName = "paymentMethodId")]
public string PaymentMethodId { get; set; }
[JsonProperty(PropertyName = "corporateSale")]
public bool CorporateSale { get; set; }
[JsonProperty(PropertyName = "dateSold")]
public DateTime? DateSold { get; set; }
[JsonProperty(PropertyName = "priceSold")]
public double PriceSold { get; set; }
[JsonProperty(PropertyName = "quantitySold")]
public int QuantitySold { get; set; }
[JsonProperty(PropertyName = "remarks")]
public string Remarks { get; set; }
[JsonProperty(PropertyName = "deleted")]
public bool Deleted { get; set; }
[JsonProperty(PropertyName = "createdAt")]
public DateTime CreatedAt { get; set; }
[JsonProperty(PropertyName = "updatedAt")]
public DateTime UpdatedAt { get; set; }
[JsonProperty(PropertyName = "version")]
public string Version { get; set; }
[JsonProperty(PropertyName = "productSku")]
public string ProductSku { get; set; }
[JsonProperty(PropertyName = "productPartNumber")]
public string ProductPartNumber { get; set; }
[JsonProperty(PropertyName = "storeName")]
public string StoreName { get; set; }
[JsonProperty(PropertyName = "paymentMethodName")]
public string PaymentMethodName { get; set; }
public virtual Product Product { get; set;}
public virtual Store Store { get; set; }
public virtual PaymentMethod PaymentMethod { get; set; }
}
Or it might be because of the Sync Tables? Here's the code that handles syncing (stuff has been omitted for brevity)
public class DataStore
{
private static DataStore _instance;
public MobileServiceClient MobileService { get; set; }
IMobileServiceSyncTable<Sale> saleTable;
public static DataStore Instance
{
get
{
if (_instance == null)
{
_instance = new DataStore();
}
return _instance;
}
}
private DataStore()
{
MobileService = new MobileServiceClient("url");
var store = new MobileServiceSQLiteStore("tabletable.db");
store.DefineTable<Sale>();
MobileService.SyncContext.InitializeAsync(store);
saleTable = MobileService.GetSyncTable<Sale>();
}
public async Task<Sale> AddSaleAsync(Sale sale)
{
await saleTable.InsertAsync(sale);
bool wasPushed = await SyncSalesAsync();
if (wasPushed) return null;
return sale;
}
public async Task<List<Sale>> GetSalesAsync(int take = 20, int skip = 0)
{
IEnumerable<Sale> items = await saleTable
.Where(sale => !sale.Deleted)
.OrderByDescending(sale => sale.CreatedAt)
.Take(take)
.Skip(skip)
.ToEnumerableAsync();
return new List<Sale>(items);
}
public async Task<bool> SyncSalesAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
bool wasPushed = true;
try
{
await MobileService.SyncContext.PushAsync();
await saleTable.PullAsync("allSales", saleTable.CreateQuery());
}
catch (Exception e)
{
Debug.WriteLine(#"/Sale/ Catch all. Sync error: {0}", e.Message);
Debug.WriteLine(e.StackTrace);
}
return wasPushed;
}
}
Any kind of help will be much appreciated.
Having SaleDto extend/implement EntityData solved the problem
public class SaleDto : EntityData

Complex Automapper Configuration

I'm mapping from an existing database to a DTO and back again use Automapper (4.1.1) and I've hit a few small problems.
I have a (simplified) model for the database table:
public class USER_DETAILS
{
[Key]
public string UDT_LOGIN { get; set; }
public string UDT_USER_NAME { get; set; }
public string UDT_INITIALS { get; set; }
public string UDT_USER_GROUP { get; set; }
public decimal UDT_CLAIM_LIMIT { get; set; }
public string UDT_CLAIM_CCY { get; set; }
}
and a DTO object:
public class User
{
public string Login { get; set; }
public string UserName { get; set; }
public string Initials { get; set; }
public string UserGroup { get; set; }
public double ClaimLimit { get; set; }
public string ClaimCurrency { get; set; }
}
I've created a profile
public class FromProfile : Profile
{
protected override void Configure()
{
this.RecognizePrefixes("UDT_");
this.ReplaceMemberName("CCY", "Currency");
this.SourceMemberNamingConvention = new UpperUnderscoreNamingConvention();
this.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
this.CreateMap<decimal, double>().ConvertUsing((decimal src) => (double)src);
this.CreateMap<USER_DETAILS, User>();
}
}
However, it seems that Automapper doesn't like combining this many settings in the config. Even simplifying the models, I can't get
this.RecognizePrefixes("UDT_");
this.ReplaceMemberName("CCY", "Currency");
to work together, and whilst
this.CreateMap<decimal, double>().ConvertUsing((decimal src) => (double)src);
works ok with the models in the test, it fails when using it against a database.
Is there a way to get all this to work together, or should I fall back to using ForMember(). I was really hoping I could get this working as there are a lot of tables in this system, and I'd rather not have to do each one individually.
You will need to extend this for other types, only tested with strings, I have an extension method that does all the work and looks for unmapped properties.
public class USER_DETAILS
{
public string UDT_LOGIN { get; set; }
public string UDT_USER_NAME { get; set; }
public string UDT_INITIALS { get; set; }
public string UDT_USER_GROUP { get; set; }
// public decimal UDT_CLAIM_LIMIT { get; set; }
public string UDT_CLAIM_CCY { get; set; }
}
public class User
{
public string Login { get; set; }
public string UserName { get; set; }
public string Initials { get; set; }
public string UserGroup { get; set; }
//public double ClaimLimit { get; set; }
public string ClaimCurrency { get; set; }
}
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination>
CustomPropertyMapper<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType == sourceType && x.DestinationType == destinationType);
var properties = sourceType.GetProperties();
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
var similarPropertyName =
properties.FirstOrDefault(x => x.Name.Replace("_", "").Replace("UDT", "").ToLower().Contains(property.ToLower()));
if(similarPropertyName == null)
continue;
var myPropInfo = sourceType.GetProperty(similarPropertyName.Name);
expression.ForMember(property, opt => opt.MapFrom<string>(myPropInfo.Name));
}
return expression;
}
}
class Program
{
static void Main(string[] args)
{
InitializeAutomapper();
var userDetails = new USER_DETAILS
{
UDT_LOGIN = "Labi-Login",
UDT_USER_NAME = "Labi-UserName",
UDT_INITIALS = "L"
};
var mapped = Mapper.Map<User>(userDetails);
}
static void InitializeAutomapper()
{
Mapper.CreateMap<USER_DETAILS, User>().CustomPropertyMapper();
}
}
}

SubSonic Simple Repository One-To-Many

I made a class like:
public class Video
{
public Guid VideoID { get; set; }
public VideoCategory VideoCategory { get; set; }
public int SortIndex { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Author { get; set; }
public string Filename { get; set; }
public new void Add()
{
this.VideoID = Guid.NewGuid();
DB.Repository.Add(this);
}
}
And another like
public class VideoCategory
{
public Guid VideoCategoryID { get; set; }
public string Title { get; set; }
public new void Add()
{
this.VideoCategoryID = Guid.NewGuid();
DB.Repository.Add(this);
}
}
I then have code like:
VideoCategory VideoCategory = new VideoCategory();
VideoCategory.Title = "TestTitle";
VideoCategory.Add();
Video Video = new Video();
Video.VideoCategory = VideoCategory;
Video.SortIndex = 1;
Video.Title = "TestTitle";
Video.Body = "TestBody";
Video.Author = "TestAuthor";
Video.Filename = "TestFile.flv";
Video.Add();
It doesn't save the VideoCategory into my database, so obviously i'm missing something. What else is needed to done to save a one-to-many relationship?
You could probably just do the following, you'll probably want to tidy it up but it will ensure your foreign key value gets populated:
public class Video
{
protected VideoCategory videoCategory;
public Guid ID { get; set; }
public VideoCategory VideoCategory
{
get { return videoCategory; }
set
{
videoCategory = value;
VideoCategoryId = value.ID;
}
}
public Guid VideoCategoryId { get; set; }
public int SortIndex { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Author { get; set; }
public string Filename { get; set; }
}
public class VideoCategory
{
public Guid ID { get; set; }
public string Title { get; set; }
}
SimpleRepository repo = new SimpleRepository(SimpleRepositoryOptions.RunMigrations);
VideoCategory videoCategory = new VideoCategory();
videoCategory.ID = Guid.NewGuid();
videoCategory.Title = "TestTitle";
repo.Add<VideoCategory>(videoCategory);
Video video = new Video();
video.ID = Guid.NewGuid();
video.VideoCategory = videoCategory;
video.SortIndex = 1;
video.Title = "TestTitle";
video.Body = "TestBody";
video.Author = "TestAuthor";
video.Filename = "TestFile.flv";
repo.Add<Video>(video);
You're not missing anything. Simplerepository doesn't support one to many out of the box.
Heres a useful link that shows how to mangage foreign keys yourself in SimpleRepository -
subsonic-3-simplerepository
Have not tried it myself, but looks like it would actually work.
Fluent Nhibernate will do this foriegn key management for you automatically, but it's a LOT more complex.
PS If this was helpful, please vote it up.

Resources