Thursday, September 26, 2019

Working with swagger

Here is the way by which we can add swagger to dotnet core api and can customize it with our needs.

(1) To work with swagger search and add below package
Swashbuckle.AspNetCore

(2) Once this is added just to make sure to enter below line of codes under ConfigureServices method in Startup.cs
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Api", Version = "v1", Description = "" });
c.OperationFilter();// This will be your step - (4)
var xmlFile = "swagger.XML";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});

and add below line of code under Configure method in Startup.cs
app.UseSwagger();

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json", "API V1");
});

(3) swagger.xml file will contain
<doc>
  <assembly>
    <name>Api</name>
  </assembly>
 <members>
    <member name="T:Namespace of member">
      <summary>
        Summary of function
     </summary>
    </member>    
</doc>

(4) Adding SwaggerHeaderFilter
public class SwaggerHeaderFilter : IOperationFilter
{

public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
                operation.Parameters = new List();

IList filterDescriptors = context.ApiDescription.ActionDescriptor.FilterDescriptors;
            bool isAuthorized = filterDescriptors.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthenticationApiAttribute);

if (isAuthorized)
            {
// This will add parameters to each endpoint of passing access token
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "X-Auth-Token",
                    In = "header",
                    Type = "string",
                    Required = true,
                    Description = "access token"
                });

// This will add parameters to each endpoint of passing access token
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "UserId",
                    In = "header",
                    Type = "integer",
                    Required = true,
                    Description = "user id"
                });
            }

            if (String.IsNullOrWhiteSpace(operation.Description))
                operation.Description = "**Action Name**: " + ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ApiDescription.ActionDescriptor).ActionName;
            else
                operation.Description = "**Action Name**: " + ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ApiDescription.ActionDescriptor).ActionName + "  " + operation.Description;

}
}

This way you can configure your swagger with API and for each of the endpoint it will have access token and user id. You can add more parameters like this if you require. In step - (4), attribute created requires to register in step - (2).

Friday, September 20, 2019

Dot Net CORE Tips

(1) Razor Pages: For dotnet core application, we can have advantage of building Razor Pages just like we have ".axpx" pages in traditional web application. But there is also an added advantage of MVC pattern can be implemented with existing structure.

(2) Microsoft.Windows.Compatibility: This package is essential whenever we are performing any operation which is available in .net framework implementation.
for e.g. dataSet.Tables[0].AsEnumerable() - This functionality will not available until you will not add above package. As this is dot net native functionality and to laverage this we need this package support. There are many other functionalities are still there.

(3) File Operation: To perform file operation in web, we have practices of using Server.MapPath(filepath) to work with files. But with dotnet core web app this operation is replace with below
private IHostingEnvironment _env;

public MyController(IHostingEnvironment env)
        {
            _env = env;
        }
var webRoot = _env.WebRootPath;

Now, here _env.webRootPath will be your application wwwroot folder path and here you can perform your operation of saving/sp-net-core
- https://gunnarpeipman.com/aspnet/aspnet-core-content-web-root/
- https://www.mikesdotnetting.com/article/302/server-mappath-equivalent-in-asp-net-core
- https://stackoverflow.com/questions/43992261/how-to-get-absolute-path-in-asp-net-core-alternative-way-for-server-mappath

(4) Upload/Save Image
- https://www.codeproject.com/Tips/4051593/How-to-Upload-Images-on-an-ASP-NET-Core-2-2-MVC-We
- https://stackoverflow.com/questions/42741170/how-to-save-images-to-database-using-asp-net-core

(5) To get all the output in json with no case applied on output of json result, in this case just add below line of code to Startup.cs file under ConfigureServices function.
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

(6) To work with tag helpers below package to install
Microsoft.AspNetCore.Razor.Runtime

(7) To work with sessions user below package 
Microsoft.AspNetCore.Session

(8) Cookie Authentication
https://www.c-sharpcorner.com/article/cookie-authentication-with-asp-net-core-2-0/

(9) StaticFiles: to work with static files like images, html, js files use below  package
Microsoft.AspNet.StaticFiles

(10) It gives us access to the assemblies and classes provided by the framework.
Microsoft.AspNet.Mvc

(11) to build bundle files for css/js use below package
BuildBundlerMinifier
(1) https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier
(2) https://www.c-sharpcorner.com/article/bundling-and-minifying-in-asp-net-core-applications/
(3) https://docs.microsoft.com/en-us/aspnet/core/client-side/bundling-and-minification?view=aspnetcore-2.2&tabs=visual-studio

(12) When there is issue of tag is not properly rendered
- In this case, check with Taghelper is added to _ViewImport.cshtml page or not, if not then add like below
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
- https://github.com/aspnet/AspNetCore/issues/534