Skip to content

Adding sample for WebApiAdaptor #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions WebApiAdaptor/WebApiAdaptor.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApiAdaptor", "WebApiAdaptor\WebApiAdaptor.csproj", "{B49DB687-BD93-4E24-81A7-BC203C7A013C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B49DB687-BD93-4E24-81A7-BC203C7A013C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B49DB687-BD93-4E24-81A7-BC203C7A013C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B49DB687-BD93-4E24-81A7-BC203C7A013C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B49DB687-BD93-4E24-81A7-BC203C7A013C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9B172FC0-45F9-4429-9368-D37F6CFE6DAE}
EndGlobalSection
EndGlobal
177 changes: 177 additions & 0 deletions WebApiAdaptor/WebApiAdaptor/Controllers/GridController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApiAdaptor.Models;

namespace WebApiAdaptor.Controllers
{
[Route("api/[controller]")]

[ApiController]
public class GridController : ControllerBase
{
// GET: api/Orders
[HttpGet]

// Action to retrieve orders
public object Get()
{
var queryString = Request.Query;
var data = OrdersDetails.GetAllRecords().ToList();

string? sort = queryString["$orderby"]; // Get sorting parameter
string? filter = queryString["$filter"]; // // Get filtering parameter

//Peform sort operation
if (!string.IsNullOrEmpty(sort))
{
var sortConditions = sort.Split(',');

var orderedData = data.OrderBy(x => 0); // Start with a stable sort

foreach (var sortCondition in sortConditions)
{
var sortParts = sortCondition.Trim().Split(' ');
var sortBy = sortParts[0];
var sortOrder = sortParts.Length > 1 && sortParts[1].ToLower() == "desc";

switch (sortBy)
{
case "OrderID":
orderedData = sortOrder ? orderedData.ThenByDescending(x => x.OrderID) : orderedData.ThenBy(x => x.OrderID);
break;
case "CustomerID":
orderedData = sortOrder ? orderedData.ThenByDescending(x => x.CustomerID) : orderedData.ThenBy(x => x.CustomerID);
break;
case "ShipCity":
orderedData = sortOrder ? orderedData.ThenByDescending(x => x.ShipCity) : orderedData.ThenBy(x => x.ShipCity);
break;
}
}

data = [.. orderedData];
}
if (filter != null)
{
var filters = filter.Split(new string[] { " and " }, StringSplitOptions.RemoveEmptyEntries);

foreach (var filterItem in filters)
{
if (filterItem.Contains("substringof"))
{
// Performing Search operation

var searchParts = filterItem.Split('(', ')', '\'');
var searchValue = searchParts[3];

// Apply the search value to all searchable fields
data = data.Where(cust =>
cust != null &&
((cust.OrderID?.ToString()?.Contains(searchValue) ?? false) ||
(cust.CustomerID?.ToLower()?.Contains(searchValue) ?? false) ||
(cust.ShipCity?.ToLower()?.Contains(searchValue) ?? false))).ToList();
}
else
{
// Performing filter operation

var filterfield = "";
var filtervalue = "";
var filterParts = filterItem.Split('(', ')', '\'');
if (filterParts.Length != 9)
{
var filterValueParts = filterParts[1].Split();
filterfield = filterValueParts[0];
filtervalue = filterValueParts[2];
}
else
{
filterfield = filterParts[3];
filtervalue = filterParts[5];
}
switch (filterfield)
{
case "OrderID":
data = data.Where(cust => cust != null && cust.OrderID?.ToString() == filtervalue.ToString()).ToList();
break;
case "CustomerID":
data = data.Where(cust => cust != null && cust.CustomerID?.ToLower().StartsWith(filtervalue.ToString()) == true).ToList();
break;
case "ShipCity":
data = data.Where(cust => cust != null && cust.ShipCity?.ToLower().StartsWith(filtervalue.ToString()) == true).ToList();
break;
// Add more cases for other searchable fields if needed
}

}
}
}

int TotalRecordsCount = data.Count;

//Perform page operation

int skip = Convert.ToInt32(queryString["$skip"]);
int take = Convert.ToInt32(queryString["$top"]);
if (take != 0)
{
data = data.Skip(skip).Take(take).ToList();

}

return new { result = data, count = TotalRecordsCount };

}


// POST: api/Orders
[HttpPost]
/// <summary>
/// Inserts a new data item into the data collection.
/// </summary>
/// <param name="value">It holds new record detail which is need to be inserted.</param>
/// <returns>Returns void</returns>
public void Post([FromBody] OrdersDetails newRecord)
{
// Insert a new record into the OrdersDetails model
OrdersDetails.GetAllRecords().Insert(0, newRecord);
}

// PUT: api/Orders/5
[HttpPut]
/// <summary>
/// Update a existing data item from the data collection.
/// </summary>
/// <param name="order">It holds updated record detail which is need to be updated.</param>
/// <returns>Returns void</returns>
public void Put(int id, [FromBody] OrdersDetails order)
{
// Find the existing order by ID
var existingOrder = OrdersDetails.GetAllRecords().FirstOrDefault(o => o.OrderID == id);
if (existingOrder != null)
{
// If the order exists, update its properties
existingOrder.OrderID = order.OrderID;
existingOrder.CustomerID = order.CustomerID;
existingOrder.ShipCity = order.ShipCity;
}
}

// DELETE: api/Orders/5
[HttpDelete("{id}")]
/// <summary>
/// Remove a specific data item from the data collection.
/// </summary>
/// <param name="id">It holds specific record detail id which is need to be removed.</param>
/// <returns>Returns void</returns>
public void Delete(int id)
{
// Find the order to remove by ID
var orderToRemove = OrdersDetails.GetAllRecords().FirstOrDefault(order => order.OrderID == id);
// If the order exists, remove it
if (orderToRemove != null)
{
OrdersDetails.GetAllRecords().Remove(orderToRemove);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;

namespace WebApiAdaptor.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
58 changes: 58 additions & 0 deletions WebApiAdaptor/WebApiAdaptor/Models/OrdersDetails.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
namespace WebApiAdaptor.Models
{
public class OrdersDetails
{
public static List<OrdersDetails> order = new List<OrdersDetails>();
public OrdersDetails()
{

}
public OrdersDetails(
int OrderID, string CustomerId, int EmployeeId, double Freight, bool Verified,
DateTime OrderDate, string ShipCity, string ShipName, string ShipCountry,
DateTime ShippedDate, string ShipAddress)
{
this.OrderID = OrderID;
this.CustomerID = CustomerId;
this.EmployeeID = EmployeeId;
this.Freight = Freight;
this.ShipCity = ShipCity;
this.Verified = Verified;
this.OrderDate = OrderDate;
this.ShipName = ShipName;
this.ShipCountry = ShipCountry;
this.ShippedDate = ShippedDate;
this.ShipAddress = ShipAddress;
}

public static List<OrdersDetails> GetAllRecords()
{
if (order.Count == 0)
{
int code = 10000;
for (int i = 1; i < 10; i++)
{
order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16), "Kirchgasse 6"));
order.Add(new OrdersDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11), "Avda. Azteca 123"));
order.Add(new OrdersDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996, 10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
order.Add(new OrdersDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, new DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12, 30), "Magazinweg 7"));
order.Add(new OrdersDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997, 12, 3), "1029 - 12th Ave. S."));
code += 5;
}
}
return order;
}

public int? OrderID { get; set; }
public string? CustomerID { get; set; }
public int? EmployeeID { get; set; }
public double? Freight { get; set; }
public string? ShipCity { get; set; }
public bool? Verified { get; set; }
public DateTime OrderDate { get; set; }
public string? ShipName { get; set; }
public string? ShipCountry { get; set; }
public DateTime ShippedDate { get; set; }
public string? ShipAddress { get; set; }
}
}
27 changes: 27 additions & 0 deletions WebApiAdaptor/WebApiAdaptor/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseDefaultFiles();
app.UseStaticFiles();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
41 changes: 41 additions & 0 deletions WebApiAdaptor/WebApiAdaptor/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3916",
"sslPort": 44313
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5161",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
// "launchUrl": "swagger",
"applicationUrl": "https://localhost:7096;http://localhost:5161",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
13 changes: 13 additions & 0 deletions WebApiAdaptor/WebApiAdaptor/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace WebApiAdaptor
{
public class WeatherForecast
{
public DateOnly Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
}
Loading
Loading