How to Get NSwagStudio to Generate C# Contract with ReadOnly Attribute? - nswagstudio

I'm running NSwagStudio v13.15.10.0 to create C# client/contract files.
I want the ReadOnly model attribute to be including in the generated C# Contract. Is this possible?
Given a sample Person model containing:
/// <summary>
/// Person Actual Birthdate (yyyy-mm-dd)
/// </summary>
public DateOnly Birthdate { get; set; }
/// <summary>
/// Computed Next Birthday Relative to Today (yyyy-mm-dd)
/// </summary>
[ReadOnly(true)]
public DateOnly NextBirthday { get; }`
The resulting swagger schema shows:
Birthdate string($date)
NextBirthday string($date)
readOnly: true`
And the JSON contains:
"Birthdate": {
"type": "string",
"format": "date"
},
"NextBirthday": {
"type": "string",
"readOnly": true,
"format": "date"
},`
The resulting Contracts.cs contains:
[Newtonsoft.Json.JsonProperty("Birthdate", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]
public System.DateTimeOffset Birthdate { get; set; }
[Newtonsoft.Json.JsonProperty("NextBirthday", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]
public System.DateTimeOffset NextBirthday { get; set; }
I want the NextBirthday to include this additional attribute:
[System.ComponentModel.ReadOnly(isReadOnly : true)]
resulting in:
[Newtonsoft.Json.JsonProperty("NextBirthday", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]
[System.ComponentModel.ReadOnly(isReadOnly : true)]
public System.DateTimeOffset NextBirthday { get; set; }
It looks like I'd need to modify this file: https://github.com/RicoSuter/NJsonSchema/blob/master/src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.liquid
I'm not sure how to modify a "liquid" file or how to rebuild NSwagStudio but I don't want a custom version of NSwag. I'm looking for a better solution that doesn't involve me editing the Contracts.cs each time.

Related

Creating List<dynamic> using Dynamic variable in C#

JSON Output
{
"balance":100.0,
"trc10": [{
"TR7NHqjeK": "10000000",
"KQxGTCi8": "20000000"
}],
"trc20": [{
"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t": "10000000",
"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjL56": "40000000"
}]
}
public class Root
{
public double balance { get; set; }
public List<dynamic> trc10 { get; set; }
public List<dynamic> trc20 { get; set; }
}
The code to transform the JSON would look something like this:
c# code
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Response.Write((myDeserializedClass.balance).ToString());
myDeserializedClass.balance output - 100.0
how to gat value of trc10,trc20 List item with select and where query
like myDeserializedClass.trc20.Where(x => x.TR7NHqjeKQxGTCi8q8ZY4pL8otSsssj6t == "TR7NHqjeKQxGTCi8q8ZY4pL8otSsssj6t")

asp net core unit test model validator not covered non required fields

I have added model validator to validate to model. it's covered only required fields but not others.
public static class TestModelHelper
{
public static IList<ValidationResult> Validate(object model)
{
var results = new List<ValidationResult>();
var validationContext = new ValidationContext(model, null, null);
Validator.TryValidateObject(model, validationContext, results, true);
if (model is IValidatableObject)
{
(model as IValidatableObject).Validate(validationContext);
}
return results;
}
}
public class Employee
{
[Key]
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[Required]
[JsonProperty("emailId")]
public string EmailId { get; set; }
}
using below command to generate the code coverage report.
dotnet test --collect:"XPlat Code Coverageā€
reportgenerator "-reports:./TestResults/{testresultsId}/coverage.cobertura.xml" "-targetdir:coveragereport" "-"reporttypes:Html"
in this model emailId only covered in code coverage. id and name are not covered.
According to your codes, I don't found any validate attribute for the Name and Id, if you want to test validate result, you should put some validate attributes for them.
More details, you could refer to below codes and try again.
public class Employee
{
[JsonProperty("id")]
[Range(0, 999.99)]
public int Id { get; set; }
[StringLength(100)]
[JsonProperty("name")]
public string Name { get; set; }
[Required]
[JsonProperty("emailId")]
public string EmailId { get; set; }
}

How to retrieve list from DB to front-end with AutoMapper

After changing the mapping to Automapper, only an empty list is sent through the endpoint.
Initially I had an endpoint that retrieved all employees with info including a list with every course each employee had taken. This was with manual mapping between entities & Dto.
//From startup.cs in Configure
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Employee, Models.EmployeeCoursesDto>();
cfg.CreateMap<Employee, Models.EmployeeDto>();
cfg.CreateMap<EmployeeCourses, Models.EmployeeCoursesDto>();
});
//From Employee entity
public class Employee
{
[Key]
//Gen new Id key in DB when object created
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(50)]
public string Title { get; set; }
public ICollection<EmployeeCourses> EmployeeCourses { get; set; }
= new List<EmployeeCourses>();
}
}
//From employee Dto
public class EmployeeDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public ICollection<EmployeeCoursesDto> EmployeeCourses { get; set; }
= new List<EmployeeCoursesDto>();
}
}
//Endpoint in controller
[HttpGet()]
public IActionResult GetAllEmployees()
{
var employeeEntities = _employeeInfoRepository.GetEmployees();
var results = Mapper.Map<IEnumerable<EmployeeDto>>(employeeEntities);
return Ok(results);
}
//From Irepository
IEnumerable<Employee> GetEmployees();
//From repository
public IEnumerable<Employee> GetEmployees()
{
return _context.Employees.OrderBy(c => c.Name).ToList();
}
I expected output all employees with all datafileds, including their list of courses.
The output is all fields with data, except the list of courses which is "0" when running with a breakpoint, and in Postman it shows as only:
"id": 2,
"name": "Test Person",
"title": "Bus Driver",
"numberOfCourses": 0,
"employeeCourses": [],
"totalAchievedHoursAuditor": 0,
"totalAchievedHoursAccountant": 51,
"courseBalanceAccountant": null,
"courseBalanceAuditor": null
However, if I try another endpoint only for retrieving a specific course, or a list of courses, the data show correctly. Seems there are an issue with mapping the employees & courses at the same time?
I found the error, not Automapper, but my Linq statement:
return _context.Employees.Include(c => c.EmployeeCourses).ToList();
Please close this thread. Thanks for the reply Lucian Bargaoanu & have a great weekend.

How to map DropList in Sitecore Glass.Mapper

I am mapping Sitecore Items using GlassMapper v5 in Sitecore.
We implemented the following classes with GlassMapper.
However, although the value of the field is acquired for the ItemTemplate item, the value of the Droplist field (CategoryTemplate) created in the ItemTemplate has been returned as NULL and it can not be acquired.
[SitecoreType(TemplateId = "9876...", AutoMap = true)]
public class ItemTemplate
{
[SitecoreParent]
public virtual Common Parent { get; set; }
[SitecoreField(FieldName = "Category", FieldType = SitecoreFieldType.Droplist)]
public virtual CategoryTemplate Category { get; set; }
}
[SitecoreType(TemplateId = "1234...", AutoMap = true, TemplateName = "CategoryTemplate")]
public class CategoryTemplate
{
[SitecoreField(FieldName = "Id")]
public virtual string CategoryId { get; set; }
[SitecoreField(FieldName = "Name")]
public virtual string CategoryName { get; set; }
}
Environment information:
- Sitecore 9.0.2
- GlassMapper 5.0.6.0
What am I missing, please?
Try SitecoreFieldType.DropLink. The DropList type stores string value. Your template need to change to droplink too.

Is there a way to add custom web services to Word 2010 via the Research Pane?

I have been wondering if I can add custom web services with the wsdl or asmx file extension via the Research Pane in Microsoft Word 2010. I have searched just about every site that has those services, but no luck finding instructions. Rather than trial and error, I felt more confident if I were to ask someone here.
Basically, what I would like to be able to do is add a site like http://www.ebi.ac.uk/Tools/webservices/wsdl or some other source and be able to send queries via the research pane.
Start by reading this http://msdn.microsoft.com/en-us/library/bb226691(v=office.11).aspx
Then the shortcut bellow (it's not perfect, and the actual search is not implemented, but I hope it helps)
1 Service interface
namespace CustomResearchServiceWCF {
[ServiceContract(Namespace="urn:Microsoft.Search")]
public interface IOfficeResearchService
{
[OperationContract(Action = "urn:Microsoft.Search/Registration")]
string Registration(string regXML);
[OperationContract(Action = "urn:Microsoft.Search/Query")]
string Query(string queryXml);
}
}
2 Implementation
namespace CustomResearchServiceWCF
{
public class OfficeResearchService : IOfficeResearchService
{
public string Registration(string regXML)
{
var providerUpdate = new ProviderUpdate();
var writerSettings = new XmlWriterSettings {OmitXmlDeclaration = true,Indent=true};
var stringWriter = new StringWriter();
var serializer = new XmlSerializer(typeof(ProviderUpdate));
using (var xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
serializer.Serialize(xmlWriter, providerUpdate);
}
return stringWriter.ToString();
}
public string Query(string queryXml)
{
throw new NotImplementedException();
}
}}
3 ProviderUpdate, ResearchService and License
namespace CustomResearchServiceWCF
{
public class License
{
[XmlAttribute(AttributeName = "acceptRequired")]
public bool AcceptRequired;
public string LicenseText { get; set; }
public License()
{
LicenseText = "some licensing information";
AcceptRequired = true;
}
}
public class Provider
{
public string Message { get; set; }
public License License { get; set; }
public string Id { get; set; }
public string Name { get; set; }
public string QueryPath { get; set; }
public string RegistrationPath { get; set; }
public string Type { get; set; }
public string AboutPath { get; set; }
[XmlAttribute]
public string Action { get; set; }
[DataMember]
public List<ResearchService> Services;
public Provider()
{
Type = "SOAP";
License = new License();
Services = new List<ResearchService>
{
new ResearchService
{
Id = "{942F685E-0935-42c8-80C5-95DB0D129910}",
Name = "Service",
Description = "Custom Research Service",
Copyright = "All content Copyright (c) 2003",
Display = "ON"
}
};
}
}
[XmlType("Service")]
public class ResearchService
{
/// <summary>
/// The GUID that is used when the Query function is called to differentiate a response from your Research service from a response from another Research service
/// </summary>
public string Id { get; set; }
/// <summary>
/// The name displayed in the Research task pane's Show Results From dropdown
/// </summary>
public string Name { get; set; }
/// <summary>
/// //The description displayed in the Properties dialog box for the service
/// </summary>
public string Description { get; set; }
public string Copyright { get; set; }
//Either On or Off; indicates whether the service should be displayed in the Show Results From dropdown.
public string Display { get; set; }
/// <summary>
/// The category with which the service should be grouped in the Show Results From dropdown and the Research options dialog box. See the Microsoft.Search.Registration.Response schema for a list of all the choices.
/// </summary>
public string Category { get; set; }
public ResearchService()
{
Category = "RESEARCH_GENERAL";
}
}
[XmlRoot(Namespace = "urn:Microsoft.Search.Registration.Response")]
public class ProviderUpdate
{
public string Status { get; set; }
public List<Provider> Providers;
public ProviderUpdate()
{
Status = "SUCCESS";
Providers = new List<Provider>
{
new Provider
{
Message = "Congratulations! You've registered Research Pane Examples!",
Action = "UPDATE",
Id = "{942F685E-0935-42c8-80C5-95DB0D129910}",
Name = "Wiktionary",
QueryPath = "http://services.highbeam.com/office/office.asmx",
RegistrationPath = "http://services.highbeam.com/office/office.asmx",
AboutPath = "http://www.highbeam.com"
}
};
}
}
}