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);
}
Related
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; }
}
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);
Can you please suggest how to write unit test for web services in xamarin forms, I am getting error to on running
[TestFixture()]
public class LeadRepositoryTest
{
private Mock<ILeadWebService> mockLeadWebService { get; set; }
private Mock<ILeadDatabaseService> mockLeadDatabaseService { get; set; }
private LeadService leadRepository { get; set; }
public LeadRepositoryTest()
{
var repository = new MockRepository(MockBehavior.Default) { DefaultValue = DefaultValue.Empty };
mockLeadWebService = repository.Create<ILeadWebService>().As<ILeadWebService>();
mockLeadDatabaseService = repository.Create<ILeadDatabaseService>().As<ILeadDatabaseService>();
mockLeadWebService.Setup(x => x.GetNormalLeads(CommonMockData.GetLeadRequestParams())).Returns(Task.FromResult(OperationResult.CreateSuccessResult(new GetLeadsApiResponseDTO())));
leadRepository = new LeadService(mockLeadDatabaseService.Object, mockLeadWebService.Object, null, null);
}
[Test()]
public async void GetNormalLeads_WebServiceIsNotNull()
{
//Arrange
var parameters = new LeadRequestParams()
{
Offset = 0,
Limit = 20,
PageName = "Today",
};
//Act
var operationResult = await leadRepository.GetNormalLeads(parameters);
//Assert
Assert.IsNotNull(operationResult?.Data);
}
},
I think what you really need is:
var mockLeadRepository = new Mock<ILeadService>();
mockLeadRepository.Setup(x => x.GetNormalLeads(It.IsAny<Object>())).Returns(Task.FromResult(OperationResult.CreateSuccessResult(new GetLeadsApiResponseDTO())));
leadRepository = mockLeadRepository.Object;
That's my class
public class PersonelAtama
{
public int PersonelID { get; set; }
public int YonetimTalepID { get; set; }
public bool durum { get; set; }
}
I want to doDictionary<int,list<myclass>>
Dictionary<int, List<PersonelAtama>>
PersonelAtamaListesi = new Dictionary<int, List<PersonelAtama>>();
How to insert into the list
PersonelAtamaListesi.Add
How assignments are made
PersonelAtamaListesi[0][1]
PersonelAtamaListesi.Add(0,new PersonelAtama()
{
PersonelID = personelID,
YonetimTalepID = yonetimTalepID,
durum = false
});
assignment into the list and how to use again
I want to add to the list and component values to achieve. I want to sample code.
You have List as TValue so:
PersonelAtamaListesi.Add(0, new List<PersonelAtama>()
{
new PersonelAtama()
{
PersonelID = 1,
YonetimTalepID = 2,
durum = false
},
new PersonelAtama()
{
PersonelID = 11,
YonetimTalepID = 222,
durum = true
}
});
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