I work on an application in online mode / disconnected and an example found on the book HTML5 Programming for ASPNET developers .
I use the ASPNET technologies MVC5 .
I have an error when I deserialize Data in my controller:
public JsonResult SaveResults()
{
string jsonData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
jsonData = sr.ReadToEnd();
}
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
SurveyDbEntities db = new SurveyDbEntities();
User usr = new User();
usr.FirstName = data["FirstName"];
usr.LastName = data["LastName"];
usr.Email = data["Email"];
db.Users.AddObject(usr);
db.SaveChanges();
string userEmail = data["Email"];
int usrId = (from item in db.Users
where item.Email == userEmail
select item.UserID).SingleOrDefault();
data.Remove("FirstName");
data.Remove("LastName");
data.Remove("Email");
foreach (string str in data.Keys)
{
int choiceId = int.Parse(str);
int questionId = int.Parse(data[str]);
Result result = new Result();
result.QuestionID = questionId;
result.ChoiceID = choiceId;
result.UserID = usrId;
db.Results.AddObject(result);
}
db.SaveChanges();
return Json("success");
}
This line shows the error
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
My jsonData ( Quote problem ? ) :
{"Email":"test#aol.fr","FirstName":"test","LastName":"test","container":"<div data-questions-questionid="1" class="paddedDiv">Which programming language do you use?<br><input type="checkbox" data-choices-questionid="1" data-choices-choiceid="1"><span>C#</span><br><input type="checkbox" data-choices-questionid="1" data-choices-choiceid="2"><span>VB.NET</span><br><input type="checkbox" data-choices-questionid="1" data-choices-choiceid="3"><span>PHP</span></div><div data-questions-questionid="2" class="paddedDiv">Which of the following browsers do you use while developing websites?<br><input type="checkbox" data-choices-questionid="2" data-choices-choiceid="4"><span>IE9</span><br><input type="checkbox" data-choices-questionid="2" data-choices-choiceid="5"><span>Firefox</span><br><input type="checkbox" data-choices-questionid="2" data-choices-choiceid="6"><span>Chrome</span></div><div data-questions-questionid="3" class="paddedDiv">Which of the following tools do you use?<br><input type="checkbox" data-choices-questionid="3" data-choices-choiceid="7"><span>Visual Studio</span><br><input type="checkbox" data-choices-questionid="3" data-choices-choiceid="8"><span>Web Matrix</span><br><input type="checkbox" data-choices-questionid="3" data-choices-choiceid="9"><span>Expression Web</span></div>"}
Then error :
{"After parsing a value an unexpected character was encountered: 1. Path 'container', line 1, position 105."}
Any idea where is the problem ?
Javascript SubmitData
function SubmitData(event) {
var data = '';
for (var i = 0; i < storage.length; i++) {
var key = storage.key(i);
var value = storage[key];
var pair = '"' + key + '":"' + value + '"';
data = data + pair + ",";
}
if (data.charAt(data.length - 1) == ',') {
data = data.substring(0, data.length - 1)
}
data = '{' + data + '}';
$.ajax({
type: "POST",
url: "/Home/SaveResults",
contentType: "application/json; charset=utf-8",
data: data,
dataType: "json",
success: function(results){
alert('Results saved!');
window.localStorage.clear();
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
})
}
Have a look at your JSON data:
"container":"<div data-questions-questionid="1
the value of property 'container' ends right before the '1'
So yes.. it's an encoding error even I don't know if there are other issues as well.
Related
I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached
but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach
but in my controller its passing null
my ajax code where I am passing the image file object,
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
//data.EmpID = $('.HiddenID').val();
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
but in controller on running the code it passes null
public void EmployeeImage(HttpPostedFileBase file)
{
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
byte[] bytes;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + ext; //appending the name with id
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img)
file.SaveAs(path);
}
}
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
var file = emp.CurrentPicURL;
EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
and in my model class my Image datatype is as
public HttpPostedFileBase CurrentPicURL { get; set; }
I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend
You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.
Sending files using a FormData object | MDN
const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
...
NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.
I am facing a new issue with a fetch
handleSendToForge(e) {
e.preventDefault();
let formData = new FormData();
formData.append('data', JSON.stringify({
Width: this.state.Width,
Length: this.state.Length,
Depth: this.state.Depth,
Thickness: this.state.Thickness,
BottomThickness: this.state.BottomThickness,
rebarSpacing: this.state.rebarSpacing,
outputrvt: this.state.outputrvt,
bucketId: this.state.bucketId,
activityId: 'RVTDrainageWebappActivity',
objectId: 'template.rvt'
}));
this.setState({
form: formData
})
fetch('designautomation', {
method: 'POST',
body: formData,
//headers: {
// //'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
//},
})
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log(error));
}
and the code for the controller is pretty standard and is slightly modified from one of the forge examples
[HttpPost]
[Route("designautomation")]
public async Task<IActionResult> Test([FromForm] StartWorkitemInput input)
{
JObject workItemData = JObject.Parse(input.data);
double Width = workItemData["Width"].Value<double>();
double Length = workItemData["Length"].Value<double>();
double Depth = workItemData["Depth"].Value<double>();
double Thickness = workItemData["Thickness"].Value<double>();
double BottomThickness = workItemData["BottomThickness"].Value<double>();
double rebarSpacing = workItemData["rebarSpacing"].Value<double>();
string outputrvt = workItemData["outputrvt"].Value<string>();
string activityId = workItemData["activityId"].Value<string>();
string bucketId = workItemData["bucketId"].Value<string>();
string objectId = workItemData["objectId"].Value<string>();
// basic input validation
string activityName = string.Format("{0}.{1}", NickName, activityId);
string bucketKey = bucketId;
string inputFileNameOSS = objectId;
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// prepare workitem arguments
// 1. input file
dynamic inputJson = new JObject();
inputJson.Width = Width;
inputJson.Length = Length;
inputJson.Depth = Depth;
inputJson.Thickness = Thickness;
inputJson.BottomThickness = BottomThickness;
inputJson.rebarSpacing = rebarSpacing;
inputJson.outputrvt = outputrvt;
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/aecom-bucket-demo-library/objects/{0}", objectId),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 2. input json
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
},
Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
};
// 3. output file
string outputFileNameOSS = outputrvt;
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
// the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
//string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&bucketKey={2}&outputFileName={3}", OAuthController.FORGE_WEBHOOK_URL, browerConnectionId, bucketKey, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "rvtFile", inputFileArgument },
{ "jsonFile", inputJsonArgument },
{ "result", outputFileArgument }
///{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
DesignAutomationClient client = new DesignAutomationClient();
client.Service.Client.BaseAddress = new Uri(#"http://localhost:3000");
WorkItemStatus workItemStatus = await client.CreateWorkItemAsync(workItemSpec);
return Ok();
}
Any idea why is giving me this error? I have tested the api using postman and it works fine but when I try to call that from a button I keep receive this error. Starting the debug it seems that the url is written correctly. Maybe it is a very simple thing that i am missing.
Cheers!
OK solved...
I was missing to add the service in the Startup and also the Forge connection information (clientid, clientsecret) in the appsettings.json
Now I need to test the AWS deployment and I guess I am done!
I am working on a Flutter app. we have a PSQL database, Node server on the background. On the Flutter app I am displaying some geometry which I fetch from the database successfully. Now after a modification on the geometry, such as lines, I want to be able to update the database via a put request.
Server goes like:
app.put('/api/shape/:id', async (req,res) =>{
let answer;
if( req.body.shape_type == "line"){
answer = await db.db.modify_line(req.params.id, req.body.info_shape);
}
res.send(answer);
});
And db.js file goes like:
modify_line : async function(id_shape, info_shape){
console.log(info_shape);
const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [id_shape, info_shape]);
return(result);
},
On the Flutter app I do this:
_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();
Map data;
if (globals.selectedType == globals.Type.line) {
String lseg = "(" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dy.toString() + ")";
data = {
'shape_type': 'line',
'info_shape': {
'id_shape': globals.selectedShapeID.toString(),
'line': lseg,
}
};
}
http.Response response;
try {
//encode Map to JSON
print("encode Map to JSON");
var body = json.encode(data);
print(body);
response =
await http.put(url,
headers: {
"Content-Type": "application/json"
},
body: body
).catchError((error) => print(error.toString()));
} catch (e) {
print(e);
}
return response;
}
Database "line" table contains a "shapeID" and "lseg" information on each row.
Currently I am getting an error when I try this code:
{ id_shape: '619',
line: '(19.5,100.6,20.5,50.9)' }
fail____error: invalid input syntax for type lseg: "{"id_shape":"619","line":"(-19.5,100.6,20.5,50.9)"}"
How shall I shape my lseg json?
Thanks
Well, it looks like to me you are passing the whole input_shape object to the SQL query, which looks like this, as per your console.log:
{
id_shape: '619',
line: '(19.5,100.6,20.5,50.9)'
}
Obviously, this is invalid for PostgreSQL.
I would say that your backend code should be more like this:
modify_line : async function(id_shape, info_shape){
console.log(info_shape);
const result = await send_query(
"UPDATE line SET line = $2 WHERE id_shape = $1",
// Reference "line" sub-object
[id_shape, info_shape.line],
);
return(result);
},
You should also pay attention to the Geometric types format for lines:
[ ( x1 , y1 ) , ( x2 , y2 ) ]
( ( x1 , y1 ) , ( x2 , y2 ) )
( x1 , y1 ) , ( x2 , y2 )
x1 , y1 , x2 , y2
I'm not 100% sure by reading this that your format (with leading and trailing parenthesis) is correct.
As the issue is solved, following is the answer:
DB.js is like:
modify_line : async function(id_shape, info_shape){
const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [info_shape['id_shape'], info_shape['line']]);
return(result);
},
and Flutter app is like:
_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();
Map data;
if (globals.selectedType == globals.Type.line) {
String lseg =
"[" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dy.toString() + "]";
data = {
'shape_type': 'line',
'info_shape': {
'id_shape': globals.selectedShapeID.toString(),
'line': lseg,
}
};
}
http.Response response;
try {
//encode Map to JSON
print("encode Map to JSON");
var body = json.encode(data);
print(body);
response =
await http.put(url,
headers: {
"Content-Type": "application/json"
},
body: body
).catchError((error) => print(error.toString()));
} catch (e) {
print(e);
}
return response;
}
I've been trying without success today to adapt this example to POST data instead of the example GET that is provided.
http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx
I've replaced the line:
request.Method = HttpMethod.Get;
With
request.Method = HttpMethod.Post;
But can find no Method that will allow me to stream in the content I wish to POST.
This HttpWebRequest seems a lot cleaner than other ways e.g. sending delegate functions to handle the response.
In Mr Wigley's example code I can see POST so it must be possible
public static class HttpMethod
{
public static string Head { get { return "HEAD"; } }
public static string Post { get { return "POST"; } }
I wrote this class some time ago
public class JsonSend<I, O>
{
bool _parseOutput;
bool _throwExceptionOnFailure;
public JsonSend()
: this(true,true)
{
}
public JsonSend(bool parseOutput, bool throwExceptionOnFailure)
{
_parseOutput = parseOutput;
_throwExceptionOnFailure = throwExceptionOnFailure;
}
public async Task<O> DoPostRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"post",
DateTime.Now.Ticks
));
string serialized = JsonConvert.SerializeObject(input);
StringContent stringContent = new StringContent(
serialized,
Encoding.UTF8,
"application/json");
var response = client.PostAsync(uri, stringContent);
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with POST ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
public async Task<O> DoPutRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"put",
DateTime.Now.Ticks
));
string serializedObject = JsonConvert.SerializeObject(input);
var response = client.PutAsync(uri,
new StringContent(
serializedObject,
Encoding.UTF8,
"application/json"));
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with PUT ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
}
Then when I want to call it, I can use it as following :
JsonSend<User, RegistrationReceived> register = new JsonSend<User, RegistrationReceived>();
RegistrationReceived responseUser = await register.DoPostRequest("http://myurl", user);
I am using/reusing json.net to get facebook likes of a user and his/her friend's like. I am having this error : Object reference not set to an instance of an object
In the following code, I have parsed facebook json three times and I have this exception raised the third time I have used it....in the methoduserlikes function to be precise...
I think the problem is in [var i].........it works fine the first two times but exeception occurs third time.....
kindly point out what seems to be the problem.....
oAuth.AccessTokenGet(Request["code"]);
global_token = oAuth.Token;
if (oAuth.Token.Length > 0)
{
url = "https://graph.facebook.com/me/likes?access_token=" + oAuth.Token;
url_friends = "https://graph.facebook.com/me/friends?access_token=" + oAuth.Token;
string json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
string jsonfriends = oAuth.WebRequest(oAuthFacebook.Method.GET, url_friends, String.Empty);
Label1.Text = oAuth.Token.ToString();
JObject likes = JObject.Parse(json);
string id = "";//user id
string name = "";//user likes
JObject friends = JObject.Parse(jsonfriends);
string fid = "";
foreach (var i in likes["data"].Children()) //Loop through the returned friends
{
id = i["id"].ToString().Replace("\"", "");
name = i["name"].ToString().Replace("\"", "");
Label3.Text = Label3.Text + "<br/> " + name;
}
foreach (var i in friends["data"].Children())
{
fid = i["id"].ToString().Replace("\"", "");
methoduserlikes(fid);
}
}
}
}
public void methoduserlikes(string id)
{
Label4.Text = Label4.Text + "<br/> " + id;
string flike = "";
string like_id = "";
string flike_url = "https://graph.facebook.com/" + id + "/likes?access_token=" + global_token;
string jsonfriend_like = oAuth.WebRequest(oAuthFacebook.Method.GET, flike_url, String.Empty);
JObject friend_like = JObject.Parse(jsonfriend_like);
foreach (var i in friend_like["data"].Children())
{
like_id = i["id"].ToString().Replace("\"", "");
**flike = i["name"].ToString().Replace("\"","");** here the exception is raised
Label5.Text = Label5.Text + "<br/> " + flike;
}
}
}