API Examples Returning various ...
API Examples
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
[ResponseType(typeof(Customer))]
public IHttpActionResult GetCustomer(string email)
{
Customer customer = db.Customers.Where(c=>c.Email== email).FirstOrDefault();
if (customer == null)
{
return NotFound();
}
return Ok(customer);
} }
// PUT: api/Customers/5
[ResponseType(typeof(void))]
public IHttpActionResult PutCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != customer.Id)
{
return BadRequest();
}
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
----
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
----
private bool CustomerExists(int id)
{
return db.Customers.Count(e => e.Id == id) > 0;
}
---
private readonly MemoryStream _Stream = new MemoryStream();
public JsonContent(object value)
{
Headers.ContentType = new MediaTypeHeaderValue("application/json");
var jw = new JsonTextWriter(new StreamWriter(_Stream));
jw.Formatting = Formatting.Indented;
var serializer = new JsonSerializer();
serializer.Serialize(jw, value);
jw.Flush();
_Stream.Position = 0;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _Stream.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length)
{
length = _Stream.Length;
return true;
}
public IHttpActionResult PostTaskStart(OrderManfTask orderManfTask)
{
List<OrderManfTask> items = new List<OrderManfTask>();
items = (from a in db.OrderManfTasks where a.OrderId == orderManfTask.OrderId && a.TaskId == orderManfTask.TaskId select a).ToList();
foreach (var i in items)
{
i.EmployeeName = orderManfTask.EmployeeName;
i.TaskId = orderManfTask.TaskId;
i.TaskEnd = orderManfTask.TaskEnd;
db.SaveChanges();
}
string tasktext = string.Empty;
switch (orderManfTask.TaskId)
{
case 1:
tasktext = "Cut";
break;
case 2:
tasktext = "Sewn";
break;
case 3:
tasktext = "Filled";
break;
}
//Add Note
OrderNote orderNote = new OrderNote();
orderNote.DownloadId = 0;
orderNote.OrderId = orderManfTask.OrderId;
orderNote.CreatedOnUtc = DateTime.Now;
orderNote.Note = "Production " + tasktext + " Task Completed by: " + orderManfTask.EmployeeName + " on " + DateTime.Now;
db.OrderNotes.Add(orderNote);
db.SaveChanges();
return Ok(new { success = true });
}
}
-----
public int PostTaskStart(OrderManfTask orderManfTask)
{
int items = 0;
int taskstarted = 0;
int taskEnded = 0;
items = (from a in db.OrderManfTasks where a.OrderId == orderManfTask.OrderId && a.TaskId == orderManfTask.TaskId select a.id).Count();
taskstarted = (from a in db.OrderManfTasks where a.OrderId == orderManfTask.OrderId && a.TaskId == orderManfTask.TaskId && a.TaskStart != null select a.id).Count();
taskEnded = (from a in db.OrderManfTasks where a.OrderId == orderManfTask.OrderId && a.TaskId == orderManfTask.TaskId && a.TaskEnd != null select a.id).Count();
//Task has an End Date
if (taskEnded > 0) { return 4; }
//Task has started
if (taskstarted > 0) { return 2; }
//task is not started but is valid
if (items > 0) { return 1; }
//task is invalid for this order
return 0;
}
----
Called in Javascript
summaryByTech.DataSource = app.DataSource("SummaryByTech", summaryByTech.Model, urlFilter, salesPerformanceTech.objGroup, salesPerformanceTech.objAggregate);
dsSummaryByTech = summaryByTech.DataSource;
Within WEBSERVICES PROJECT
[Authorize(Roles = "Franchisee,HomeOffice")]
public class SummaryByTechController : ApiController
{
// 1. Group By Tech over a date range
// 2. Group By Tech by Week for single column
[HttpGet]
public List<Model_BigBoard.DTO.DTOSummaryByTech> FetchSummaryByTech(string bNumber, DateTime startDate, DateTime endDate)
{
BusinessLogic.BLSummaryByTech bl = new BusinessLogic.BLSummaryByTech();
string bNumberConvert = Dwyer.BIMS.BigBoard.Base.Util.Tools.BusinessSupport.HexToASCIICharString(bNumber);
return bl.LoadSummaryByTech(bNumberConvert, startDate, endDate);
}
}
}
https://nordicapis.com/3-common-methods-api-authentication-explained/
CALLING THE API
From Javascript
<script>
$("#Create").click(function () {
var source = {
'OrderId': $("#OrderId").val(),
'TrackingNumber': $('#TrackingNumber').val(),
'TotalWeight': $('#TotalWeight').val(),
'ShippedDateUtc': $('#ShippedDateUtc').val(),
'AdminComment': $('#AdminComment').val(),
'CreatedOnUtc': new Date().toISOString(),
}
$.ajax({
type: "POST",
data: source,
url: "/api/Shipments",
})
.done(function (data, status, jqXHR) {
if (data.Success)
{
$("#OrderId").val("");
$('#TrackingNumber').val("");
$('#TotalWeight').val("");
$('#ShippedDateUtc').val("");
$('#AdminComment').val("");
}
else
{
alert(data.Message) //display exception
}
//alert("Success");
})
.fail(function (jqXHR, textStatus, err) {
//alert("Failed");
})
event.preventDefault();
});
</script>
<script type="text/javascript">
function getcustomer() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var email = $('#Email').val();
var Url="@Url.Content("~/api/customers/getcustomer")";
$.ajax({
url:Url,
dataType: 'json',
data: { email: countryID },
success: function (data) {
$.each(data, function (index, optiondata) {
$("#FirstName").val(optiondata.firstName);
});
}
});
}
</script>
<script>
$('#ppTable').on('click', '.btnSelect', function () {
// var tds = $(this).addClass('row-highlight').find('td');
var currentRow = $(this).closest("tr");
var OrderId = currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var OrderItemId = currentRow.find("td:eq(1)").text();
var tracking = currentRow.find(".tracking").val(); // get current row 2nd TD
var weight = currentRow.find(".totalweight").val(); // get current row 3rd TD
var shipdate = currentRow.find(".shipdate").val(); // get current row 4rd TD
// var data = OrderId + "-" + tracking + "-" + weight + "-" + shipdate;
//alert(data);
var source = {
'OrderId':OrderId,
'TrackingNumber': tracking,
'TotalWeight': weight,
'ShippedDateUtc': shipdate,
'AdminComment': OrderItemId,
'CreatedOnUtc': new Date().toISOString(),
}
$.ajax({
type: "POST",
data: source,
url: "/api/PPShipments",
})
.done(function (data, status, jqXHR) {
if (data.Success)
{
// $("#OrderId").val("");
// $('#TrackingNumber').val("");
// $('#TotalWeight').val("");
//$('#ShippedDateUtc').val("");
// $('#AdminComment').val("");
currentRow.remove();
}
else
{
alert(data.Message) //display exception
}
//alert("Success");
})
.fail(function (jqXHR, textStatus, err) {
//alert("Failed");
})
event.preventDefault();
});
Comments