C# Solr query - how to only get future dates? - c#

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.

Related

How to save a List of objects to Firestore

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.

Adding Sort functionality with Lucene.Net

I am working on implementing Search using Lucene.Net in my E Commerce site. I want to Sort by result depending on user selected criterion. It might be Name,Price,Discount,NewArrivals etc
My Code
var sortBy = new Lucene.Net.Search.Sort(new Lucene.Net.Search.SortField("Name", Lucene.Net.Search.SortField.STRING, true));
//var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Name", analyzer);
//Query searchQuery = parser.Parse(query);
//TopDocs hits = searcher.Search(searchQuery, int.MaxValue);
//Sort sort=new Sort
//TopDocs hits = searcher.Search(QueryMaker(query, searchfields, storeId), int.MaxValue);
TopFieldDocs hits = searcher.Search(QueryMaker(query, searchfields, storeId),null,int.MaxValue,sortBy);
int results = hits.TotalHits;
Product searchResult = null;
if (results < limit)
limit = results;
//if (limit == 0)
// limit = int.MaxValue;
for (int i = (pagenumber*limit) + 1; i <= ( ( pagenumber * limit ) + limit); i++)
{
try
{
Document doc = searcher.Doc(hits.ScoreDocs[i-1].Doc);
searchResult = new Product();
searchResult.Id = Convert.ToInt32(doc.Get("Id"));
searchResult.Name = doc.Get("Name");
searchResult.SeName = doc.Get("SeName");
searchResult.StoreId = Convert.ToInt32(doc.Get("StoreId"));
searchResults.Add(searchResult);
searchResult = null;
}
catch (Exception ae)
{
}
}
But this doesnt give me expected result and does not sort products using its Name
Any Solutions

Testing JSON Results from MVC 4 C# Controller

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.

ebay GetOrders API using OutputSelector and SortOrder - .Net SDK

I am using ebay .Net SDK. Everything is working fine except following requirements:
Using of OutputSelector to boost performance
Unable to use SortingOrder, while showing records.
Total income/amount sold for specified time range i.e. Total amount across all calls of the pagination without looping through pages and aggregating it manually.
Here is the code which I am using:
var apicall = new GetOrdersCall(context);
//apicall.ApiRequest.OutputSelector = new StringCollection(new String[] { "Order.OrderID", "Order.Total" });
apicall.ApiRequest.Pagination = new PaginationType
{
EntriesPerPage = Util.RecordsPerPage(),
PageNumber = int.Parse(Request.Form["pageNumber"])
};
var fltr = new TimeFilter(Convert.ToDateTime(Request.Form["dateFrom"] + "T00:00:00.000Z"), Convert.ToDateTime(Request.Form["dateTo"] + "T23:59:59.999Z"));
var statusCodeType = (OrderStatusCodeType)Enum.Parse(typeof(OrderStatusCodeType), Request.Form["statusCode"]);
var orders = apicall.GetOrders(fltr, TradingRoleCodeType.Seller, statusCodeType);
Please assist me how to use these 3 functionality as well.
After much efforts I got the way for it:
var request = new GetOrdersRequestType
{
//OutputSelector = new StringCollection {"OrderID","Total"},
CreateTimeFrom = Convert.ToDateTime(Request.Form["dateFrom"] + "T00:00:00.000Z"),
CreateTimeTo = Convert.ToDateTime(Request.Form["dateTo"] + "T23:59:59.999Z"),
OrderStatus = (OrderStatusCodeType)Enum.Parse(typeof(OrderStatusCodeType), Request.Form["statusCode"]),
OrderRole = TradingRoleCodeType.Seller,
Pagination = new PaginationType
{
EntriesPerPage = Util.RecordsPerPage(),
PageNumber = int.Parse(Request.Form["pageNumber"])
}
};
var apicall = new GetOrdersCall(context)
{
ApiRequest = request,
OutputSelector =
new string[]
{
"OrderID", "Total", "PaidTime", "eBayPaymentStatus",
"PaymentMethod", "Title", "PageNumber", "PaginationResult.TotalNumberOfPages"
}
};
apicall.Execute();
var orders = apicall.ApiResponse.OrderArray;

Multiple complexFilter in Magento's api v2

Currently I’m having some difficulties with using new Magento's soap v2 from c# interface.
With php i was able to do something like this:
$params["created_at"]["from"] = date("Y-m-d H:i:s",Functions::convert_time($dataDa));
$params["created_at"]["to"] = date("Y-m-d H:i:s",Functions::convert_time($dataA));
MageInterface::getSingleton()->shipmentList($params);
In this mode i was able to find list of orders which were created from $dataDa to $dataA without problems. With c# however it seems that only the last one of the selectors work.
My code:
var cpf = new complexFilter[2];
cpf[0] = new complexFilter
{
key = "created_at",
value = new associativeEntity
{
key = "to",
value = uxDataA.DateTime.ToString("yy-MM-dd HH:mm:ss")
}
});
cpf[1] = new complexFilter
{
key = "created_at",
value = new associativeEntity
{
key = "from",
value = uxDataDa.DateTime.ToString("yy-MM-dd HH:mm:ss")
}
});
var filters = new filters();
filters.complex_filter = cpf;
var risultato = mage.salesOrderList(sessionKey, filters);
In this mode only created_at->from criteria is taken in consideration (it's like second complex filter override previous one with the same key). Ideas?
Thanks in advance.
This works for me :
private filters addFilter(filters filtresIn, string key, string op, string value)
{
filters filtres = filtresIn;
if (filtres == null)
filtres = new filters();
complexFilter compfiltres = new complexFilter();
compfiltres.key = key;
associativeEntity ass = new associativeEntity();
ass.key = op;
ass.value = value;
compfiltres.value = ass;
List<complexFilter> tmpLst;
if (filtres.complex_filter!=null)
tmpLst = filtres.complex_filter.ToList();
else tmpLst = new List<complexFilter>();
tmpLst.Add(compfiltres);
filtres.complex_filter = tmpLst.ToArray();
return filtres;
}
and call
{
Mage_Api_Model_Server_V2_HandlerPortTypeClient clientSoap = new Mage_Api_Model_Server_V2_HandlerPortTypeClient();
string sessionId = clientSoap.login(LOG, PASS);
filters filtres = new filters();
filtres = addFilter(filtres, "status", "eq", "processing");
filtres = addFilter(filtres, "created_at", "from", "2014-09-07 08:00:00");
filtres = addFilter(filtres, "created_at", "to", "2014-09-07 00:00:00");
salesOrderEntity[] lst = clientSoap.salesOrderList(sessionId, filtres);
}
Solved, there was a bug (or the feature?) in mage\sales\order\api\v2.php
See more info in this thread: http://www.magentocommerce.com/boards/viewthread/70368/

Categories

Resources