I'm using the azure search api trying to filter by a certain field value: businesstype = store. It always returns 3 stores, even though I should have thousands. I can't tell for sure what's inside the index. In the Azure search web portal I type businessType eq 'store' and it gives me two stores, then starts returning businesstype = restaurant. Not sure what is going on. We have other implementations in other projects where filters are working. Here's code that I'm executing as it is invoked by using ASP.NET Web API
var indexClient = new SearchIndexClient(GlobalSettings.SearchServiceName, $"businesses{GlobalSettings.Environment}", new SearchCredentials(GlobalSettings.SearchServiceAdminApiKey));
if (latitude == null && longitude == null)
{
//chicago
latitude = 41.8333925;
longitude = -88.0121478;
}
// get all attributes and camel case them
var attributes = typeof(BusinessSearchItem).GetProperties().Select(x => char.ToLowerInvariant(x.Name[0]) + x.Name.Substring(1)).ToList();
var parameters = new SearchParameters
{
Select = attributes,
QueryType = QueryType.Full,
Top = take,
Skip = skip,
IncludeTotalResultCount = true,
OrderBy = new List<string>() { $"geo.distance(location, geography'POINT({longitude} {latitude})')" }
};
// filters
string filter = "";
if (!string.IsNullOrEmpty(businessType))
{
switch (businessType.ToLower())
{
case "restaurant":
filter += "businessType eq 'Restaurant'";
break;
case "store":
filter += "businessType eq 'Store'";
break;
}// end switch on business type
}
parameters.Filter = filter;
try
{
// run the search
var results = indexClient.Documents.Search<BusinessSearchItem>(q, parameters);
Logger.Log.Info($"Search conducted. Query: {q} Business Type: {businessType} Lat: {latitude} Long: {longitude} User: {username}");
var businessDTOs = results.Results.Select(x => new BusinessDTO
{
.........
).ToList()
}).ToList();
the model BusinessSearchItem has a field BusinessType of string that has the attribute searchable. The skip is 0 and take 40.
The problem wasn't the search at all, it was that the data was not in the index
Related
I have a Controller class on which I execute a SOQL query to Custom Metadata Type records.
The SOQL query also contains a child relationship query (Master-Detail relationship).
I need to write a test with mock custom metadata records
#AuraEnabled(cacheable=true)
public static List<Response> getLeadMetadataValues() {
List<Lead_Business_Status__mdt> leadBusinessStatusList = [
SELECT Id, Label, DeveloperName, Index__c,
(SELECT Id, Label, DeveloperName, Reason_Status_Api_Name__c FROM Lead_Reason_Status__r)
FROM Lead_Business_Status__mdt ORDER BY Index__c ASC
];
List<Response> resList = new List<Response>();
if (Test.isRunningTest()) {
leadBusinessStatusList = new List<Lead_Business_Status__mdt>();
leadBusinessStatusList.add(createMock());
}
for (Lead_Business_Status__mdt bs : leadBusinessStatusList) {
Response res = new Response();
res.Id = bs.Id;
res.businessStatusLabel = bs.Label;
res.businessStatusDevName = bs.DeveloperName;
res.index = bs.Index__c;
for (Lead_Reason_Status__mdt rs : bs.Lead_Reason_Status__r) {
ReasonStatus rsObj = new ReasonStatus();
rsObj.Id = rs.Id;
rsObj.reasonStatusLabel = rs.Label;
rsObj.reasonStatusDevName = rs.DeveloperName;
rsObj.fieldApiName = rs.Reason_Status_Api_Name__c;
res.reasonStatusList.add(rsObj);
}
resList.add(res);
}
return resList;
}
I use Test.isRunningTest() to populate the leadBusinessStatusList with the mock data.
I am able to create a mock object for the Master record: Lead_Business_Status__mdt and Detail record: Lead_Reason_Status__mdt. However, I wasn't able to add the Detail record to the related list: Lead_Reason_Status__r
private static Lead_Business_Status__mdt createMock() {
String reasonStatusStr = '{"Label":"Transfer to Queue", "DeveloperName":"Transfer_to_Queue", "Reason_Status_Api_Name__c":"Transfer_to_Queue"}';
Lead_Reason_Status__mdt reasonStatusObj = (Lead_Reason_Status__mdt) System.JSON.deserialize(reasonStatusStr, Lead_Reason_Status__mdt.class);
System.debug('Lead_Reason_Status__mdt: ' + reasonStatusObj);
String businessStatusStr = '{"Label":"Wrong Lead", "DeveloperName":"Wrong_Lead", "Index__c":"1"}';
Lead_Business_Status__mdt businessStatusObj = (Lead_Business_Status__mdt) System.JSON.deserialize(businessStatusStr, Lead_Business_Status__mdt.class);
return businessStatusObj;
}
The test is covered except the inner for loop of the Lead_Reason_Status__mdt.
How can I create a mock object with populating the child relationship list?
Can you try use JSON.deserialize method to setup these metadata records.
List<Lead_Business_Status__mdt> leadBusinessStatusList = (List< Lead_Business_Status__mdt >) JSON.deserialize( '[{"Id": "xoid914011599", "Label": "test", "DeveloperName": "test","Reason_Status_Api_Name__c": "test"}, {"Id": "xoid9140115992","Label":"test2","DeveloperName": "test2","Reason_Status_Api_Name__c": "test2"}]', List<Lead_Business_Status__mdt>.class );
I have SSRS report with parameters under SQL Reporting service 2012 standard edition. I like to export to excel and send as an attachment in the email to different receipt and receipt comes from some SQL query that means it is dynamic.
Data-driven subscription can do this but I have SQL Server 2012 Standard edition which does not support data-driven subscription and I can not upgrade, so I am looking for any code which can do the similar job like a data-driven subscription.
I found this link which has the solution to my issue.
http://jaliyaudagedara.blogspot.com/2012/10/creating-data-driven-subscription.html
when I try this code under visual studio 2015 "Class Library" project by adding service reference "http://mylocalserver:81/reportserver/ReportService2010.asmx" I am getting an error on this line of code.
ReportingService2010SoapClient rs= new ReportingService2010SoapClient();
Additional information about the error: Could not find default endpoint element that references contract 'ReportService2010.ReportingService2010Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
After spending enough time to make it work with "Class Library" project, I decided to do the code under web service project by adding the web service reference. with some trial and error finally, I got the working code here under web service project. below code works on my local machine which has Sql server 2012 enterprise edition but it gives me the same error saying "Data-driven subscriptions to reports" is not supported in this edition of Reporting Services" on my company server which has SQL server 2012 standard edition.
public void DoWork()
{
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = CredentialCache.DefaultCredentials;
// rs.Url = "http://mylocalserver:81/reportserver/ReportService2010.asmx";
rs.Url = "http://companyserver/reportserver/ReportService2010.asmx";
var reportPath = "/CYTYC Reports/";
string report = $"{reportPath}AllContactCIPPointsReport";
string description = "Programmatic Data Driven Subscription \"Report Server Email\" ";
//set extension as Windows File Share
ExtensionSettings settings = new ExtensionSettings();
settings.Extension = "Report Server Email";
// Set the extension parameter values.
var extensionParams = new ParameterValueOrFieldReference[8];
// var to = new ParameterFieldReference { ParameterName = "TO", FieldAlias = "PARAMS" }; // Data-driven.
var to = new ParameterValue { Name = "TO", Value = "example#gmail.com" }; // Data-driven.
extensionParams[0] = to;
var replyTo = new ParameterValue { Name = "ReplyTo", Value = "example#gmail.com" };
extensionParams[1] = replyTo;
var includeReport = new ParameterValue { Name = "IncludeReport", Value = "False" };
extensionParams[2] = includeReport;
var renderFormat = new ParameterValue { Name = "RenderFormat", Value = "HTML4.0" };
extensionParams[3] = renderFormat;
var priority = new ParameterValue { Name = "Priority", Value = "NORMAL" };
extensionParams[4] = priority;
var subject = new ParameterValue { Name = "Subject", Value = "Subsribed Report" };
extensionParams[5] = subject;
var comment = new ParameterValue { Name = "Comment", Value = "Here is the link to your report." };
extensionParams[6] = comment;
var includeLink = new ParameterValue { Name = "IncludeLink", Value = "True" };
extensionParams[7] = includeLink;
settings.ParameterValues = extensionParams;
// Create the data source for the delivery query.
var delivery = new DataSource { Name = "" };
var dataSourceDefinition = new DataSourceDefinition
{
ConnectString = "Data Source=CYTYC-LIVE;Initial Catalog=yourdatabasename",
CredentialRetrieval = CredentialRetrievalEnum.Store,
Enabled = true,
EnabledSpecified = true,
Extension = "SQL",
ImpersonateUserSpecified = false,
UserName = "username",
Password = "password"
};
delivery.Item = dataSourceDefinition;
// Create the data set for the delivery query.
var dataSetDefinition = new DataSetDefinition
{
AccentSensitivitySpecified = false,
CaseSensitivitySpecified = false,
KanatypeSensitivitySpecified = false,
WidthSensitivitySpecified = false
};
var queryDefinition = new QueryDefinition
{
CommandText = #"Your select * from Query",
CommandType = "Text",
Timeout = 45,
TimeoutSpecified = true
};
dataSetDefinition.Query = queryDefinition;
var results = new DataSetDefinition();
var oServerInfoHeader = new ServerInfoHeader();
var oTrustedUserHeader = new TrustedUserHeader();
bool changed;
string[] paramNames;
try
{
results = rs.PrepareQuery(delivery, dataSetDefinition, out changed, out paramNames);//.PrepareQuery(oTrustedUserHeader, delivery, dataSetDefinition, out results, out changed,out paramNames);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var dataRetrieval = new DataRetrievalPlan { DataSet = results, Item = dataSourceDefinition };
// Set the event type and match data for the delivery.
const string eventType = "TimedSubscription";
const string matchData = "<ScheduleDefinition><StartDateTime>2018-06-01T14:00:00-07:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Monday>True</Monday><Tuesday>True</Tuesday><Wednesday>True</Wednesday><Thursday>True</Thursday><Friday>True</Friday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>";
//const string eventType = "SnapshotUpdated";
//const string matchData = null;
//// Set the report parameter values.
//var parameters = new ParameterValueOrFieldReference[1];
//// i am retrieving value EMAIL from database and I am passing that value as my report parameter value
//var reportparam = new ParameterFieldReference { ParameterName = "yourreportparametername", FieldAlias = "PARAMS" }; // Data-driven.
//parameters[0] = reportparam;
var parameters = new ParameterValue[1];
var reportparam = new ParameterValue {Name = "yourreportparametername", Value = "yourreportparametervalue"};
parameters[0] = reportparam;
string subscriptionId = "";
try
{
subscriptionId = rs.CreateDataDrivenSubscription(report, settings, dataRetrieval, description, eventType, matchData, parameters);
//(oTrustedUserHeader, report, settings, dataRetrieval,description, eventType, matchData, parameters,out subscriptionId);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(ex.Detail.InnerText.ToString(CultureInfo.InvariantCulture));
}
}
You don't say why you need the Data Driven subscriptions - a regular SSRS subscription can e-mail an Excel report with set or default parameters.
There aren't any third party tools that I know of that emulates the Data Driven subscriptions but there have been some users who have created their own.
If you just want to trigger a subscription based on criteria, you could just use an SSIS job to run the query to determine whether to send or not and trigger the subscription if so.
Something like Data Driven Subscriptions SSRS Standard Edition 2008
If you need something more complicated (like varying TO/CC recipients, changing parameter values...), you'll need to do a bit more programming. Here's a couple things to get started with the theory and code:
https://www.mssqltips.com/sqlservertip/4249/simulate-reporting-services-data-driven-subscriptions-on-unsupported-editions/
http://www.sqlservercentral.com/articles/Reporting+Services+(SSRS)/163119/
I am using mongodb and node.js. In my database i have 6 fields that is
bid
color (Array)
size (Array)
cat_id
sub_cat_id
All is working fine. Now i want to add filter in my code. In filter area i have add this all fields. user select multiple colors and sizes so it will come in Array format but most of the time user will not select color option or size option at that time field values comes blank so my filter will not take any result from database. so i want to remove color or size field if value is empty during search. I have tried below code but its not working.how i do this.
var catId = new Array();
var sort = saveFilterSort.sort;
var filter = req.body;
if(req.body.catId){
catId.push("category_id:"+req.body.catId);
}
if(req.body.subcatid){
catId.push("sub_category_id:"+req.body.subcatid);
}
if(req.body.minprice){
catId.push("price:{$gt:"+req.body.minprice+"}");
}
if(req.body.maxprice){
catId.push("price:{$lt:"+req.body.maxprice+"}");
}
if(req.body.color){
catId.push("color:{$in:"+req.body.color+"}");
}
if(req.body.size){
catId.push("attribute:{$in:"+req.body.size+"}");
}
var finalCat = catId.join(',');
console.log(finalCat);
console.log(catId);
if((filter) && (sort)){
Product.find(
{
brand_id:bid, finalCat
},
function(error,fetchallFeatProds)
{
console.log('#######################');
console.log(fetchallFeatProds);
console.log('#######################');
callback(error,fetchallFeatProds);
}).sort( {_id:-1,price:-1} );
This code is not working. Please help me.
Mongoose find prototype handle json and not string
var query = {brand_id:bid};
var sort = saveFilterSort.sort;
var filter = req.body;
if(req.body.catId){
query.category_id = req.body.catId;
}
if(req.body.subcatid){
query.sub_category_id = req.body.subcatid;
}
if(req.body.minprice){
query.price = {$gt:req.body.minprice};
}
if(req.body.maxprice){
query.price = {$lt:req.body.maxprice};
}
if(req.body.color){
query.color = {$in:req.body.color};
}
if(req.body.size){
query.attribute = {$in:req.body.size};
}
if((filter) && (sort)){
Product.find(query, ...
Want to retrieve below values from array object not other details, but getting whole data like events, listeners, etc.
2014-10-01: 02014-10-02: 02014-10-06: 42014-10-08: 50.2857142857142852014-10-09: 42014-10-10: 32014-10-13: 32014-10-14: 2.52014-10-15: 52014-10-16: 02014-10-20: 32014-10-21: 12014-10-27: 32014-10-28: 6.7777777777777782014-10-29: 12014-10-31: 0.66666666666666662014-11-03: 42014-11-04: 19.252014-11-05: 33.62014-11-06: 12014-11-07: 32014-11-10: 32014-11-11: 3.6666666666666665
Below is my some of the code which generate this object, any help on this please..
var daysOfMonth = new Ext.util.HashMap();
//console.log("startdate", this.startDate);
//console.log("enddate", this.endDate);
start = new Date(this.startDate);
end = new Date(this.endDate);
for (start; start <= end; start.setDate(start.getDate() + 1)) {
daysOfMonth.add(new Date(start), null);
}
//daysOfMonth = Ext.Array.flatten(daysOfMonth);
console.log("days of month", daysOfMonth);
var userstory_cycle_times_by_date = this._getCycleTimes(userstory_snaps_by_date);
var storydaysOfMonth = Ext.Object.merge(daysOfMonth, userstory_cycle_times_by_date);
//console.log("days of month", daysOfMonth);
var defect_cycle_times_by_date = this._getCycleTimes(defect_snaps_by_date);
var defectdaysOfMonth = Ext.Object.merge(daysOfMonth, defect_cycle_times_by_date);
You can get an object of all the key/value pairs like so:
_.reduce(daysOfMonth.getKeys(), function(result, key) {
result[key] = daysOfMonth.get(key);
return result;
}, {});
I'm curious why you're using a HashMap to begin with rather than just a regular plain old javascript object literal?
I have build some dropdown lists using the LINK to Objects method and #html.dropdownlist Webmatrix helper. This works fine.
I want to know how to pass / store the selected value in my database table.
Build of items list in code section
var titlesData = db.Query("SELECT TitleId, Name FROM Titles ORDER BY Name");
titlesListItems = titlesData.Select(i => new SelectListItem {
Value = i.TitleId.ToString(),
Text = i.Name,
Selected = i.TitleId == providerData.TitleId ? true : false
});
HTML markup section:
#Html.DropDownList("titlesCombo","-- Veuillez sélectionner -- ",titlesListItems)
Database update command (see the ???):
db.Execute("UPDATE Providers SET TitleId=#0 WHERE ProviderId=#1",???,providerId)
The method I used for now is to create another variable:
var titleId = "";
if (!IsPost) {
titleId = providerData.TitleId.ToString(); //providerData stores the SQL query result
}
if (IsPost) {
var titleId = Request.Form[TitleID]
db.Execute("UPDATE Providers SET TitleId=#0 WHERE ProviderId=#1",titleId,providerId)
}
Unfortunately, data doesn't get updated
From what I can see, you haven't referenced rightly the DropDownList helper in your code.
Try with the following code:
var titleId = "";
if (!IsPost) {
titleId = providerData.TitleId.ToString();
}
if (IsPost) {
titleId = Request.Form["titlesCombo"];
db.Execute("UPDATE Providers SET TitleId=#0 WHERE ProviderId=#1",titleId,providerId);
}