Post multiple entities using AngularJS services - javascript

I want to post 2 entities using Angular JS .
here is my AccountController.js
$scope.InsertAccount = function (user,account) {
accountsService.InsertAccount(user,account);
};
My AccountService.js
var InsertAccount = function (user, account) {
return $http.post("http://localhost:26309/api/Compte/addUserV", {user :user, compte: account})
.then(function () {
$log.info("Insert Successful");
return;
});
};
I can post a single parameter ,but it doesnt work when i try to put many.

Do you mean many users, many accounts? Typically, since you're creating multiple entities, you'll want multiple POSTs. So a helper function could be what you're looking for:
$scope.InsertAccounts = function (users, accounts) {
return $q.all(users.map(function (user, n) {
return $scope.InsertAccount(user, accounts[n]);
}));
}

when we retrieve the JSonObject in webApi Controller , how can we deserialize it ? it seems that the problem is in this code `
public HttpResponseMessage addUserV(Newtonsoft.Json.Linq.JObject data)
{
Utilisateur user = data["user"].ToObject<Utilisateur>();
Compte compte = data["compte"].ToObject<Compte>();
try
{
if (!_compteService.CreerUtilisateur(user, compte))
{
throw new Exception("ajout de l'instance de l'utilisateur non effecuté " + compte.designation);
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
//response.StatusCode = HttpStatusCode.Created;
// String uri = Url.Link("GetUser", new { id = user.id });
// response.Headers.Location = new Uri(uri);
return response;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
return response;
}
}
`

try using JSON.stringify(), The JSON.stringify() method converts a JavaScript value to a JSON string. so it will consider your array/object as a single value.
var InsertAccount = function (user, account) {
//use JSON.stringify
var data = JSON.stringify({user :user, compte: account});
return $http.post("http://localhost:26309/api/Compte/addUserV", data)
.then(function (response) {
$log.info("Insert Successful");
return response;
});
};

should be work your method. however can try this one
var InsertAccount = function (user, account) {
var data = {user :user, compte: account}; // assign first and can try JSON.stringify({,,})
return $http.post("http://localhost:26309/api/Compte/addUserV", data)
.then(function (response) {
$log.info("Insert Successful");
return response;
});
};
in server side can try
public HttpResponseMessage addUserV(Newtonsoft.Json.Linq.JObject data)
{
var result = JsonConvert.DeserializeObject<dynamic>(data);
var user = result.user;
var compte = result.compte;
// rest of code
}

Related

mvc asp can't update using query from my view

