Breeze WebAPI SaveChanges() - Invalid object name 'dbo.tblAgencyQuery - c#

I am using Breeze WebAPI to save a new row to my database but when I try to call the method SaveChanges() I get the error Invalid object name 'dbo.tblAgencyQuery.
See below for my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Breeze.WebApi;
using AgencyUpdate.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AgencyUpdate.Controllers
{
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<AgencyDbContext> _ContextProvider =
new EFContextProvider<AgencyDbContext>();
[HttpGet]
public string MetaData()
{
return _ContextProvider.Metadata();
}
[HttpGet]
public IQueryable<api_Agency> GetAgency()
{
return _ContextProvider.Context.api_Agency;
}
[HttpPost]
public void SaveData(JObject data)
{
Newtonsoft.Json.Linq.JToken[] agency = data.GetValue("agency").ToArray();
dynamic DeserializedData = JsonConvert.DeserializeObject(agency[0].ToString());
//using (var context = new AgencyDbContext())
//{
// tblAgencyQuery AgencyQuery = new tblAgencyQuery(); {
// AgencyQuery.QueryID = Guid.NewGuid();
// AgencyQuery.QueryText = agency[0].ToString();
// AgencyQuery.AgencyID = DeserializedData.agencyID;
// };
// context.tblAgencyQuery.Add(AgencyQuery);
// context.SaveChanges();
//}
tblAgencyQuery tblAgencyQuery = new tblAgencyQuery();
tblAgencyQuery.QueryID = Guid.NewGuid();
tblAgencyQuery.QueryText = agency[0].ToString();
tblAgencyQuery.AgencyID = DeserializedData.agencyID;
_ContextProvider.Context.tblAgencyQuery.Add(tblAgencyQuery);
_ContextProvider.Context.Entry(tblAgencyQuery).State = System.Data.EntityState.Added;
_ContextProvider.Context.SaveChanges();
}
[HttpGet]
public IQueryable<api_AgencyOffice> GetOffice()
{
return _ContextProvider.Context.api_AgencyOffice;
}
[HttpGet]
public IQueryable<api_AgencyContact> GetContact()
{
return _ContextProvider.Context.api_AgencyContact;
}
}
}
I am calling public void SaveData(JObject data) from my javascript. I deserialize the data and assign the values to a new instance of tblAgencyQuery. Then I add it to the context so I have the data ready to be saved.
But SavedChanges() doesn't like my object. Is it expecting a different object?
This is the exception window
My JavaScript Method
var saveChanges = function (agencyObservable) {
if (agencyObservable) {
var data = ko.toJSON(agencyObservable);
var options = {
url: '/breeze/SaveData',
type: 'POST',
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8"
}
return $.ajax(options)
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
log('Saved data successfully', saveResult, true);
};
function saveFailed(error) {
var msg = 'Save failed: ' + error.message;
logger.log(msg, error, system.getModuleId(datacontext), true);
error.message = msg;
}
}
};

You should be calling Breeze's EntityManager.saveChanges method. This will connect to a server side SaveChanges method that in turn makes use of Breeze's ContextProvider.SaveChanges method. In your code snippet, you are basically bypassing Breeze's entire save mechanism. The Breeze zip available on the Breeze web site contains a number of samples that show how this should be done.
On the client:
myEntityManager.saveChanges().then(saveSucceeded).fail(saveFailed);
On the server
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
return ContextProvider.SaveChanges(saveBundle);
}

Related

Unable to call smulate an Function from post Man to update a database

