Autogenerate DTO elements when loading an XML for Deserialization - c#

Suggest me a proper solution for autogenerating DTO elements when loading a proper XML for Deserialization.
This is my DTO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace GHelper.DTO
{
public class ElementsDTO
{
[XmlRoot("GalLC")]
public class FareBB
{
[xmlElement("Ip")]
public string strIp { get; set; }
[xmlElement("Port")]
public int intPort { get; set; }
[xmlElement("Type")]
public int intPort{ get; set; }
[xmlElement("Email")]
public string strEmail{ get; set; }
}
}
}
Here is my XML
<GalLC>
<Ip>192.168.2.100</Ip>
<Port>5051</Port>
<Type></Type>
<Email></Email>
</GalLC>
The problem is: when i am getting a lengthy XML, I will consume lots of time to create a DTO for it.
Please suggest me something about creating a DTO automatically.

Given that it sounds like you've worked out how to get an XML schema definition (XSD) you could use XSD.exe to generate the classes or there's even online tools for it... And if you want something really custom, you could look into T4 Text Templates.

Related

DataTypeAnnotations MetadataType not working as expected

I try to implement Metadatatype, in order to seperate Validation attributes from my Acquisitiecode class, into the AcquisitiecodeAnnotations class.
Now when I add attributes (like Required, StringLength and so on) to the Acquisitiecode class, validation works as expected. When I move these attributes to the AcquisitiecodeAnnotations class and bind this class using the MetadataType attribute, I does not work.
Please find the code examples below (I've stripped them down for readability). Also, the project is an ASP.NET Core 3.0 web application. All code, including the examples are also running in.NET Core 3.0 projects.
Snippet 1:
using System;
using System.ComponentModel.DataAnnotations;
namespace Shared.Entities
{
[MetadataType(typeof(AcquisitiecodeAnnotations))]
public partial class Acquisitiecode
{ }
public partial class AcquisitiecodeAnnotations
{
[StringLength(4, ErrorMessage = "The value cannot exceed 4 characters. ")]
public string Acquisitiecode1 { get; set; }
}
}
Snippet 2:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Shared.Entities
{
public partial class Acquisitiecode
{
public Acquisitiecode()
{
Lidmaatschap = new HashSet<Lidmaatschap>();
}
public string Acquisitiecode1 { get; set; }
public virtual Lid Lid { get; set; }
public virtual ICollection<Lidmaatschap> Lidmaatschap { get; set; }
}
}
As of October 2020 the current version of Blazor does not support Metadatatype.
For more information please read this issue.

How to use <list> with modelView

I'm trying to Graph Excel data using ChartJS.
Visual Studio is saying that List<Graphs> does not contain a definition for Answers.
I can't find anything wrong with my code, though. Though, I've only been using VS for the past two days.
Can someone look at my code and maybe find a mistake, or two? Thanks!
ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using ReinovaGrafieken.Models;
namespace ReinovaGrafieken.Models
{
public class GraphDataViewModel
{
public List<Graphs> GraphData { get; set; }
}
}
Graphs Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReinovaGrafieken.Models;
namespace ReinovaGrafieken.Models
{
public class Graphs
{
public string Names { get; set; }
public string AnswerHeaders { get; set; }
public int Answers { get; set; }
public string Questions { get; set; }
public string AnteOrPost { get; set; }
}
}
And a piece of the code from the View:
#model ReinovaGrafieken.Models.GraphDataViewModel
#{
ViewBag.Title = "Dashboard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<h2>Dashboard</h2>
<div id="chart_container">
<canvas id="bar_chart"></canvas>
<script>
var answers = #Html.Raw(Json.Encode(#Model.GraphData.Answers));
var labels = #Html.Raw(Json.Encode(#Model.GraphData.Names));
This is where I got the ideas from, where it does work for that person:
https://www.youtube.com/watch?v=E7Voso411Vs&t=2787s
GraphData is collection of Graph. So Answers is accessible property on Graph and not GraphData.
Like #Stephen Muecke wrote, List<T> does not contain a property named Answers.
You could take element, which you need like this:
#Model.GraphData.First().Answers
(get first element from the list).
Or you can use .Foreach() method

If I know the length of a string, should I declare it as a char with specific length

I'm preparing an Entity Framework model (CODE FIRST) for my C#.NET project. It dawned on me that I was going to have PageTitles stored as strings which have no length restrictions apart from the max and minimum bits available.
I have assumed that if I know a string will be 255 characters long and never exceed that, I could declare my string as a new char[255].
What are the downsides of using char instead of string.
What are the upsides of using char instead of string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ContentManagementSystem.Models
{
public class Page
{
int Id { get; set; }
string PageTitle { get; set; }
// This seems wasteful and unclear
char[] PageTitle = new char[255];
// How would i apply { get; set; } to this?
}
}
Is there some way of restricting a strings size?
---------------ANSWERED---------------------
This is now my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace ContentManagementSystem.Models
{
public class Page
{
public int Id { get; set; }
[MaxLength(255)] public string Title { get; set; }
[MaxLength(255)] public string Description { get; set; }
public string Content { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<Page> Pages { get; set; }
}
}
No, you should not use a char[] when you intend to operate on it as a string. Why? Beacuse string has a ton of useful methods that will be unavailable to you if you use a character array. Performance benefits of a character array, if any, would be exceedingly minimal.
EDIT: As DamienG pointed out, this will only work in case of code first.
Are you looking for this?
[MaxLength(255)]
public string PageTitle { get; set; }
Referenced dll:
Assembly System.ComponentModel.DataAnnotations.dll
Referenced namespace:
namespace System.ComponentModel.DataAnnotations
I wouldn't store strings as chars as you'll be forever cursing as you pass them around to things that want a string.
You can specify a maximum length for a string in Entity Framework using the designer for model-first or using the MaxLength attribute on the property for Code First models.
Use the StringLength attribute to inform the framework about the maximum length. You can continue to use strings instead of character arrays.
using System.ComponentModel.DataAnnotations;
...
[StringLength(255)]
public string PageTitle { get; set; }
Using the StringLength attribute in this case may be preferable to the MaxLength attribute because StringLength can also used by the model validation framework to validate user input.
If basic inconvenience is note enough to convince you not to do so - it is also against API design guidelines for C#/.Net - returning arrays via get/set methods is not recommended due to unclear behavior (is it copy/reference) and potential performance impact due to copying large arrays.
When you re-read your sample code you will already know the answer - it is bad idea to replace string with char[255] in public API because it will be very hard to deal with - you don't know how to set it. Most people will expect "XxxxxTitle" property to be be of any type string.
If you need to put length restriction - just enforce it in set method.

Is it possible to have a field named bool in C#?

I am sitting playing with elastic search from C#, and I wanted to create a query using an anonymous type in C# serialized to JSON. But I ran in to a problem as I need JSON that looks like this in one part:
{"bool": {<unimportant for question>}}
This would translate into a c# class that has a field named bool. Is this possible? (My guess is no...)
I think I will need custom serialization, or maybe elastic search provides some other alternative name for bool.
If you want to name variables the same as keywords you can prefix them with #.
bool #bool = false;
I would avoid doing this in ALL circumstances where possible. It's just plain confusing.
You can set the name in a [DataMember] attribute, but you need to use real classes (not anonymous).
using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the DataContractSerializer.
[DataContract()]
class Enterprise : IExtensibleDataObject
{
[DataMember(Name = "bool")]
public bool CaptainKirk {get; set;}
// more stuff here
}
More Info: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx
Use the DateMember attribute to specify what the serialised name is:
[DataMember(Name = "bool")]
public string MyBoolean { get; set; }
See also: JavaScriptSerializer.Deserialize - how to change field names

Enum Class Calling

I have created Enum class of LeaveReason in data access layer having values sick leave,planned leave or other reason now i want to call this enum class to my custom type layer but how to call it ???
please help as i am new in c#...
here is my code looks like.....
In Data Access layer :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sherserve.DataAccessLayer
{
public enum LeaveReason
{
Sick,
Planned,
Other
}
}
In Data Custom Type layer :
Now i want to access enum class which i created in data access layer in custom type layer.
You can see i have added reference of data access layer but it is showing error..
please correct this and tell me how i can call enum class in custom type layer.
using System;
using System.Collections.Generic;
using System.Text;
using Sherserve.DataAccessLayer;
namespace Sherserve.CustomTypeLayer
{
public class EmployeeLeave
{
public LeaveReason LeaveType { get; set; }
public int EmployeeId { get; set; }
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public string Reason { get; set; }
}
}
my problem is that i am un able to call enum class from data access to custom type and also i am unable to add reference of data access class to custom type...
please guide me properly..
thanks
You need to add a reference to the Sherserve.DataAccessLayer in the Sherserve.CustomTypeLayer. Typically the Sherserve.CustomTypeLayer would be a class library project that its output is a .dll file that you add to the other dataaccess layer from references -> add reference.

Categories

Resources