I created a DynamoDb using NET and able to getitem, which is not an empty list. I get a status 400 error on the putitem using Postman. This is the error:
"errors": {
"id": [
"Could not convert string to integer: 9134d3a0-a6bf-4409-87b3-d9fad02bd31c. Path 'id', line 2, position 44."
]
},
This is the body I use for the post:
{
"id":"9134d3a0-a6bf-4409-87b3-d9fad02bd31c",
"replyDateTime": "63669789320007900",
"body":"a good body",
"title":"best title",
"creator": " James"
}
This is my createtable code:
var request = new CreateTableRequest
{
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = "S"
},
new AttributeDefinition
{
AttributeName = "ReplyDateTime",
AttributeType = "S"
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = "HASH" // Partition Key
},
new KeySchemaElement
{
AttributeName = "ReplyDateTime",
KeyType = "Range" // Sort Key
}
},
this is the putitem code:
public async Task AddNewEntry(string id, string replyDateTime, string body, string title, string creator)
{
var queryRequest = RequestBuilder(id, replyDateTime, body, title, creator);
await PutItemAsync(queryRequest);
}
private PutItemRequest RequestBuilder(string id, string replyDateTime, string body, string title, string creator)
{
var item = new Dictionary<string, AttributeValue>
{
{"Id", new AttributeValue {S = id}},
{"ReplyDateTime", new AttributeValue {S = replyDateTime}},
{"Body", new AttributeValue {S = body}},
{"Creator", new AttributeValue {S = creator}},
{"Title", new AttributeValue {S = title}}
};
return new PutItemRequest
{
TableName = "BlogDynamoDbTable",
Item = item
};
}
private async Task PutItemAsync(PutItemRequest request)
{
await _dynamoClient.PutItemAsync(request);
}
}
I believe I made the primary key a string. Why is an integer even mentioned in the error message?
I found my error. The model file was defining id as an integer. Grrr
I changed it to string and it posts.
public class Item
{
[Amazon.DynamoDBv2.DataModel.DynamoDBHashKey]
public string Id { get; set; }
[Amazon.DynamoDBv2.DataModel.DynamoDBRangeKey]
public string ReplyDateTime { get; set; }
public string Body { get; set; }
public string Title { get; set; }
public string Creator { get; set; }
}
Related
I think this is because my json gives me an array, but I don't know how it solved, this is what I did. (I'm new at this)
running in Visual Studio 2019 (xamarin.form) with web services but the url is hidden for security, so don't pay attention in that.
---my-json---
{
"cuentas":[
{
"cuenta":"0500",
"usuario":41
},
{
"cuenta":"0508",
"usuario":6
},
{
"cuenta":"0522",
"usuario":41
},
{
"cuenta":"0532",
"usuario":41
},
null
]
}
---WSClient.cs---
class WSClient
{
public async Task<T> Post<T>(string url, StringContent c)
{
var client = new HttpClient();
var response = await client.PostAsync(url, c);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
}
----Cuenta.cs---
public class Cuenta
{
public string cuenta { get; set; }
public int usuario { get; set; }
}
------MainPage.xaml.cs-----
private async void BtnCall_Clicked(object sender, EventArgs e)
{
WSClient client = new WSClient();
string dato = "";
StringContent content = new StringContent(dato, Encoding.UTF8, "application/json");
var result = await client.Post<Cuenta>("http://www.***", content);
if (result != null) {
lblCuenta.Text = result.cuenta;
lblUsuario.Text = result.cuenta;
}
}
It doesn't show me anything and it doesn't give me any mistakes... any advice?
( I can see the json in the console if I use WriteLine in "WSClient" )
your class should look like this (using json2csharp.com)
public class Cuenta
{
public string cuenta { get; set; }
public int usuario { get; set; }
}
public class RootObject
{
public List<Cuenta> cuentas { get; set; }
}
var result = await client.Post<RootObject>("http://www.***", content);
I am writing a Provider Hosted APP using SP 2013 and I have a data layer which uses REST to CRUD on sharepoint lists. Now I got the List items in JSON format but I am not able to iterate through the list data can you please help in doing that? (is there any class for List Items which I can deserialize into?)
This is the code
public JToken GetListData(string webUrl, string userName, SecureString password, string listTitle)
{
using (var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Credentials = new SharePointOnlineCredentials(userName, password);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
var endpointUri = new Uri(new Uri(webUrl), string.Format("/sites/DTF/_api/web/lists/getbytitle('{0}')/Items", listTitle));
var result = client.DownloadString(endpointUri);
var t = JToken.Parse(result);
return t["d"];
}
}
You need to use the DataContractJsonSerializer class to deserialize the data as is demonstrated here:
http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
To make this work though you have to create classes that match the structure of the Json. The easiest way to do this copying a raw Json response into a tool which will generate the classes like this one:
http://json2csharp.com/
The actual classes you will need to generate varies based on the structure of the data you are getting in your REST response. Here is an example I created that demonstrates making a request, parsing the Json Response and downloading a file based on the result:
public class JsonHelper
{
/// JSON Serialization
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// JSON Deserialization
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
//Custom Json Classes
public class RootObject
{
public D d { get; set; }
}
public class D
{
public GetContextWebInformation GetContextWebInformation { get; set; }
public List<Result> results { get; set; }
}
public class GetContextWebInformation
{
public int FormDigestTimeoutSeconds { get; set; }
public string FormDigestValue { get; set; }
public string LibraryVersion { get; set; }
public string SiteFullUrl { get; set; }
public string WebFullUrl { get; set; }
}
public class Result
{
public ContentType ContentType { get; set; }
public string EncodedAbsUrl { get; set; }
public string FileLeafRef { get; set; }
public Folder Folder { get; set; }
public int FileSystemObjectType { get; set; }
public int Id { get; set; }
public string ContentTypeId { get; set; }
public string Title { get; set; }
public int? ImageWidth { get; set; }
public int? ImageHeight { get; set; }
public string ImageCreateDate { get; set; }
public object Description { get; set; }
public object Keywords { get; set; }
public string OData__dlc_DocId { get; set; }
public int ID { get; set; }
public string Created { get; set; }
public int AuthorId { get; set; }
public string Modified { get; set; }
public int EditorId { get; set; }
public object OData__CopySource { get; set; }
public int? CheckoutUserId { get; set; }
public string OData__UIVersionString { get; set; }
public string GUID { get; set; }
}
//SharePoint Calls
class Program
{
static void Main()
{
string url = "https://sharepoint.wilsonconst.com/";
string filename = "2010-07-23 13.32.22.jpg";
string digest = "";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
HttpResponseMessage response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(content);
digest = sp.d.GetContextWebInformation.FormDigestValue;
}
client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "GET");
string uri = "_api/web/lists/GetByTitle('Wilson Pictures')/Items?$select=ID,FileLeafRef,EncodedAbsUrl&$filter=FileLeafRef eq '" + filename + "'";
HttpResponseMessage response2 = client.GetAsync(uri).Result;
response2.EnsureSuccessStatusCode();
if (response2.IsSuccessStatusCode)
{
string listItems = response2.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(listItems);
foreach (Result result in sp.d.results)
{
MemoryStream stream = (MemoryStream)client.GetAsync(result.EncodedAbsUrl).Result.Content.ReadAsStreamAsync().Result;
using(FileStream fileStream = System.IO.File.Create(#"C:\" + result.FileLeafRef))
{
stream.WriteTo(fileStream);
}
}
}
else
{
var content = response.Content.ReadAsStringAsync();
}
}
This seems like a lot of complexity, but really it makes working with Json objects quite easy and takes only moments to setup before you can start calling your custom objects to easily manipulate the data.
Assuming that you want to retrieve data from SharePoint Online the following example demonstrates how to consume SharePoint REST Interface via WebClient Class:
using (var client = new SPRestClient(webUri.ToString()))
{
client.Credentials = GetCredentials(webUri,userName,password);
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
var data = client.GetJson("/_api/lists/getbytitle('Tasks')/items"); //get list items
//print list item's title
foreach (var item in data["d"]["results"])
{
Console.WriteLine(item["Title"]);
}
}
where
public static SharePointOnlineCredentials GetCredentials(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var ch in password) securePassword.AppendChar(ch);
return new SharePointOnlineCredentials(userName, securePassword);
}
and
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SharePoint.Client
{
public class SPRestClient : WebClient
{
public SPRestClient(string webUri)
{
BaseAddress = webUri;
FormatType = JsonFormatType.Verbose;
}
public JObject GetJson(string requestUri)
{
return ExecuteJson(requestUri, HttpMethod.Get, null, default(string));
}
public JObject ExecuteJson<T>(string requestUri, HttpMethod method, IDictionary<string, string> headers, T data)
{
string result;
var uri = BaseAddress + requestUri;
if (headers != null)
{
foreach (var key in headers.Keys)
{
Headers.Add(key, headers[key]);
}
}
EnsureRequest(method);
switch (method.Method)
{
case "GET":
result = DownloadString(uri);
break;
case "POST":
if (data != null)
{
var payload = JsonConvert.SerializeObject(data);
result = UploadString(uri, method.Method, payload);
}
else
{
result = UploadString(uri, method.Method);
}
break;
default:
throw new NotSupportedException(string.Format("Method {0} is not supported", method.Method));
}
return JObject.Parse(result);
}
private void EnsureRequest(HttpMethod method)
{
var mapping = new Dictionary<JsonFormatType, string>();
mapping[JsonFormatType.Verbose] = "application/json;odata=verbose";
mapping[JsonFormatType.MinimalMetadata] = "application/json; odata=minimalmetadata";
mapping[JsonFormatType.NoMetadata] = "application/json; odata=nometadata";
Headers.Add(HttpRequestHeader.ContentType, mapping[FormatType]);
Headers.Add(HttpRequestHeader.Accept, mapping[FormatType]);
if (method == HttpMethod.Post)
{
Headers.Add("X-RequestDigest", RequestFormDigest());
}
}
private string RequestFormDigest()
{
var endpointUrl = string.Format("{0}/_api/contextinfo", BaseAddress);
var result = UploadString(endpointUrl, "Post");
var contentJson = JObject.Parse(result);
return contentJson["FormDigestValue"].ToString();
}
public JsonFormatType FormatType { get; set; }
}
public enum JsonFormatType
{
Verbose,
MinimalMetadata,
NoMetadata
}
}
SPRestClient.cs
Sorry for this lengthy query, I decided to add the whole test so that it will be easier for even newbies to help me with this total brain-melt.
The using directives are:
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
Please leave feedback if I'm too lengthy, but what could possibly go wrong if I add a complete test?
[TestFixture]
public class ClicksByScoreAndCardTest
{
private IDocumentStore _documentStore;
[SetUp]
public void SetUp()
{
_documentStore = new EmbeddableDocumentStore {RunInMemory = true}.Initialize();
_documentStore.DatabaseCommands.DisableAllCaching();
IndexCreation.CreateIndexes(typeof (ClicksBySearchAndProductCode).Assembly, _documentStore);
}
[TearDown]
public void TearDown()
{
_documentStore.Dispose();
}
[Test]
public void ShouldCountTotalLeadsMatchingPreference()
{
var userFirst = new User {Id = "users/134"};
var userSecond = new User {Id = "users/135"};
var searchFirst = new Search(userFirst)
{
Id = "searches/24",
VisitId = "visits/63"
};
searchFirst.Result = new Result();
searchFirst.Result.Rows = new List<Row>(
new[]
{
new Row {ProductCode = "CreditCards/123", Score = 6},
new Row {ProductCode = "CreditCards/124", Score = 4}
});
var searchSecond = new Search(userSecond)
{
Id = "searches/25",
VisitId = "visits/64"
};
searchSecond.Result = new Result();
searchSecond.Result.Rows = new List<Row>(
new[]
{
new Row {ProductCode = "CreditCards/122", Score = 9},
new Row {ProductCode = "CreditCards/124", Score = 4}
});
var searches = new List<Search>
{
searchFirst,
searchSecond
};
var click = new Click
{
VisitId = "visits/64",
ProductCode = "CreditCards/122",
SearchId = "searches/25"
};
using (var session = _documentStore.OpenSession())
{
foreach (var search in searches)
{
session.Store(search);
}
session.Store(click);
session.SaveChanges();
}
IList<ClicksBySearchAndProductCode.MapReduceResult> clicksBySearchAndProductCode = null;
using (var session = _documentStore.OpenSession())
{
clicksBySearchAndProductCode = session.Query<ClicksBySearchAndProductCode.MapReduceResult>(ClicksBySearchAndProductCode.INDEX_NAME)
.Customize(x => x.WaitForNonStaleResults()).ToArray();
}
Assert.That(clicksBySearchAndProductCode.Count, Is.EqualTo(4));
var mapReduce = clicksBySearchAndProductCode
.First(x => x.SearchId.Equals("searches/25")
&& x.ProductCode.Equals("CreditCards/122"));
Assert.That(mapReduce.Clicks,
Is.EqualTo(1));
}
}
public class ClicksBySearchAndProductCode :
AbstractMultiMapIndexCreationTask
<ClicksBySearchAndProductCode.MapReduceResult>
{
public const string INDEX_NAME = "ClicksBySearchAndProductCode";
public override string IndexName
{
get { return INDEX_NAME; }
}
public class MapReduceResult
{
public string SearchId { get; set; }
public string ProductCode { get; set; }
public string Score { get; set; }
public int Clicks { get; set; }
}
public ClicksBySearchAndProductCode()
{
AddMap<Search>(
searches =>
from search in searches
from row in search.Result.Rows
select new
{
SearchId = search.Id,
ProductCode = row.ProductCode,
Score = row.Score.ToString(),
Clicks = 0
});
AddMap<Click>(
clicks =>
from click in clicks
select new
{
SearchId = click.SearchId,
ProductCode = click.ProductCode,
Score = (string)null,
Clicks = 1
});
Reduce =
results =>
from result in results
group result by
new { SearchId = result.SearchId, ProductCode = result.ProductCode }
into g
select
new
{
SearchId = g.Key.SearchId,
ProductCode = g.Key.ProductCode,
Score = g.First(x => x.Score != null).Score,
Clicks = g.Sum(x => x.Clicks)
};
}
}
public class User
{
public string Id { get; set; }
}
public class Search
{
public string Id { get; set; }
public string VisitId { get; set; }
public User User { get; set; }
private Result _result = new Result();
public Result Result
{
get { return _result; }
set { _result = value; }
}
public Search(User user)
{
User = user;
}
}
public class Result
{
private IList<Row> _rows = new List<Row>();
public IList<Row> Rows
{
get { return _rows; }
set { _rows = value; }
}
}
public class Row
{
public string ProductCode { get; set; }
public int Score { get; set; }
}
public class Click
{
public string VisitId { get; set; }
public string SearchId { get; set; }
public string ProductCode { get; set; }
}
My problem here is that I expect Count to be one in that specific test, but it just doesn't seem to add the Clicks in the Click map and the result is 0 clicks. I'm totally confused, and I'm sure that there is a really simple solution to my problem, but I just can't find it..
..hope there is a week-end warrior out there who can take me under his wings.
Yes, it was a brain-melt, for me non-trivial, but still. The proper reduce should look like this:
Reduce =
results =>
from result in results
group result by
new { SearchId = result.SearchId, ProductCode = result.ProductCode }
into g
select
new
{
SearchId = g.Key.SearchId,
ProductCode = g.Key.ProductCode,
Score = g.Select(x=>x.Score).FirstOrDefault(),
Clicks = g.Sum(x => x.Clicks)
};
Not all Maps had the Score set to a non-null-value, and therefore my original version had a problem with:
Score = g.First(x => x.Score != null).Score
Mental note, use:
Score = g.Select(x=>x.Score).FirstOrDefault()
Don't use:
Score = g.First(x => x.Score != null).Score
How to receive posted values to variable in .asmx that was posted from extjs, so it can be saved using ado.net to database?
SENDING DATA WITH EXT.AJAX
{
text: 'Add',
formBind: true,
disabled: true,
handler: function () {
var form = this.up('form').getForm();
var formValues = form.getValues();
var firstName = formValues.firstName;
var lastName = formValues.lastName;
if (form.isValid()) {
Ext.Ajax.request({
url: 'WebServices/WebService.asmx/AddAgent',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
jsonData: { FirstName: firstName, LastName: lastName }
});
}
}
}
When submited, firebug reports error:
How to properly recieve this values in .asmx so they can be used in [WebMethod] and saved with Ado.Net?
[Serializable]
public class Agents
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
//CREATE
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string AddAgent()
{
string connStr = ConfigurationManager.ConnectionStrings["AgentsServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into Agent(id, firstName, lastName) values(#id, #firstName, #lastName)", connection))
{
command.Parameters.AddWithValue("#firstName", FirstName); //here i get message( The name "FirstNAme does not exist in current context")
command.Parameters.AddWithValue("#lastName", LastName); // -||-
command.ExecuteNonQuery();
}
}
}
EDIT:
No. stil 500 Internal Server Error:
Your web method doesn't seem to take any argument. Also your method expects to return a string and yet you do not return anything. So either return something or modify your method signature to void. Also you have set UseHttpGet = true and yet you are sending a POST request. Try like this:
[WebMethod]
[ScriptMethod]
public void AddAgent(Agents agents)
{
string connStr = ConfigurationManager.ConnectionStrings["AgentsServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into Agent(id, firstName, lastName) values(#id, #firstName, #lastName)", connection))
{
command.Parameters.AddWithValue("#firstName", agents.FirstName);
command.Parameters.AddWithValue("#lastName", agents.LastName);
command.ExecuteNonQuery();
}
}
}
Also since you have defined the Id property of your Agents model as a non-nullable integer I would recommend you sending a value for it:
jsonData: { agents: { Id: 0, FirstName: firstName, LastName: lastName } }
Is there a special way of creating a google chart via an Ajax call, which is different from the static method?
The HTML i am producing is correct because it will load from a normal HTML file, but when im calling the Ajax, the data in the graph is not showing.
I am using google.setOnLoadCallback() and google.load('visualization', '1', {packages: ['table']})
You need to get data from ajax call and then put it in to your visualization function.
Here is my code:
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(OnLoad);
var url = '/Charting/GetData';
function OnLoad() {
$.ajax({
url: url,
dataType: 'json',
success: function (response) {
drawVisualization(response);
}
});
};
function drawVisualization(response) {
var chart = new google.visualization.ColumnChart(
document.getElementById('visualization'));
var data = new google.visualization.DataTable(response);
chart.draw(data);
};
Also i recommend you to use this class to generate correct JSON response:
public class ChartHelper
{
public ColInfo[] cols { get; set; }
public DataPointSet[] rows { get; set; }
}
public class ColInfo
{
public string id { get; set; }
public string label { get; set; }
public string type { get; set; }
}
public class DataPointSet
{
public DataPoint[] c { get; set; }
}
public class DataPoint
{
public object v { get; set; } // value
public string f { get; set; } // format
}
Then you can use it like this:
[ActionName("data")]
public JsonResult Data()
{
Random r = new Random();
var graph = new ChartHelper
{
cols = new ColInfo[] {
new ColInfo { id = "A", label = "Name", type = "string" },
new ColInfo { id = "B", label = "Value", type = "number" },
},
rows = new DataPointSet[] {
new DataPointSet {
c = new DataPoint[]
{
new DataPoint { v = "Name" },
new DataPoint { v = r.NextDouble()},
}},
new DataPointSet {
c = new DataPoint[]
{
new DataPoint { v = "Name2" },
new DataPoint { v = r.NextDouble()},
}},
new DataPointSet {
c = new DataPoint[]
{
new DataPoint { v = "Name3" },
new DataPoint { v = r.NextDouble()},
}}
}
};
return Json(graph, JsonRequestBehavior.AllowGet);
}