I have a repository, where I have this method for getting some data. Here is the code:
public List<HeatmapViewModel> GetStops()
{
using (var ctx = new GoogleMapTutorialEntities())
{
List<HeatmapViewModel> items = new List<HeatmapViewModel>();
#region firstitem_calculation
var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new Logging
{
Longitude2 = x.Longitude2,
Latitude2 = x.Latitude2,
CurDateTime = x.CurDateTime
}).FirstOrDefault();
var midnight = new DateTime(firstitem.CurDateTime.Year, firstitem.CurDateTime.Month, firstitem.CurDateTime.Day, 00, 00, 00);
TimeSpan difference = (firstitem.CurDateTime - midnight);
var difference_after_midnight = (int) difference.TotalMinutes;
items.Add( new HeatmapViewModel
{
FirstStartDifference = difference_after_midnight
});
#endregion
return items;
}
}
I need to call this method in controller, in this method:
public JsonResult GetStops()
{
}
How I can do this?
YourRepositoryName repo = new YourRepositoryName();
var _data = repo.GetStops();
public JsonResult GetStops()
{
var repo = new TheRepository();
var listOfHeatMapVm = repo.GetStops();
//Convert the list of HeatMapVm to Json result here.
return Json(listOfHeatMapVm);
}
Related
I need to save my list of objects to Firestore database. Below is my code:
How I Create the List of object
private async void LoadPlazaListAndSummary()
{
_plazaList = await _dc.GetPlazas();
foreach(var item in _plazaList)
{
var par = new ParameterManualTags
{
Plaza = item.Code,
Lane = item.Lane,
DateTo = System.DateTime.Now,
DateFrom = System.DateTime.Today
};
var manualCount = await _dc.GetManualAndTransactionCount(par);
var model = new Summary
{
Name = item.Name,
Lane = item.Lane,
Code = item.Code,
DateRun = System.DateTime.Now,
ManualAverage = 100.00,
ManualCount = manualCount[0],
ReadCount = 1,
TotalTransaction = manualCount[1],
Type = item.Type,
Plaza = item,
DateFrom = par.DateFrom,
DateTo = par.DateTo,
RfidAddress = item.ReaderIpAddress,
IsDedicated = item.IsDedicated ? "Dedicated" : "Mixed"
};
model.ManualAverage = Math.Round(ComputeManualPercentage(model), 2);
_summaryList.Add(model);
DgSummary.Items.Add(model);
}
}
This is my sample to save data to Firestore:
public void SetData()
{
if (_isConnected)
{
try
{
var doc = _database.Collection("MyCollection").Document("myDocument");
Dictionary<string, object> data = new Dictionary<string, object>()
{
{"FirstName", "MyFirstName"},
{"LastName", "MyLastName"},
{"PhoneNumber", "PhoneNumber"}
};
var x = doc.SetAsync(data);
Console.WriteLine("Saved");
}
catch (Exception ex)
{
Console.WriteLine($#"An error occured in saving the data: {ex.Message}");
}
}
}
Using my sample code, I can insert one at a time to Firestore but, I do not know how to save a list of objects to Firestore.
I need a list of all the animals names within a shelter. The shelter is chosen by id, so in this case 1.
The api-route should be /api/shelters/< id >/animals.
If the chosen id isn't a shelter it should be a 404 .
// specific list of animals in the chosen shelter -by Id-
public IActionResult animals(int ShelterId) {
var infoAnimals = ShelterDatabase.Shelter.Animals;
return new ObjectResult(infoAnimals);
}
var shelter = new Shelter.Shared.Shelter()
{
ShelterId = 1,
Name = "Our shelter"
};
shelter.Animals = new List<Animal>
{
new Cat{ Id = 1,Name = "Poes",DateOfBirth = new DateTime(2000, 02, 14),IsChecked = true,KidFriendly = false,Since = DateTime.Now,Declawed = true,Race = "Hairless Sphynx"},
new Cat{ Id = 2,Name = "Kity",DateOfBirth = new DateTime(2000, 02, 14),IsChecked = true,KidFriendly = false,Since = DateTime.Now,Declawed = true,Race = "Hairless Sphynx"},
new Cat{ Id = 3,Name = "wietel",DateOfBirth = new DateTime(2000, 02, 14),IsChecked = true,KidFriendly = false,Since = DateTime.Now,Declawed = true,Race = "Hairless Sphynx"},
new Dog{ Id = 4,Name = "Felix",DateOfBirth = new DateTime(2000, 02, 14),IsChecked = true,KidFriendly = true,Since = DateTime.Now,Barker = true,Race = "Golden Retriever"},
new Dog{ Id = 5,Name = "peppa",DateOfBirth = new DateTime(2000, 02, 14),IsChecked = true,KidFriendly = true,Since = DateTime.Now,Barker = true,Race = "Danish Dog"},
};
Firstly take a look at the documentation
The default routing scheme will be like this: "[controller]/[action]/{id}",
So for every action in the controller there will be a separate route
In your case /api/shelters/< id >/animals, your route misses the action or they are in incorrect order
I would do it like this:
//api/shelters/0
[HttpGet("[controller]/{id}")]
public IActionResult sherlter(int ShelterId) {
var shelter = ShelterDatabase.Shelter;
return new ObjectResult(shelter);
}
//api/shelters/animals/0
[HttpGet("[controller]/[action]/{id}")]
public IActionResult animals(int ShelterId) {
var infoAnimals = ShelterDatabase.Shelter.Animals;
return new ObjectResult(infoAnimals);
}
(Use annotations: [HttpGet] for .net core or [Route] for .net framework)
Your code should look similar to this:
public IActionResult animals(int ShelterId)
{
var shelters = ShelterDatabase.Shelter; // this should be collection of shelters
var shelter = shelters.FirstOrDefault(_ => _.ShelterId == ShelterId);
if (shelter == null)
{
return NotFound();
}
var animals = shelter.Animals;
return new ObjectResult(animals);
}
Try this, you must specify the request method allowed (Get, Post, Put, Delete) and give it a route prefix/suffix and route name (animals).
// specific list of animals in the chosen shelter -by Id-
[HttpGet("{id}/animals")]
public IActionResult animals(int ShelterId) {
var infoAnimals = ShelterDatabase.Shelter.Animals;
return new ObjectResult(infoAnimals);
}
I have a search method that queries Solr for event items. I need to modify it to only get events where the date has not already passed (i.e. Where(x => x.EventDate.Date >= DateTime.Now.Date), but I'm not sure how to add this because I'm not very familiar with Solr. Here's my search function:
public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
{
new IsSearchablePredicateBuilder()
};
if (contentTypeFilters.Any())
{
var contentTypePredicateBuilder = new ContentTypePredicateBuilder();
contentTypePredicateBuilder.ContentTypes = contentTypeFilters;
searchFilters.Add(contentTypePredicateBuilder);
}
if (otherFilters.Any())
{
var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);
searchFilters.Add(tagFilterBuilder);
}
if (string.IsNullOrWhiteSpace(keywords))
{
keywords = "";
}
SearchRequest searchRequest = new SearchRequest();
var queryParams = new Dictionary<string, string>() { };
queryParams.Add("q", keywords);
searchRequest.QueryParameters = queryParams;
searchRequest.SortBy = "";
searchRequest.SortOrder = "";
SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
queryArguments.FilterBuilders = searchFilters;
queryArguments.Page = page;
queryArguments.PerPage = perPage;
queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
queryArguments.SearchRequest = searchRequest;
queryArguments.IndexName = _indexName;
if (string.IsNullOrWhiteSpace(keywords))
{
queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
}
else
{
queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
}
queryArguments.SortBuilder = sortBuilder;
try
{
var results = _searchManager.GetResults<SearchResultItem>(queryArguments);
SearchQueryResults queryResults = new SearchQueryResults();
queryResults.ResultItems = results.Results;
queryResults.CurrentPage = page;
queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());
queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;
return queryResults;
}
catch (Exception exc)
{
Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
return null;
}
}
and here is how it's being called:
Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));
How do I add in date filtering so that it only returns items where the date is in the future?
I would add filter query to the list of existing ones filtering the date field. On the documentation page, I was able to find information about fluent API, which could help here
Query.Field("date").From(DateTime.Now)
I'm not C# developer, that this code could have some mistakes, but I think the main idea is clear what needs to be done.
So I have action Method in my controller which get data from the CSV file which I uploaded through web
I want to pass that data to Insert controller so data from the CSV will automatically inserted to tables in my DB and pass it to view
I'm using CSV HELPER, MVC
public ActionResult ImportCSV(HttpPostedFileBase file, int compID)
{
var compName = db.CourierCompanies.Find(compID);
string path = null;
List<MyViewModel> csvD = new List<MyViewModel>();
try
{
if(file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "upload\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var invoCSV = csv.GetRecords<ImportCsV>();
foreach(var i in invoCSV)
{
MyViewModel iCSV = new MyViewModel();
iCSV.CustID = i.cust_id;
iCSV.Fullname = i.fullname;
iCSV.CustComp = i.company;
iCSV.InvoiceNo = i.rec_no;
iCSV.InsertDate = DateTime.Parse(i.doc_dt);
iCSV.Road = i.w_addr1;
iCSV.City = i.w_city;
iCSV.Zip = i.w_zip;
iCSV.Phone = i.w_phone;
iCSV.Status = "BelumTerkirim";
iCSV.compID = compID;
iCSV.CompName = compName.CompName;
iCSV.StatDate = DateTime.Now;
csvD.Add(iCSV);
}
}
}
catch
{
ViewData["Error"] = "Upload Failed";
}
return View();
}
Insert Controller
public ActionResult Create( MyViewModel model, int compID, HttpPostedFileBase file)
{
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
model.Image = ms.GetBuffer();
}
}
var cust = new Customer()
{
CustID = model.CustID,
Phone = model.Phone,
CustComp = model.CustComp,
Fullname = model.Fullname
};
var addrDet = new AddrDetail()
{
Road = model.Road,
City = model.City,
Zipcode = model.Zip
};
var invoice = new Invoice()
{
InvoiceNo = model.InvoiceNo
};
var stat = new Status()
{
Status1 = model.Status,
StatDate = model.StatDate,
Ket = model.Ket
};
var image = new Models.Image()
{
Image1 = model.Image
};
var detail = new DetailPengiriman()
{
NamaPenerima = model.NamaPenerima,
StatusPenerima = model.StatusPenerima,
TrDate = model.TrDate,
InsertDate = model.InsertDate
};
if (ModelState.IsValid )
{
//customer
db.Customers.Add(cust);
detail.CustID = cust.CustID;
invoice.CustID = cust.CustID;
//addrDet
db.AddrDetails.Add(addrDet);
cust.AddrDetID = addrDet.AddrDetID;
//invoice
db.Invoices.Add(invoice);
stat.InvoiceNo = invoice.InvoiceNo;
image.InvoiceNo = invoice.InvoiceNo;
detail.InvoiceNo = invoice.InvoiceNo;
//status
db.Status.Add(stat);
detail.StatusID = stat.StatusID;
////image
db.Images.Add(image);
detail.ImageID = image.ImageID;
//detail
detail.CompID = compID;
db.DetailPengirimen.Add(detail);
db.SaveChanges();
return RedirectToAction("Index", new { compID = detail.CompID});
}
return View();
}
You can abstract that business logic in another class and instantiate it inside your CSV action.
This way your can call your methods for inserting customers from both actions!
So I have a controller that returns json to my views that I need to test. I have tried using reflection with a dynamic data type to access a sub property of a list but I keep getting something similar to 'unable to cast' errors. Basically I have a list within a list that I want to access and verify things about but I can't access it. Has anyone tested json returned from their controller before in MVC4 and have advice?
Code:
// arrange
var repositoryMock = new Mock<IEdwConsoleRepository>();
var date = -1;
var fromDate = DateTime.Today.AddDays(date);
EtlTableHistory[] tableHistories =
{
new EtlTableHistory
{
Table = new Table(),
RelatedStatus = new BatchStatus(),
BatchId = 1
}
};
EtlBatchHistory[] batchHistories = { new EtlBatchHistory
{
Status = new BatchStatus(),
TableHistories = tableHistories
} };
repositoryMock.Setup(repository => repository.GetBatchHistories(fromDate)).Returns((IEnumerable<EtlBatchHistory>)batchHistories);
var controller = new EdwController(new Mock<IEdwSecurityService>().Object, repositoryMock.Object);
// act
ActionResult result = controller.BatchHistories(1);
// assert
Assert.IsInstanceOfType(result, typeof(JsonResult), "Result type was incorrect");
var jsonResult = (JsonResult)result;
var resultData = (dynamic)jsonResult.Data;
var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);
var returnedTableHistoriesType = returnedHistories.GetType();
Assert.AreEqual(1, returnedTableHistoriesType.GetProperty("Count").GetValue(returnedHistories, null), "Wrong number of logs in result data");
Here's an example:
Controller:
[HttpPost]
public JsonResult AddNewImage(string buildingID, string desc)
{
ReturnArgs r = new ReturnArgs();
if (Request.Files.Count == 0)
{
r.Status = 102;
r.Message = "Oops! That image did not seem to make it!";
return Json(r);
}
if (!repo.BuildingExists(buildingID))
{
r.Status = 101;
r.Message = "Oops! That building can't be found!";
return Json(r);
}
SaveImages(buildingID, desc);
r.Status = 200;
r.Message = repo.GetBuildingByID(buildingID).images.Last().ImageID;
return Json(r);
}
public class ReturnArgs
{
public int Status { get; set; }
public string Message { get; set; }
}
Test:
[TestMethod]
public void AddNewImage_Returns_Error_On_No_File()
{
// Arrange
ExtendedBuilding bld = repo.GetBuildings()[0];
string ID = bld.Id;
var fakeContext = new Mock<HttpContextBase>();
var fakeRequest = new Mock<HttpRequestBase>();
fakeContext.Setup(cont => cont.Request).Returns(fakeRequest.Object);
fakeRequest.Setup(req => req.Files.Count).Returns(0);
BuildingController noFileController = new BuildingController(repo);
noFileController.ControllerContext = new ControllerContext(fakeContext.Object, new System.Web.Routing.RouteData(), noFileController);
// Act
var result = noFileController.AddNewImage(ID, "empty");
ReturnArgs data = (ReturnArgs)(result as JsonResult).Data;
// Assert
Assert.IsTrue(data.Status == 102);
}
In your example it looks to me that the problem is here:
var resultData = (dynamic)jsonResult.Data;
var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);
The resultData object would be the exact type of the object that you returned in your action. So if you did something like:
List<String> list = repo.GetList();
return Json(list);
Then your resultData would be of type:
List<String>
Try making sure that you are returning your Object using the Json(obj) function.
You can deserialize your Json into a dynamic object and then ask for the property you want
Example:
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var propertyValue = obj.MyProperty; //Ask for the right property
You can add Json serializer from Nuget Json.Net package.