I am trying to have save changes on my script and I just need an update from my table. So far if I clicked the button, the alert success will not pop and can't see any error either. I also tried to verify to my table if the changes is made but the result is nothing happened
Here is the call function from my save button:
<script>
var op = '';
var op_dif = '';
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
alert(op + " " + op_dif); // I can see the value here
$.post("/Home/UpdateOP", {
'data': JSON.stringify([{
'op': op,
'opDiff': Op_dif
}])
}, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
</script>
My view where my update query is located:
public string UpdateOpsDiff(operation[] ops)
{
string res = "";
foreach(var op in ops)
{
string updatetQuery = "update sys.OP_difficulty set op_difficulty = #diff where op = #op;";
MySqlCommand updateCommand = new MySqlCommand(updatetQuery);
updateCommand.Connection = myConnection;
updateCommand.Parameters.AddWithValue("#diff", op.op_dif);
updateCommand.Parameters.AddWithValue("#op", op.op);
myConnection.Open();
int updatedRowNum = 0;
try
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
catch(MySqlException)
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
res = "{status:SUCCESS, updatedRowNum:" + updatedRowNum + "}";
}
return res;
}
Controller where it reads the view query:
public string UpdateOp()
{
string data = Request.Form["data"];
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
return sys.UpdateOpsDiff(rows);
}
catch (JsonSerializationException je)
{
Console.WriteLine(je.Message);
return "{status:'DATA_FORMAT_ERROR'}";
}
}
Is there any missing items that I need. It already working using the query from my controller but this time I need to store my query from my view.
Any suggestions or comments. TIA
Since you're using AJAX callback, you should change return type to ActionResult and mark the action method with [HttpPost] attribute, also you should use return Content() or return Json() depending on returned type from UpdateOpsDiff() (string or object, respectively). Here is an example of proper setup:
[HttpPost]
public ActionResult UpdateOp(string data)
{
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
string result = sys.UpdateOpsDiff(rows);
// return JSON-formatted string should use 'Content()', see https://stackoverflow.com/q/9777731
return Content(result, "application/json");
}
catch (JsonSerializationException je)
{
// do something
return Json(new { status = "DATA_FORMAT_ERROR"});
}
}
Then set the AJAX callback to pass JSON string into action method mentioned above:
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
var values = { op: op, opDiff: op_dif };
$.post("/Home/UpdateOP", { data: JSON.stringify(values) }, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
Note:
The JSON-formatted string should be presented in key-value pairs to be returned as content, as shown in example below:
res = string.Format(#"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);

Cloud function returning nil value

I had a freelancer do some work in cloud code however I can no longer contact them due to an argument that occurred. I do not know javascript nor am I familiar with Parse cloud code and I was hoping someone could shed light on whether or not I am calling this function correctly considering it returns as if its parameter was equal to nil although I do believe I am giving it a value. Below is the javascript cloud code function as well as my swift code where I am calling it. For instance it is returning the value (-5).
Parse.Cloud.define("AddFriendRequest", function (request, response) {
var FriendRequest = Parse.Object.extend("FriendsIncoming");
var FRequest = new FriendRequest();
var user = request.user;
var query = new Parse.Query(Parse.User);
query.equalTo("username", request.params.username);
query.find({
success: function (people) {
if(people.length == 0)
{
response.success(-5);
return;
}
var person = people[0];
FRequest.set("OwnerID", user.id);
FRequest.set("TargetFriend", person.id);
FRequest.set("Status", 0);
var query = new Parse.Query("FriendsIncoming");
query.equalTo("OwnerID", user.id);
query.equalTo("TargetFriendID", person.id);
query.find({
success: function (results) {
if (results.length > 0) {
response.success(1);
return;
}
FRequest.save(null, {
success: function (Friend) {
response.success(2);
},
error: function (Friend, error) {
response.error(3);
}
});
response.error(-2);
},
error: function () {
response.error(-1);
}
});
}
,
error: function (Friend, error) {
response.error(-4);
}
});
});
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == NewRequest {
textField.resignFirstResponder()
print(NewRequest)
var name : NSString
name = NewRequest.text!
print(name)
//let parameters : [NSObject : AnyObject]
let params = ["TargetFriendID" : name]
PFCloud.callFunctionInBackground("AddFriendRequest", withParameters: params) { results, error in
if error != nil {
//Your error handling here
} else {
print(results)
}
}
return false
}
return true
}
The parameter from the client is named "TargetFriendID", but the cloud function runs the query on request.params.username.
Either rename the parameter in swift to username, or rename the parameter in the cloud to request.params.TargetFriendID.

using java script and JQuery to show message instead of throwing exception

How to show message(to inform user if group is added successfully or not) using Javascript and JQuery instead of throwing an erro. Actually this code check if group name already exist in database.
Controller :
[HttpPost]
public int CreateGroup(UserGroup group)
{
return bc.Create(group, user.id);
}
User group class:
UserGroupDalc Dalc = new UserGroupDalc();
public int Create(UserGroup group, int creatorId)
{
if(ByName(group.name) != null) throw new ArgumentException(string.Format("Group name: {0} is already exist.", group.name));
return Dalc.CreateGroup(group, creatorId);
}
User group dalc class:
public int CreateGroup(UserGroup group, int creatorId) {
connection();
com = new SqlCommand("spp_adm_user_group_ins", conn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#name", group.name);
com.Parameters.AddWithValue("#userid", group.creator_id);
conn.Open();
int i = com.ExecuteNonQuery();
if (i >= 1)
{
return 1;
}
else
{
return 0;
}
This js for posting data:
save: function () {
var jForm = $("#form1");
Metronic.blockUI();
GroupAPI.create(jForm.serialize(),
function (data) {
console.log(data);
},
function (error) {
console.log(error);
},
function () { Metronic.unblockUI(); });
}
}
}();
var GroupAPI = function () {
var url_create = "api/usergroup/createGroup";
var url_list = "api/usergroup/list";
return {
create: function (item, done, fail, always) {
var jqxhr = $.post(url_create, item);
jqXhrHandler(jqxhr, done, fail, always);
}
}
}();
Change user group class
UserGroupDalc Dalc = new UserGroupDalc();
public int Create(UserGroup group, int creatorId)
{
if(ByName(group.name) != null){
return 1;
}
return Dalc.CreateGroup(group, creatorId);
}
js
save: function () {
var jForm = $("#form1");
Metronic.blockUI();
GroupAPI.create(jForm.serialize(),
function (data) {
//console.log(data);
if (data == 0)
{
alert('added');
}else if(data == 1){
alert('already exist');
}
},
function (error) {
console.log(error);
},
function () { Metronic.unblockUI(); });
}
}
}();
it will be better to response a 422 status code, in this case indicate validation failed and server is not able to process the request, you can as well put the user readable message in the response response body
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

