I create the following function to calculate total between two dates but always get null value what was wrong ?
void calcul_total_period() async {
var totalSumPeriod = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['TOTAL']; //['$startDate''$endDate'];
print(' $totalSumPeriod');
setState(() {
somme_period = totalSumPeriod ?? 00;
somme_total_period = somme.toStringAsFixed(2);
});
}
function in db
Future claculTotalPeriod (String startDate, String endDate) async {
var totalClientperiod = await database;
var result = await totalClientperiod.rawQuery("SELECT SUM($colPrix) AS TOTAL from $clientTable WHERE $colDate BETWEEN '$startDate' AND '$endDate'");
print('$result');
return result.toList();
}
What's somme ?
void calcul_total_period() async {
var totalSumPeriod = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['TOTAL']; //['$startDate''$endDate'];
print(' $totalSumPeriod');
setState(() {
somme_period = totalSumPeriod ?? 00;
somme_total_period = ---> somme <----.toStringAsFixed(2);
});
}
I have the following entities:
Batch
Samples
SampleContainers
SampleTests
A batch contains many samples. A sample contains many SampleContainers and many SampleTests.
I am trying to make a copy of batch and insert into database.
Attempt #1: get function in repository:
return await context.Set<TEntity>().FindAsync(id);
Controller:
var coc = await repository.Get(batchId);
coc.BatchStatusId = (int)Enums.BatchStatus.InProgress;
coc.IsTemplate = false;
coc.Id = 0;
var b = await repository.Add(coc);
Here only batch object was duplicated but related samples and containers were not duplicated/inserted.
Attempt #2: I changed my Get function as follows:
public async override Task<Batch> Get(int id)
{
return await context.Set<Batch>()
.Include(p => p.Samples)
.FirstOrDefaultAsync(p => p.Id == id);
}
This time batch was duplicated but samples and containers and tests were all updated with new batchId/FK (I wanted them all to be duplicated).
Attempt #3: following this, I implemented as follows:
public async Task<int> DuplicateBatch([FromBody]int batchId)
{
try
{
var coc = await repository.Get(batchId);
coc.BatchStatusId = (int)Enums.BatchStatus.InProgress;
coc.IsTemplate = false;
coc.Id = 0;
var samples = coc.Samples.ToList();
repository.DetachEntity(coc);
var b = await repository.Add(coc);
var allSampleTests = await sampleTestRepo.GetAll();
var allSampleContainers = await sampleContainersRepo.GetAll();
var sampletests = from st in allSampleTests
join s in samples on st.SampleId equals s.Id
select st;
var sampleContainers = from sc in allSampleContainers
join s in samples on sc.SampleId equals s.Id
select sc;
sampleRepo.DetachEntities(samples);
sampleTestRepo.DetachEntities(sampletests.ToList());
sampleContainersRepo.DetachEntities(sampleContainers.ToList());
foreach (var s in samples)
{
s.BatchId = b.Id;
var sample = await sampleRepo.Add(s);
foreach (var st in sampletests)
{
st.SampleId = sample.Id;
await sampleTestRepo.Add(st);
}
foreach(var sc in sampleContainers)
{
sc.SampleId = sample.Id;
await sampleContainersRepo.Add(sc);
}
}
return 1;
}
catch (Exception ex)
{
return 0;
}
}
This time I am facing the following exception as soon as I reach Detach function:
{"The property 'Batch.Id' is part of a key and so cannot be modified
or marked as modified. To change the principal of an existing entity
with an identifying foreign key, first delete the dependent and invoke
'SaveChanges', and then associate the dependent with the new
principal."}
This is how I did it, most of it is self explanatory.
public async Task<int> DuplicateBatch([FromBody]int batchId)
{
try
{
//STEP 1: Fetch the entities
var coc2 = await repository.Get(batchId);
var samples = coc2.Samples.ToList();
var allSampleTests = await sampleTestRepo.GetAll();
var allSampleContainers = await sampleContainersRepo.GetAll();
var sampletests = samples.SelectMany(st => st.SampleTests).ToList();
var samplecontainers = samples.SelectMany(st => st.SampleContainers).ToList();
//STEP 2: Detach
var coc = repository.DetachEntity(coc2);
var samplesDetached = sampleRepo.DetachEntities(samples);
var sampleTestsDetached = sampleTestRepo.DetachEntities(sampletests);
var sampleContianersDetached = sampleContainersRepo.DetachEntities(samplecontainers);
//STEP 3: Update object
coc2.BatchStatusId = (int)Enums.BatchStatus.InProgress;
coc2.IsTemplate = false;
var b = await repository.Add(coc);
return 1;
}
catch (Exception ex)
{
return 0;
}
}
An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.
Here is the Api Controller:
EmailTemplate.UI\Areas\Ticket\Api\TicketController.cs
HERE IS THE CODE:
var client = new HttpClient();
string _url = _apiTicket + "Areas/Ticket/Api/TicketController/Get/10?PageIndex=" + pageIndex + "&PageSize=" + pageSize;
var response = client.GetAsync(_url).Result;
var result1 = response.Content.ReadAsStringAsync().Result;
here in response this error comes.
i want to filter data by pageIndex and pagesize in datatable server side mvc 4.
Here is the method in api:
public HttpResponseMessage Get1(int UserId)
{
string _searchString = GetQueryValueByName.Get(Request.GetQueryNameValuePairs(), "searchstr");
int _start = int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),"start"));
int _length =int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),"length"));
List<sp_Ticketlist_Result> _dbData;
int _dataTotaRowCount;
_dbData = _repository.GetTicket(UserId).ToList();
_dataTotaRowCount = _dbData.Count();
if (!string.IsNullOrEmpty(_searchString))
{
_dbData = _dbData.Where(m =>
m.Name.ToUpper().Contains(_searchString.ToUpper())).ToList();
_dataTotaRowCount = _dbData.Count();
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
else
{
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
return Request.CreateResponse(HttpStatusCode.OK,DataTableObjectConverter.ConvertData(_dbData, _dataTotaRowCount));
}
public static class GetQueryValueByName
{
public static string Get(IEnumerable<KeyValuePair<string, string>> _req,
string key)
{
return _req.FirstOrDefault(ma => string.Compare(ma.Key, key) ==
0).Value;
}
}
public static class DataTableObjectConverter
{
public static DataTableObject ConvertData<T>(T source, int count)
where T : class, new()
{
DataTableObject _obj = new DataTableObject();
//_obj.draw = 1;
_obj.recordsFiltered = count;
_obj.recordsTotal = count;
_obj.data = source;
return _obj;
}
}
Is there need for any method with pageIndex and pagesize??
how do i call data through pageIndex and pagesize defines in method??
Here is my GetData method:
public ActionResult GetData()
{
// Initialization.
JsonResult result = new JsonResult();
try
{
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
// int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int recordStatr = start != null ? Convert.ToInt32(start) : 0;
recordStatr = recordStatr == 0 ? 1 : recordStatr;
var pageIndex = (recordStatr / pageSize) + 1;
int recordsTotal = 0;
// Loading.
List<AppTicket> data = this.LoadData();
// Total record count.
int totalRecords = data.Count;
// Verification.
//if (!string.IsNullOrEmpty(search) &&
// !string.IsNullOrWhiteSpace(search))
//{
// // Apply search
// data = data.Where(p => p.Title.ToString().ToLower().Contains(search.ToLower()) ||
// p.Name.ToLower().Contains(search.ToLower()) ||
// p.Email.ToString().ToLower().Contains(search.ToLower())).ToList();
// //p.ProductName.ToLower().Contains(search.ToLower()) ||
// //p.SpecialOffer.ToLower().Contains(search.ToLower()) ||
// //p.UnitPrice.ToString().ToLower().Contains(search.ToLower()) ||
// //p.UnitPriceDiscount.ToString().ToLower().Contains(search.ToLower())).ToList();
//}
// Sorting.
data = this.SortByColumnWithOrder(order, orderDir, data);
// Filter record count.
int recFilter = data.Count;
// Apply pagination.
// data = data.Skip(startRec).Take(pageSize).ToList();
// Loading drop down lists.
// result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = data }, JsonRequestBehavior.AllowGet);
//Find Order Column
//var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
//var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var client = new HttpClient();
//client.BaseAddress = new Uri("http://localhost:1849");
//client.DefaultRequestHeaders.Accept.Clear();
// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// string _url = _apiTicket + ".Get?UserId=" + 10 + "&PageIndex=" + pageIndex + "&PageSize=" + pageSize;
//var response = client.GetAsync(_url).Result;
//var response1 = client.GetAsync("/Areas/Ticket/Api/Get/10,10,10").Result;
//if (response1.IsSuccessStatusCode)
//{
// string responseString = response.Content.ReadAsStringAsync().Result;
//}
// string _url = _apiTicket + "Get1/10?searchstr=Monaj&PageIndex=" + pageIndex + "&PageSize=" + pageSize;
// string apiUrl = "Api/Ticket/10?searchstr=Monaj&PageIndex=" + pageIndex + "&PageSize=" + pageSize;
string apiUrl = "../Areas/api/Ticket/1?searchstr=Monaj&start=0&length=10";
var response = client.GetAsync(apiUrl).Result;
var result1 = response.Content.ReadAsStringAsync().Result;
// HttpResponseMessage response = await client.GetAsync(_url);
// HttpResponseMessage response = client.GetAsync(_url).Result;
//var response = client.GetAsync(_url).Result;
// var result1 = response.Content.ReadAsStringAsync().Result;
JsonResult jsonresult = Json(result1, JsonRequestBehavior.AllowGet);
AppTicket _contacts = new AppTicket();
_contacts = JsonConvert.DeserializeObject<AppTicket>(jsonresult.Data.ToString());
//return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = _contacts.listcourses }, JsonRequestBehavior.AllowGet);
result = this.Json(new { draw = Convert.ToInt32(draw), recordsFiltered = totalRecords, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// Info
Console.Write(ex);
}
// Return info.
return result;
}
I am using the json ajax here in custom-datatable.js.
here is the code:
$(document).ready(function ()
{
debugger
$('#TableId').DataTable(
{
//"columnDefs": [
// { "width": "5%", "targets": [0] },
// {
// "className": "text-center custom-middle-align",
// "targets": [0, 1, 2, 3, 4, 5, 6]
// },
//],
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'width': '1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta) {
return '<input type="checkbox">';
}
}
,
{
targets: 2,
render: function (data, type, row, meta) {
if (type === 'display') {
data = '<a href="/TicketTemplate/AppDetails/' + row.Id + ' " >' + data + '</a>';
}
return data;
}
},
{
targets: 1,
render: function (data, type, row, meta) {
return moment(data).format('DD/MM/YYYY HH:mm:ss');
}
}
],
"language":
{
"processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax":
{
"url": "/TicketTemplate/GetData",
"type": "POST",
"dataType": "JSON"
},
"columns": [
{ "data": '' },
{ "data": "CreatedDate" },
{ "data": "Title" },
//{
// //"data": "title",
// "render": function (data, type, row, meta) {
// //return '' + title + '';
// return '' + data + '';
// }
//},
//{
//{
// //"data": "title",
// "render": function (data, type, row, meta) {
// //return '' + title + '';
// return "" + row.Title + " ";
// }
//},
{ "data": "Name" },
{ "data": "Email" },
{ "data": "AssignTo" },
{ "data": "Status" }
]
});
});
First of all it hit the Mvc controller GetData() and in GetData() call the Api Controller Get().
Paging sorting searching all are in using api dynamically.
As you have mentioned in your comment that, "i want to call the datatable paging sorting searching through MVC controller and web api controller", then I would recommend to do like this, that is what i have done in many projects.
//This is my API Get method
public HttpResponseMessage Get(int id)
{
string _searchString =
GetQueryValueByName.Get(Request.GetQueryNameValuePairs(), "searchstr");
int _start =
int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),
"start"));
int _length =
int.Parse(GetQueryValueByName.Get(Request.GetQueryNameValuePairs(),
"length"));
List<sp_Ticketlist_Result> _dbData;
int _dataTotaRowCount;
_dbData = _repository.GetTicket(id).ToList();
_dataTotaRowCount = _dbData.Count();
if (!string.IsNullOrEmpty(_searchString))
{
_dbData = _dbData.Where(m =>
m.Name.ToUpper().Contains(_searchString.ToUpper())).ToList();
_dataTotaRowCount = _dbData.Count();
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
else
{
_dbData = _dbData.Skip(_start).Take(_length).ToList();
}
return Request.CreateResponse(HttpStatusCode.OK,
DataTableObjectConverter.ConvertData(_dbData, _dataTotaRowCount));
}
Bellow is my GetQueryValueByName and DataTableObjectConverter Class, that i kept in a separated class file and just reference to my Api Controller.
public static class GetQueryValueByName
{
public static string Get(IEnumerable<KeyValuePair<string, string>> _req,
string key)
{
return _req.FirstOrDefault(ma => string.Compare(ma.Key, key) ==
0).Value;
}
}
public static class DataTableObjectConverter
{
public static DataTableObject ConvertData<T>(T source, int count)
where T : class, new()
{
DataTableObject _obj = new DataTableObject();
//_obj.draw = 1;
_obj.recordsFiltered = count;
_obj.recordsTotal = count;
_obj.data = source;
return _obj;
}
}
public class DataTableObject
{
public int recordsTotal { get; set; }
public int recordsFiltered { get; set; }
public Object data { get; set; }
}
Then my URL will be like this,
string apiUrl = "http://localhost:55442/api/Ticket/1?
searchstr=Monaj&start=0&length=10";
var client = new HttpClient();
var response = client.GetAsync(apiUrl).Result;
var result1 = response.Content.ReadAsStringAsync().Result;
Note: See, here I'm passing start,length,search string as query string and I'm fetching them in my Api Get method. Just update your URL here and don't give / in query string parameters. You have written like this,
" + pageIndex + "/PageSize=" + pageSize;
This is wrong. Check how I have done. You need to separate by &
Hi can anyone answer me why this linq query wont return by date?
DocumentStore store = new DocumentStore { Url = "http://localhost:8080/" };
store.Initialize();
using (var session = store.OpenSession())
{
bool carExists = session.Query<Car>().Any(c => c.CarId == 1);
if (!carExists)
{
Car myNewCar = new Car
{
CarId = 1,
ManufactureDate = new DateTime(2010, 1, 1),
Name = "Porshe"
};
session.Store(myNewCar);
session.SaveChanges();
}
IQueryable<Car> cars = session.Query<Car>()
.Where(c => c.ManufactureDate == new DateTime(2010, 1, 1));
foreach (var car in cars)
{
Console.WriteLine(car.Name);
}
Console.ReadKey();
}
Your index is stale at the second query. Review the documentation.
Also, your first query should be a Load instead. Review the documentation.
DocumentStore store = new DocumentStore { Url = "http://localhost:8080/" };
store.Initialize();
using (var session = store.OpenSession())
{
bool carExists = session.Load<Car>(1) != null;
if (!carExists)
{
Car myNewCar = new Car
{
CarId = 1,
ManufactureDate = new DateTime(2010, 1, 1),
Name = "Porshe"
};
session.Store(myNewCar);
session.SaveChanges();
}
IQueryable<Car> cars = session.Query<Car>()
.Customize(x=> x.WaitForNonStaleResults()) // only for testing!
.Where(c => c.ManufactureDate == new DateTime(2010, 1, 1));
foreach (var car in cars)
{
Console.WriteLine(car.Name);
}
Console.ReadKey();
}
I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.