C# swagger documentation for individual members of the request body object - c#

We are writing swagger documentation using /// comments in the following way:
/// <summary>
/// Create a new widget
/// </summary>
/// <param name="widget"></param>
[HttpPost("/create")]
[ProducesResponseType(typeof(IPayment), 200)]
[ProducesResponseType(typeof(ErrorResult), 400)]
[ProducesResponseType(typeof(ErrorResult), 404)]
public Task<IActionResult> CreateWidget([FromBody] Widget widget)
{
Now Widget is an implementation of IWidget and the user of the documentation should know in detail what each data member of Widget / IWidget means, what's mandatory, what's optional, and valid values.
We found that the only place to add this description is in
/// <param name="widget">very big multi line description</param>
While this works for the end user, is there a better way? We ask this because it is much more maintainable if the descriptions are provided inline in the class / interface definition.

On the same way you document your actions with the /// comments you can also document your models
Here is an example:
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=Location#/Location/Location_Get2
The code for that looks like:
/// <summary>
/// ## Geographic coordinates
/// ___
/// A **geographic coordinate system** is a coordinate system used in geography that enables every location on Earth
/// </summary>
public class Location
{
/// <summary>**Latitude**: a geographic coordinate that specifies the north–south position of a point on the Earth's surface.</summary>
/// <example>25.85</example>
[Range(-90, 90)]
public float Lat { get; set; }
/// <summary>**Longitude**: a geographic coordinate that specifies the east-west position of a point on the Earth's surface.</summary>
/// <example>-80.27</example>
[Range(-180, 180)]
public float Lon { get; set; }
}
This is how it looks like:
On Post or Put requests the documentation can also be seen on the model tab:
https://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=Company
And as usual under the Models:

Related

Provide a complex object for a SwaggerExample?

We're using Swagger.Net package to help with our documentation.
I'm trying to add request data to be auto-generated into my documentation and was looking at this answer that provides this code block:
[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{...}
I'm not sure how I can translate that int into a more complex object. For example:
[Route("SaveCustomThing"), HttpPost]
[SwaggerExample("thing", ???)]
public HttpResponseMessage SaveCustomThing([FromBody] Thing thing)
{...}
How do I pass a pre-configured Thing object in the SwaggerExample attribute?
Looking at the code that attribute (SwaggerExample) takes two parameters:
public SwaggerExampleAttribute(string parameterName, object example)
{
this.ParameterName = parameterName;
this.Example = example;
}
https://github.com/heldersepu/Swagger-Net/blob/6afdb0c1ba611273f27e8a904ec2bb06a630b1b4/Swagger.Net/Swagger/Annotations/SwaggerExampleAttribute.cs#L16
We can see the first one is a string but second is an object...
In theory you should be able to pass anything there.
Another alternative I would recommend, if you have complex models like your Thing you should consider adding the examples on the model, we can do a lot more there... as you can see below we can add description, example values and with some other decorators we can limit the range of values code looks like:
/// <summary>
/// ## Geographic coordinates
/// ___
/// A **geographic coordinate system** is a coordinate system used in geography that enables every location on Earth to be specified by a set of numbers
/// </summary>
public class Location
{
/// <summary>**Latitude**: a geographic coordinate that specifies the north–south position of a point on the Earth's surface.</summary>
/// <example>25.85</example>
[Range(-90, 90)]
public float Lat { get; set; }
/// <summary>**Longitude**: a geographic coordinate that specifies the east-west position of a point on the Earth's surface.</summary>
/// <example>-80.27</example>
[Range(-180, 180)]
public float Lon { get; set; }
}
http://swagger-net-test.azurewebsites.net/swagger/ui/index#/Location/Location_Get2

tiles for offline telerik wpf map

Problem Summary
I am trying to create an offline tiled map for a WPF application that uses telerik. The user does not need to zoom in very far. I am having trouble finding a source of tiles that can be implemented with telerik.
What I've tried
I am using RadMap from telerik for WPF. They have an option for implementing tiles from a custom tile provider. I have been trying to follow the solutions given in this forum and this forum. They recommend downloading tiles from Easy OpenStreetMap Downloader, but it the file format does not match the code. It appears in the code, the tiles should be grouped in folders according to zoom level, then in a folder according to x coordinate. However, it looks to me like openstreetmaps downloader groups them by y coordinate only. I either need to get openstreetmaps downloader to save the tiles in this format, or to find another provider that will.
Code
Here is the telerik code that I am trying to base my solution off of:
/// <summary>
/// Tile source which read map tiles from the file system.
/// </summary>
public class FileSystemTileSource : TiledMapSource
{
private string tilePathFormat;
/// <summary>
/// Initializes a new instance of the FileSystemTileSource class.
/// </summary>
/// <param name="tilePathFormat">Format string to access tiles in file system.</param>
public FileSystemTileSource(string tilePathFormat)
: base(1, 20, 256, 256)
{
this.tilePathFormat = tilePathFormat;
}
/// <summary>
/// Initialize provider.
/// </summary>
public override void Initialize()
{
// Raise provider intialized event.
this.RaiseIntializeCompleted();
}
/// <summary>
/// Gets the image URI.
/// </summary>
/// <param name="tileLevel">Tile level.</param>
/// <param name="tilePositionX">Tile X.</param>
/// <param name="tilePositionY">Tile Y.</param>
/// <returns>URI of image.</returns>
protected override Uri GetTile(int tileLevel, int tilePositionX, int tilePositionY)
{
int zoomLevel = ConvertTileToZoomLevel(tileLevel);
string tileFileName = this.tilePathFormat.Replace("{zoom}", zoomLevel.ToString(CultureInfo.InvariantCulture));
tileFileName = tileFileName.Replace("{x}", tilePositionX.ToString(CultureInfo.InvariantCulture));
tileFileName = tileFileName.Replace("{y}", tilePositionY.ToString(CultureInfo.InvariantCulture));
if (File.Exists(tileFileName))
{
return new Uri(tileFileName);
}
else
{
return null;
}
}
}
/// <summary>
/// Map provider which read map tiles from the file system.
/// </summary>
public class FileSystemProvider : TiledProvider
{
/// <summary>
/// Initializes a new instance of the MyMapProvider class.
/// </summary>
/// <param name="tilePathFormat">Format string to access tiles in file system.</param>
public FileSystemProvider(string tilePathFormat)
: base()
{
FileSystemTileSource source = new FileSystemTileSource(tilePathFormat);
this.MapSources.Add(source.UniqueId, source);
}
/// <summary>
/// Returns the SpatialReference for the map provider.
/// </summary>
public override ISpatialReference SpatialReference
{
get
{
return new MercatorProjection();
}
}
}
public MainWindow()
{
InitializeComponent();
this.radMap.Provider = new FileSystemProvider("Path to OpenStreet Images\\{zoom}\\{x}\\os_{x}_{y}_{zoom}.png");
}

Should Controllers read custom app settings from web.config?

In my mvc application during certain times of the year we want to show one of two links. Basically I have to switch the link when I get a call from management. So, I thought instead of having to recompile the app I would add a custom app setting to the web.config file. Then I created a wrapper so that it is strongly typed. Now, my problem is I don't know where to execute the logic. Should add a property to my view model and set it in the controller based on the configuration setting value? Or should I read it directly in my View and toggle between the two links? I'm pretty sure this only belongs in the view or the controller, and not the service layer, since it is used specifically for UI stuff.
Details.cshtml //current code
#if(Search.App.ParcelDetailDisplayMode == Search.App.DisplayMode.Tax ){
<a id="tax-link" href="#taxlink" title="View Tax Bill on Tax Collectors Website">Tax Bill</a>
}
else if(Search.App.ParcelDetailDisplayMode == Search.App.DisplayMode.Trim ){
<a id="trim-link" href="#trimlink" title="View your TRIM notice online">Trim Notice</a>
}
web.config
<add key="ParcelDetailDisplayMode" value="Tax"/>
config wrapper
namespace Search
{
/// <summary>
/// The app.
/// </summary>
public static class App
{
/// <summary>
/// Gets the tax bill link.
/// </summary>
public static string TaxBillLink
{
get
{
return ConfigurationManager.AppSettings["TaxBillLink"];
}
}
/// <summary>
/// Gets the trim notice link.
/// </summary>
public static string TrimNoticeLink
{
get
{
return ConfigurationManager.AppSettings["TrimLink"];
}
}
/// <summary>
/// Gets the map link.
/// </summary>
public static string MapLink
{
get
{
return ConfigurationManager.AppSettings["MapLink"];
}
}
/// <summary>
/// Gets the update address link.
/// </summary>
public static string UpdateAddressLink
{
get
{
return ConfigurationManager.AppSettings["UpdateAddressLink"];
}
}
/// <summary>
/// Gets the release name.
/// </summary>
public static string ReleaseName
{
get
{
return ConfigurationManager.AppSettings["ReleaseName"];
}
}
/// <summary>
/// Gets the parcel detail display mode.
/// </summary>
public static DisplayMode ParcelDetailDisplayMode
{
get
{
var r = DisplayMode.Tax;
DisplayMode.TryParse(ConfigurationManager.AppSettings["ParcelDetailDisplayMode"], out r);
return r;
}
}
/// <summary>
/// The display mode.
/// </summary>
public enum DisplayMode
{
/// <summary>
/// The trim.
/// </summary>
Trim,
/// <summary>
/// The tax.
/// </summary>
Tax
}
}
}
I would say it does not really matter. Adding it as a property of your model feels to give a little bit more separation.
What does matter though is that your wrapper is static. This will make it really difficult to mock it for the purpose of unit testing (or any other purpose)
There should be no logic in the controller.
Read this for example: Where should I put my controller business logic in MVC3
or this one: https://softwareengineering.stackexchange.com/questions/165444/where-to-put-business-logic-in-mvc-design
I know it's tempting but the less logic you put there the best you will find yourself in the future.
the answer in my opinion is:
You should read your property in a business layer benhead the controller and pass it all the way up to the view in a model object.
I agree with Maurizio in general that all business logic should be in some service/business logic layer. However in this case since you're only fetching a value from web.config whether, in your controller action, you do:
var someValue = App.TaxBillLink;
or you do:
var someValue = _linkService.GetTodaysLink();
really doesn't matter much unless there is some sort of logic there that needs to be unit tested.

Implementing a feature to track if the user is repeating a search

I have a view model that represents all the fields available for searching. I'd like to add some logic that would be able to identify if the search values are all the same and determine whether to hit the DB again for their query.
I think I would have to do something like..
after user submits form save form values to some
temporary field.
upon second submission compare temp value to form values collection.
if values are equal set property in view
model IsSameSearch = true
I'd like to use the Post Redirect Get Pattern too. So that My search View doesn't do anything except post the form values to another action that processes and filters the data, which is then "Getted" using Ajax.
The SearchViewModel contains many many search parameters. Here is an abbreviated version.
public bool UseAdvancedSearch { get; set; }
public bool isSameSearch { get; set; }
/// <summary>
/// Gets or sets the page.
/// </summary>
[HiddenInput]
[ScaffoldColumn(false)]
public int Page { get; set; }
[HiddenInput]
[ScaffoldColumn(false)]
public string SortOption { get; set; }
/// <summary>
/// Gets or sets the address keywords.
/// </summary>
[Display(Name="Address")]
public string AddressKeywords { get; set; }
/// <summary>
/// Gets or sets the census.
/// </summary>
public string Census { get; set; }
/// <summary>
/// Gets or sets the lot block sub.
/// </summary>
public string LotBlockSub { get; set; }
/// <summary>
/// Gets or sets the owner keywords.
/// </summary>
[Display(Name="Owner")]
public string OwnerKeywords { get; set; }
/// <summary>
/// Gets or sets the section township range.
/// </summary>
public string SectionTownshipRange { get; set; }
/// <summary>
/// Gets or sets the strap.
/// </summary>
///
[Display(Name="Account Number/Parcel ID")]
public string Strap { get; set; }
/// <summary>
/// Gets or sets the subdivision.
/// </summary>
public string Subdivision { get; set; }
/// <summary>
/// Gets or sets the use code.
/// </summary>
[Display(Name = "Use Code")]
public string UseCode { get; set; }
/// <summary>
/// Gets or sets the zip code.
/// </summary>
[Display(Name="Zip Code")]
public string ZipCode { get; set; }
If you are getting data from Entity Framework you could cache the data at EF level. Look at the package entity framework extended https://github.com/loresoft/EntityFramework.Extended. It is as simple as adding method .FromCache () to the query you use to retrieve and filter the data and it will cache the query result. Make sure you load all the data required using includes etc.
You wouldn't have to worry about same search in model as the caching provider would look at filter settings and determine that it was different. Alternatively cache the data before filtering and then filter the cached results. This is more appropriate if you have lots of filter parameters with significant variance as you will only have to cache 1 large result rather than thousands of smaller results.
You can get more advanced and specify cache period e.g. Cache for 10 minutes
What you are describing is called caching.
One way to accomplish that in your scenario would be to implement GetHashCode() in a way that it would take into account all your fields/properties to compute a unique value. That way you can use your Hash as the key entry in your cache, and store the results with that key.
For that actual caching you could just use the MemoryCache class provided by the .Net Framework if you are not deploying to a web farm.
Also, if you are familiar with IoC and DI (such as using Unity), things like this can be implemented as an Interceptor, and only requiring you to add an attribute to the method you'd like to cache. That way you implement caching only once as a cross-cutting concern and not fill up your application code with things like this.

property inaccessible due to protection level?

This is the line that the error is showing on:
public IOAuth2ServiceProvider<IElance> ElanceServiceProvider { get; set; }
It's showing the error on the IElance Type on that line, but here's the interface:
public interface IElance : IApiBinding
{
/// <summary>
/// Search all jobs, list jobs associated with an employee or a freelancer, and retrieve information for a specific job.
/// </summary>
IJobOperations JobOperations { get; }
/// <summary>
/// Access all messages, users, messages, and Work View™ data associated with an Elance Workroom.
/// </summary>
IWorkRoomOperations WorkroomOperations { get; }
/// <summary>
/// View all of the information associated with an employee or a freelancer.
/// </summary>
IProfileOperations ProfileOperations { get; }
/// <summary>
/// View detailed information on freelancers, and retrieve a list of all freelancers employed by an employer.
/// </summary>
IFreelancerOperations FreelancerOperations { get; }
/// <summary>
/// List Elance groups, and retrieve lists of members and jobs belonging to a group.
/// </summary>
IGroupOperations GroupOperations { get; }
/// <summary>
/// Obtain ancillary Elance information, such as the current list of all job categories.
/// </summary>
IUtilityOperations UtilityOperations { get; }
}
I can't for the life of me figure out why it's telling me this. Am I missing something obvious? I would greatly appreciate any direction on this error.
This is probably caused by IApiBinding or one of its base interfaces not being public. Another possibility is that one of the types used by the interface members is not public.

Categories

Resources