MVC- After ajax request Page cannot be refresh

on my view page , i am passing some values to controller by ajax request , on controller action, after checking , redirecting message value to view's controller.Adding message to model and pasisng model to view again with new model value.On second time( postback) model values passed to view as Json but new model value(which is message) cannot be catch by javascript.In my code it is Model.INFO
$.ajax({
type: "POST",
url: '#Url.Action("TeamSaveChanges", "Administrator")',
data: {
ID: '#Model.ID',
doctorID: doctorValue,
nurseID:nurseValue,
driverID:driverValue,
technicianID: technicianValue
},
dataType: "text",
success: function () { alert("#Model.INFO")},
error: function () { alert("Error occured!!!") }
});
Controller
public ActionResult TeamSaveChanges(Guid ID, Guid? doctorID, Guid? nurseID, Guid? driverID, Guid? technicianID)
{
try
{
using (var client = SoapProxyFactory.CreateDSrvGDSoapClient())
{
var emptyTeam = Guid.Empty;
var ambID = client.getAmbulanceIDbyTeamID(ID);
var baseresult = client.checkAmblanceTeamsforDuplicateMembers(ambID, ID);
if (doctorID == emptyTeam && nurseID == emptyTeam && driverID == emptyTeam && technicianID == emptyTeam )
{
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
else
{
foreach (var item in baseresult)
{
if(item.DOCTORCODE == doctorID && item.NURSECODE == nurseID && item.DRIVERCODE == driverID && item.TECHNICIANCODE == technicianID)
throw new Exception("The team with Same Members is exist." + "<p>(" + item.TEAMCODE + ")</p>");
}
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
catch (Exception exp)
{
string message = exp.Message;
return RedirectToAction("TeamMembers", "Administrator", new { ID = ID, message = message });
}
[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult TeamMembers(Guid? ID,string message)
{
try
{
if (!ID.HasValue())
return RedirectToAction("Ambulance");
using (var client = SoapProxyFactory.CreateDSrvALLSoapClient())
{
Guid id = ID.Value;
var clientGD = SoapProxyFactory.CreateDSrvGDSoapClient();
var result = client.GetTeamMembers(id);
result.INFO = message;
if (message != null)
{
result.INFO = message;
return Json(result,JsonRequestBehavior.AllowGet);
}
return View(result);
}
}
This line:
success: function () { alert("#Model.INFO")},
Will only pull in the INFO of the model once because it renders the server value in the client. If you are expecting it to change, then you have to pass the result back to success, and accept the new value as such:
success: function (d) { alert(d); },
To return a value to it you have to return from the action:
return Content("SOMEVAL"); // or PartialView or something that is string data
However, redirecting to action isn't going to return a response to the caller, and may not be handled properly through AJAX, so I'm not 100% sure what the question is...
Why would you use AJAX for this? What is happening is your script is firing a request off to your controller, which sends the response back as data, not a redirect to a new webpage.
Just create a form that POSTs those variables to your controller in typical MVC fashion, you'll get the result you want.

Windows Azure Mobile Service: dont insert more than once the same data

I have an application in windows phone and make registration with facebook and I store some data in a table, however, a single user it is being stored more than once in the table. I tried (getting the fb-id) check on the table if a record with that fb-id, but before re registrare l new user should check whether there is, however, such as asynchronous methods there is no order and always first executes the query insertion, as I can resolve this?
client side (limited)
await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);
Message = string.Format("User Authenticate - {0}", App.MobileService.CurrentUser.UserId);
//***** Get fb info
var userId = App.MobileService.CurrentUser.UserId;
var facebookId = userId.Substring(userId.IndexOf(':') + 1);
var client = new HttpClient();
var fbUser = await client.GetAsync("https://graph.facebook.com/" + facebookId);
var response = await fbUser.Content.ReadAsStringAsync();
var jo = JObject.Parse(response);
var FbidUser = jo.GetValue("id");
var userName = jo.GetValue("name");
var genero = jo.GetValue("gender");
but, i slould be do at server client, but how to insert info data one time, i mean, Check the record in the table before inserting.
Server side Azure:
function insert(item, user, request)
{
item.UserName = "<unknown>"; // default
var identities = user.getIdentities();
var req = require('request');
if (identities.facebook)
{
var fbAccessToken = identities.facebook.accessToken;
var url = 'https://graph.facebook.com/me?access_token=' + fbAccessToken;
req(url, function (err, resp, body)
{
if (err || resp.statusCode !== 200)
{
console.error('Error sending data to FB Graph API: ', err);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, body);
}
else
{
try
{
var userData = JSON.parse(body);
item.UserName = userData.name;
request.execute();
} catch (ex)
{
console.error('Error parsing response from FB Graph API: ', ex);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
});
}
}
according to the above code, i have a second question, in the developer center on facebook, I have access to email and photos (my application), I guess userData variable contains this information?, how do I access it?, how to call those properties where the rest of the information?
If all you want is to prevent two items for users with the same name to be inserted, the easiest way would be to not use the name at all, but instead use the FB id (after all, it's possible that two different people have the same name). That you can do with the script below:
function insert(item, user, request)
{
item.UserId = user.userId;
var currentTable = tables.current;
currentTable.where({ UserId: user.userId }).read({
success: function(results) {
if (results.length > 0) {
// an item with that user id already exists in the table
request.respond(400,
{ error: 'item already in the table' });
} else {
// new user, can insert it here
request.execute();
}
}
});
}
Now, if you really want to use the user name as the "key" for your table, you can do something similar as well:
function insert(item, user, request)
{
item.UserName = "<unknown>"; // default
var identities = user.getIdentities();
var req = require('request');
var currentTable = tables.current;
if (identities.facebook)
{
var fbAccessToken = identities.facebook.accessToken;
var url = 'https://graph.facebook.com/me?access_token=' + fbAccessToken;
req(url, function (err, resp, body)
{
if (err || resp.statusCode !== 200)
{
console.error('Error sending data to FB Graph API: ', err);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, body);
} else {
try {
var userData = JSON.parse(body);
item.UserName = userData.name;
currentTable.where({ UserName: item.UserName }).read({
success: function(results) {
if (results.length > 0) {
request.respond(statusCodes.BAD_REQUEST,
{ error: 'Name already in the table' });
} else {
request.execute();
}
}
});
} catch (ex) {
console.error('Error parsing response from FB Graph API: ', ex);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
});
}
}

Categories