I have an Azure function that get an HTTP request , this azure function call a Stored Procedure who update the database,
The Stored Procedure works well and update the table in DB.
But when i ant to simulate this request with postMan i had error(500 :Internal Serveur Erro).
Here is my Function Azure:
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using Core.Handlers;
using System.Text.Json;
using Newtonsoft.Json.Linq;
namespace RealTimeTriggerFunctions
{
public static class SendToAzureSql
{
private static readonly string AZURE_TABLE1=
Environment.GetEnvironmentVariable("AZURE_TABLE1");
// Handler
private static AzureSqlHandler azSqlHandler;
[FunctionName("SendToAzureSql")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string procedureName = "";
try
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
if(string.IsNullOrEmpty(requestBody))
{
return new BadRequestResult();
}
dynamic message = JsonConvert.DeserializeObject(requestBody);
if (message == null)
{
return new BadRequestResult();
}
log.LogInformation((string)message.type.ToString()+ " progress...");
switch (message.type.ToString())
{
case "xx.yy.zz.event.table1.table1":
procedureName = "stored_table1";
InitHandlers(log, AZURE_TABLE1);
break;
default:
return new BadRequestObjectResult("Wrong Request!");
}
var dataJson = JsonDocument.Parse(requestBody);
string actionType = message.type.ToString().Contains("deleted") ? "Deleted": "Default";
await azSqlHandler.UpsertItemAsync(procedureName, actionType, payload:
dataJson.RootElement);
return new OkObjectResult(message.type.ToString() + " Processed");
}
catch (Exception e)
{
log.LogError($"An error occurred while processing request : '{e.Message}'");
throw e;
}
}
/// <summary>
/// Init connexions
/// </summary>
private static void InitHandlers(ILogger log, string connectionString)
{
// Create handler
azSqlHandler = new AzureSqlHandler(log, connectionString);
}
}
}
I call this request in POST : http://localhost:7071/API/SendToAzureSql I get 500.
I found my answer here:
Fetching access token for keyvault
i run az- login in my Azure cli and it Works

Determine URL prior to routing in controller for asp.net core

I am developing an asp.net core site, and I have a controller class which gets data for an api that I am using (jquery datatable).
ClientController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using GuptaAccounting.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
namespace GuptaAccounting.Controllers
{
//Need to add the route so server knows which path/url to go to
[Route("api/Client")]
//State that this is an api controller
[ApiController]
public class ClientController : Controller
{
private readonly ApplicationDbContext _db;
public ClientController(ApplicationDbContext db)
{
_db = db;
}
[HttpGet]
public IActionResult GetAll()
{
return Json(new
{
data = _db.Client.Where(Client => Client.IsConsultationClient == false).ToList()
});
}
}
}
I need to know where I am on the site, prior to routing to "api/client" so that i can return different data in the GetAll function (returning clients where IsConsultationClient == true). How would I do this? I have already tried to use IHttpContextAccessor and i didn't have any luck.
[EDIT]
I am making an ajax call from a js file. Here is part of my code
dataTable = $('#DT_load').DataTable({
//need to make an ajax call using the api that i included
"ajax": {
"url": "/api/client",
//this is a get request
"type": "GET",
"datatype": "json"
},
Maybe this will work.
In controller:
[HttpGet]
[MyRouter]
public IActionResult GetAll(bool isConsultationClient = false)
{
return Json(new
{
data = _db.Client
.Where(Client => Client.IsConsultationClient == isConsultationClient).ToList()});
}
}
In AttributeFilter:
public class MyRouterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request.Headers
.TryGetValue("IsConsultationClient", out var isConsultationClient))
{
if (isConsultationClient== "Yes")
context.ActionArguments.Add("isConsultationClient", true);
else if (isConsultationClient== "No")
context.ActionArguments.Add("isConsultationClient", false);
}
}
}

Error while reading data from database in c#

I have an error in this code. I deserialize a JSON file and stored that data in the database now I want to show that data from my database.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}
Error is:
JSON can not be used like method.
What should I do?
Your contoller must be extend the base class Controller in which the Json() virtual method is available:
public class StudentController : Controller
{
// your code
}
To resolve this error you can try as below
public class StudentController : Controller
{
// your code
}
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var list = await context.StudentDto.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
What you need to do is to extend your StudentCotroller with Controller then put your code under that.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController:Controller
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}

MVC 4 return JSON as ActionResult

