I have two urls to call to get json object and tabulate them in tableviewcontroller. However, I could not able to figure out how to Create a single TableSource that can handle two different instances of List.
public void Inbox()
{
var ts= new TableSource(this);
TableView.Source=ts;
var client1 = new RestClient ("MyURL");
client1.Authenticator = new HttpBasicAuthenticator ("admin", "admin");
var request1 = new RestRequest ("MYURL/x/y");
request1.AddHeader ("Accept", "application/json");
request1.AddHeader ("Content-Type", "application/json");
var client2 = new RestClient ("MyURL");
client2.Authenticator = new HttpBasicAuthenticator ("admin", "admin");
var request2 = new RestRequest ("MYURL/a/b");
request2.AddHeader ("Accept", "application/json");
request2.AddHeader ("Content-Type", "application/json");
client1.ExecuteAsync (request1, response1 => {
aTasks = Newtonsoft.Json.JsonConvert.DeserializeObject<List<HTask>> (response1.Content);
InvokeOnMainThread (() => {
ts.Data1= aTasks;
TableView.ReloadData();
});
});
client2.ExecuteAsync (request2, response2 => {
bTasks = Newtonsoft.Json.JsonConvert.DeserializeObject<List<HTask>> (response2.Content);
InvokeOnMainThread (() => {
ts.Data2= bTasks;
TableView.ReloadData();
});
});
}
create your TableSource and assign it when you create your TableView. Instead of passing the data in the constructor, create two public properties for the two different datasets you're working with.
var ts = new TableSource(this);
TableView.Source = ts;
later, then you have your data loaded, update your existing TableSource
ts.Data1 = aTasks;
TableView.ReloadData();
when your second set of data loads, update your existing TableSource again
ts.Data2 = bTasks;
TableView.ReloadData();
Related
Hi I am just learning Xamarin android development and I just want to CRUD operation but I am stuck that I am unable to get any response from webapi. I have tested my api using SOAPUI and response is ok from that.
[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
if (value != "1234")
{
string json = #"{ data: 'Emp Code is not valid.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
else
{
string json = #"{ data: 'data save sucessfully.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
}
this is api code and below is my android application code but I am getting null response exception.
public async Task SaveTodoItemAsync(string EmpCode)
{
try
{
string url = "http://192.168.1.9/attandanceapi/api/attandance?value=12132";
var uri = new Uri(string.Format(url));
var json = JsonConvert.SerializeObject(EmpCode);
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(url, content);
var responses = response;
}
catch (Exception ex)
{
var w = ex.ToString();
}
}
I think we have problem here. You are trying to create content from string not from Json.
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
try this:
var content = new StringContent(json, Encoding.UTF8, "application/json");
Edit:
I cannot see your default headers so if you don't have them - just add.
client.DefaultRequestHeaders.Add("Accept", "application/json");
Hi Have This Code, I Want This Function To Return A List Of CLS_EL_ARCHIVE Objects But I Get This Error :
'CLS_EL_ARCHIVE' does not contain a constructor that takes 0 argument
public override IEnumerable<CLS_EL_ARCHIVE> GetAll()
{
DataTable DT = DAC.SelectData("SP_GET_ALL", new SqlParameter[] { new SqlParameter("#Table", "ARCHIVE") });
List<CLS_EL_ARCHIVE> ArchiveList = new List<CLS_EL_ARCHIVE>();
ArchiveList = DT.AsEnumerable().Select(Row => new CLS_EL_ARCHIVE
{
ArchiveId = Row.Field<int>("ArchiveId"),
Label = Row.Field<string>("Label"),
Date = Row.Field<DateTime>("Date"),
Note = Row.Field<string>("Note")
});
return ArchiveList;
}
This is working for me :) waiting for more answers
DataTable DT = DAC.SelectData("SP_GET_ALL", new SqlParameter[] { new SqlParameter("#Table", "ARCHIVE") });
List<CLS_EL_ARCHIVE> ArchiveList = new List<CLS_EL_ARCHIVE>();
ArchiveList = DT.AsEnumerable().Select(Row => new CLS_EL_ARCHIVE(Row.Field<int>("ArchiveId"), Row.Field<string>("Label"),
Row.Field<DateTime>("Date"), Row.Field<string>("Note"))).ToList();
I'm having a bit of a problem, I'm trying to do a http post request to my backend php. I'm new to angular and wanted to try the different REST method. I'm good with GET method. After this I will try UPDATE and DELETE method but for now I'm stuck on this. T__T.
Here a bit of the code in php
$data = array(
"email" => $email,
"password" => $this->input->post("password")
);
$insert_data = $this->player_registration->insert($data);
And here my factory
angular.module('myApp.services', ['ngResource'])
.factory('webService', function($resource){
var apiUrl = "http:domain.com/feed/"; //change this to web service
var factory = {};
factory.registerPlayer = function() {
return $resource( apiUrl + ':type', {type:'player'}, {
post: {method:'POST', params: {}}
});
};
factory.getPlayerByEmail = function () {
return $resource( apiUrl + ':type', {type:'player'}, {
get: {method: "GET", params: {}}
});
};
return factory;
})
And my controller
function registerController($scope, webService) {
$scope.inputs = {};
$scope.inputs.email = "testuser#domain.com";
$scope.inputs.password = "password";
var req = new webService.registerPlayer($scope.inputs);
req.save()
My app.js
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers'])
The default save() in $resources is actually $save().
var req = new webService.registerPlayer($scope.inputs);
req.$save()
I am trying to POST parameters through the request, to a service that returns a JSON object. The service works well for android and iOS. I am trying to get this working for wp7. The service requires the content type to be 'application/json' I have pasted the code that sets up the http request below:
var client = new RestClient(baseurl);
var request = new RestRequest();
request.Resource = "login";
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.AddHeader("content-type", "application/json");
request.RequestFormat = DataFormat.Json;
var postData = new Dictionary<string, string>()
{
{"key1",value1},
{"key2",value2}
};
request.AddBody(postData);
client.ExecuteAsync(request, response =>
{
var jsonUser = response.Content;
});
The response error I get from the server is an internal server error. Is anything wrong with the code above. I also tried request.AddParameter method but ended with the same result. The code for that is below:
var client = new RestClient(baseurl);
var request = new RestRequest();
request.Resource = "login";
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.AddHeader("content-type", "application/json");
request.RequestFormat = DataFormat.Json;
var postData = new Dictionary<string, string>()
{
{"key1",value1},
{"key2",value2}
};
var json = JsonConvert.SerializeObject(postData);
request.AddParameter("application/json", json, ParameterType.RequestBody);
client.ExecuteAsync(request, response =>
{
var jsonUser = response.Content;
});
Is there anything that I am doing wrong in either of the cases?
I Have the following test:
[Test]
public void Add_New_Group_Should_Return_StatusCode_Created_And_A_Header_Location_To_The_New_Group()
{
var newGroup = new GroupData { ID = 1, UserID = 1, Name = "Group 1", Description = "Description 1" };
var fakeGroupDAL = A.Fake<IGroupDAL>();
var contactGroupsController = new ContactGroupsController(fakeGroupDAL);
SetupControllerForTests(contactGroupsController, HttpMethod.Post);
var response = contactGroupsController.AddGroup(new ContactGroupApiRequest(), newGroup);
Assert.IsTrue(response.StatusCode == HttpStatusCode.Created, "Should have returned HttpStatusCode.Created");
}
Which calls the following configuration method:
private static void SetupControllerForTests(ApiController controller, HttpMethod httpMethod)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(httpMethod, "http://localhost/contactgroups");
var route = config.Routes.MapHttpRoute("ContactGroupsApi", "{controller}/{action}/{request}", new { request = RouteParameter.Optional });
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "contactgroups" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
I'm trying to test the following action method:
[HttpPost]
public HttpResponseMessage AddGroup([FromUri]ApiRequest req, [FromBody] GroupData contactGroup)
{
if(ModelState.IsValid && contactGroup !=null)
{
_groupDal.AddGroup(contactGroup);
contactGroup.Name = HttpUtility.HtmlEncode(String.Format("{0} - {1}", contactGroup.Name, contactGroup.Description));
var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(contactGroup.Name) };
var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group", UserId = contactGroup.UserID, GroupId = contactGroup.ID});
response.Headers.Location = new Uri(uriString);
return response;
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
The action method works perfectly well when called normally, but fails under test because the call to Url.Link returns null.
var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group", UserId = contactGroup.UserID, GroupId = contactGroup.ID});
All this code is based very closely on the following article: Unit test ASP.NET Web Api
I suspect that when running under test there is insufficient route table info. Any idea what I'm doing wrong?
I fixed my tests by adding the HttpRouteData to the HttpRouteDataKey property of the controller's HttpRequestMessage. Like this:
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;