i'm trying to get my apicontroller to work. But somehow i cannot return Json().
Here's the error message from the compiler:
Error CS0029 Cannot implicitly convert type
'System.Web.Http.Results.JsonResult<>'
to
'System.Web.Mvc.JsonResult' Opten.Polyglott.Web D:\Development\git\Opten.Polyglott\src\Opten.Polyglott.Web\Controllers\NewsletterApiController.cs
I cannot explain why it cannot convert the Json() to the ActionResult even the Json()inherits ActionResult.
Here's my controller:
using MailChimp;
using MailChimp.Helper;
using Opten.Polyglott.Web.Models;
using Opten.Umbraco.Common.Extensions;
using System.Configuration;
using System.Web.Mvc;
using Umbraco.Core.Logging;
using Umbraco.Web.WebApi;
namespace Opten.Polyglott.Web.Controllers
{
public class NewsletterApiController : UmbracoApiController
{
public ActionResult Subscribe(Newsletter newsletter)
{
bool isSuccessful = false;
if (ModelState.IsValid)
{
isSuccessful = SubscribeEmail(newsletter.Email);
}
return Json(new { isSuccess = isSuccessful });
}
}
}
Thanks for any help.
Your problem is within the usings as the UmbracoApiController most likely inherits from ApiController (from System.Web.Http) not Controller (from System.Web.Mvc) and thus they have different dependencies. To fix your problem first remove the
using System.Web.Mvc;
and put the
using System.Web.Http;
as for the return in this case that would be IHttpActionResult so you would have something as follows:
using MailChimp;
using MailChimp.Helper;
using Opten.Polyglott.Web.Models;
using Opten.Umbraco.Common.Extensions;
using System.Configuration;
using System.Web.Http;
using Umbraco.Core.Logging;
using Umbraco.Web.WebApi;
namespace Opten.Polyglott.Web.Controllers
{
public class NewsletterApiController : UmbracoApiController
{
public IHttpActionResult Subscribe(Newsletter newsletter)
{
bool isSuccessful = false;
if (ModelState.IsValid)
{
isSuccessful = SubscribeEmail(newsletter.Email);
}
return Json(new { isSuccess = isSuccessful });
}
}
}
Let me know if that works for you.
It seems your Json is using class in System.Web.Http, not in System.Web.Mvc. In this case, you can use this code:
return new JsonResult{ isSuccess = isSuccessful };
When using ActionResult using Response.StatusCode is a good practice:
public ActionResult SomeMethod()
{
try
{
// ...
// doing something here...
// ...
// success:
Response.StatusCode = (int)HttpStatusCode.OK;
return Json(new { responseText = "OK" });
}
catch
{
// error:
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { responseText = "ERROR" });
}
}
Add the following line in your WebApiConfig.cs file:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Json method is not recognized in Web Api controller

I have an web api controller
using sport.BLL.Abstract;
using sport.BLL.Concrete;
using sport.DAL.Entities;
using sport.webApi.Models;
using AutoMapper;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.WebPages.Html;
namespace sport.webApi.Controllers
{
public class AccountManageController : ApiController
{
[HttpPost]
public System.Web.Mvc.ActionResult CreateAccount(CollaborateurModel item)
{
var user = new ApplicationUser { UserName = item.Username, Email = item.Email };
var result = UserManager.CreateAsync(user, item.Password);
if (result.Result.Succeeded)
{
var currentUser = UserManager.FindByName(item.Username);
var roleresult = UserManager.AddToRole(currentUser.Id, item.Role);
ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);
entity.id_user_fk = currentUser.Id;
entity.is_deleted = false;
repo.CreateCollaborator(entity);
var response = new { Success = true };
return Json(response);
}
else
{
var errorResponse = new { Success = false, ErrorMessage = "error" };
return Json(errorResponse);
}
}
}
}
I got an error in this line :
return Json(response);
the Json Method is not recognized!!! when I googled about that I get this link which indicates that Json method is included in System.Web.Mvc. Even I try to import this namespace I get the same error?
So is the reason of this error?
How can I fix it?
The problem is that you are inheriting from ApiController but Json is a member of System.Web.Mvc.Controller.
Try using JsonResult:
return new JsonResult { data = yourData; }
You can set any object to a data as it will be serialized to a JSON.
For instance, if you need to return only a result of operation, you can use it this way:
return new JsonResult { data = true; } // or false
However, it is a good practice to describe a result class and return objects.
How can I fix it?
The reason is in the fact that you aren't inheriting from Controller but from ApiController, where the former has Json(object o) as a method in it's base class, but that doesn't actually matter, as there is a fundamental problem with your approach.
ApiController which is used with WebAPI isn't meant to return an ActionResult, which is a concept that belongs to MVC. Instead, you simply return your POCO and let the WebAPI framework handle serialization for you:
public object CreateAccount(CollaborateurModel item)
{
// Do stuff:
if (result.Result.Succeeded)
{
return new { Success = true }
}
else
{
return new { Success = false, ErrorMessage = "error" };
}
}
You can set your formatter configuration in your Global.asax.cs file, and tell it exactly which ones to use (in your case, you'll want the JsonMediaTypeFormatter).

Categories

Resources