Conditional to limit .Net webservice results - asp.net

I'm not sure if this is the right way but I have a web service that returns json. Now I wanted to set a conditional to omit rows returned that have a value of false in cell appearInShowcase. Most of the code is pretty straight forward what it does but the cell that has a true false value is appearInShowcase which is in a table photo. In the ms sql database the appearInShowcase is of type ntext.
public List<wsGalleryPhotos> GetGalleryPhotos(int collectionID)
{
photoDataContext dc = new photoDataContext();
List<wsGalleryPhotos> results = new List<wsGalleryPhotos>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
foreach (photo photo in dc.photos.Where(s => s.collectionID == collectionID))
{
if(photo.appearInShowcase == "true")
{
results.Add(new wsGalleryPhotos()
{
photoID = photo.photoID,
collectionID = Convert.ToInt32(photo.collectionID),
name = photo.name,
description = photo.description,
filepath = photo.filepath,
thumbnail = photo.thumbnail
});
}
}
return results;
}

if you want to add a condition, you should do it like this:
public List<wsGalleryPhotos> GetGalleryPhotos(int collectionID)
{
photoDataContext dc = new photoDataContext();
List<wsGalleryPhotos> results = new List<wsGalleryPhotos>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
results = dc.photos.Where(s => s.collectionID == collectionID && s.appearInShowcase == "true")
.Select(s => new wsGalleryPhotos
{
photoID = s.photoID,
collectionID = collectionID,
name = s.name,
description = s.description,
filepath = s.filepath,
thumbnail = s.thumbnail
}).ToList();
return results;
}

Related

ElasticSearch 7 nest 7 return attribute from result all result

I'm using ElarsticSearch 7.7 & NEST 7.7 and on my web page, I'm getting 9 search result documents per page. Even I'm showing the first 9 results on the page, I need to return some property values from all the results for side filtration on the web page.
Eg: if I'm searching "LapTop", my page will show 9 results on the first page. Also, I need to show all the "Manufactures" from all the search results. Not only manufacturers in the first-page result. Then customers can filter by manufacture not only display on the first page.
I have tried GlobalAggregation but it returns categories and manufactures only items in selected page.
public SearchResult Search(SearchType searchType, string searchQuery, int storeId, int pageNumber = 1, int pageSize = 12, IList<SearchFilter> requestFilter = null, decimal? priceFrom = 0, decimal? priceTo = 100000000, string sortBy = null, int totalCount = 0)
{
var queryContainer = new QueryContainer();
var sorts = new List<ISort>();
sorts.Add(new FieldSort { Field = "_score", Order = SortOrder.Descending });
switch (sortBy)
{
case "z-a":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Descending });
break;
case "a-z":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Ascending });
break;
}
var aggrigations = new AggregationDictionary
{
{"average_per_child", new
AverageAggregation("average_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"max_per_child", new MaxAggregation("max_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"min_per_child", new MinAggregation("min_per_child", Field<ElasticIndexGroupProduct>(d => d.Price))},
{
"globle_filter_aggrigation", new GlobalAggregation("globle_filter_aggrigation")
{
Aggregations =new AggregationDictionary
{
{"category_flow", new TermsAggregation("category_flow"){Field = Field<ElasticIndexGroupProduct>(p => p.CategoryFlow)} },
{"manufacturers", new TermsAggregation("manufacturers"){Field = Field<ElasticIndexGroupProduct>(p => p.Manufacturer)} }
}
}
}
};
var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
{
Profile = true,
From = (pageNumber - 1) * pageSize,
Size = pageSize,
Version = true,
Sort = sorts,
//Scroll = Time.MinusOne,
Aggregations = aggrigations
};
var multiMatch = new QueryStringQuery
{
Query = searchQuery,
Fields = GetSearchFields(searchType),
Boost = 1.1,
Name = "named_query",
DefaultOperator = Operator.Or,
Analyzer = "standard",
QuoteAnalyzer = "keyword",
AllowLeadingWildcard = true,
MaximumDeterminizedStates = 2,
Escape = true,
FuzzyPrefixLength = 2,
FuzzyMaxExpansions = 3,
FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
Rewrite = MultiTermQueryRewrite.ConstantScore,
Fuzziness = Fuzziness.Auto,
TieBreaker = 1,
AnalyzeWildcard = true,
MinimumShouldMatch = 2,
QuoteFieldSuffix = "'",
Lenient = true,
AutoGenerateSynonymsPhraseQuery = false
};
searchRequest.Query = new BoolQuery
{
Must = new QueryContainer[] { multiMatch },
Filter = new QueryContainer[] { queryContainer }
};
var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
var categoryFlowsGlobe = new List<string>();
var allAggregations = searchResponse.Aggregations.Global("globle_filter_aggrigation");
var categories = allAggregations.Terms("category_flow");
foreach (var aggItem in categories.Buckets)
{
if (!categoryFlowsGlobe.Any(x => x == aggItem.Key))
{
categoryFlowsGlobe.Add(aggItem.Key);
}
}
}
This is the exact use case for Post filter - to run a search request that returns hits and aggregations, then to apply filtering to the hits after aggregations have been calculated.
For Manufacturers, these can be retrieved with a terms aggregation in the search request - you can adjust the size on the aggregation if you need to return all manufacturers, otherwise you might decide to return only the top x.

Amazon DynamoDBv2 QueryOperationConfig SelectValues.Count not working

I have this piece of code like this:
var options = new DynamoDBOperationConfig
{
ConditionalOperator = ConditionalOperatorValues.Or,
OverrideTableName = nameTable,
ConsistentRead = true
};
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count
};
result = context.FromQueryAsync<TEntity>(queryConfig, options).GetRemainingAsync().Result;
as per the documentation, it should return just the count of values that match the filter, at least, the piece of code in the SelectValues class says that
//
// Summary:
// An enumeration of all supported Select values for Query and Scan. Value of Count
// will force service to return the number of items, not the items themselves.
but result is always an empty list; how can i make the count work ?
If you are still looking for the answer, this is the solution:
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count,
ConsistentRead = true
};
var table = context.GetTargetTable<TEntity>();
var search = table.Query(queryConfig);
result = search.Count;
Having ConsistentRead set to true will cause it to give you real time updates when the table is updated.
It's not working on Document level...
You can try to do this in low level model.
int count = 0;
Dictionary<string, AttributeValue> lastKey = null;
do
{
var request = new QueryRequest
{
TableName = "tableNmae",
IndexName = "indexName",
KeyConditionExpression = "ID= :v_ID",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{
":v_ID",
new AttributeValue
{
N = "1"
}
}
},
ConsistentRead = false,
Select = Select.COUNT,
ExclusiveStartKey = lastKey
};
var respone = await tableClient.QueryAsync(request);
count += respone.Count;
lastKey = respone.LastEvaluatedKey;
} while (lastKey != null && lastKey.Count != 0);

Datatables Object Reference not set to instance of an object for one variable

This is my datatables serverside implementation. FilterInput contains 5 variables:
Level <- string
Message <- string
Exception <-string
StartDate <- DateTime
EndDate <- DateTime
For some reason when I run this code as it is, I will always get this error:
{System.NullReferenceException: Object reference not set to an
instance of an object.
This is referring to this line:
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
However, if I remove the search for FilterInput.Exception, everything runs fine again. I have tested it with input ("abc") or without input ("") and the results are the same. The other FilterInputs don't have the same error.
public JsonResult Search(SearchViewModels Input, EventLogsSearchViewModel FilterInput)
{
JsonResult result = new JsonResult(null);
try
{
var data = dbContext.EventLogs.ToList();
int totalRecords = data.Count;
var modelStructure = new Dictionary<int, string>();
modelStructure.Add(1, "Level");
modelStructure.Add(2, "TimeStamp");
modelStructure.Add(3, "LogEvent");
modelStructure.Add(4, "Message");
modelStructure.Add(5, "MessageTemplate");
modelStructure.Add(6, "Exception");
modelStructure.Add(7, "Properties");
var StartDate = FilterInput.StartDate != default(DateTime);
var EndDate = FilterInput.EndDate != default(DateTime);
if ((!string.IsNullOrEmpty(FilterInput.Level) && !string.IsNullOrWhiteSpace(FilterInput.Level)) ||
(!string.IsNullOrEmpty(FilterInput.Message) && !string.IsNullOrWhiteSpace(FilterInput.Message)) ||
(!string.IsNullOrEmpty(FilterInput.Exception) && !string.IsNullOrWhiteSpace(FilterInput.Exception)) ||
(StartDate && EndDate))
{
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
data = data.Where(u => u.TimeStamp >= FilterInput.StartDate && u.TimeStamp <= FilterInput.EndDate).ToList();
}
if (!(string.IsNullOrEmpty(Input.Order) && string.IsNullOrEmpty(Input.OrderDir)))
{
var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(Input.Order));
data = data.AsQueryable().OrderBy(columnName.Value + " " + Input.OrderDir).ToList();
}
int recFilter = data.Count;
data = data.Skip(Input.StartRec).Take(Input.PageSize).ToList();
var modifiedData = data.Select(u => new EventLogsListViewModel
{
Id = u.Id,
Message = u.Message,
MessageTemplate = u.MessageTemplate,
Level = u.Level,
TimeStamp = u.TimeStamp,
Exception = u.Exception,
Properties = u.Properties,
LogEvent = u.LogEvent
});
result = this.Json(new
{
draw = Convert.ToInt32(Input.Draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = modifiedData,
order = Input.Order,
orderdir = Input.OrderDir
});
}
catch (Exception e)
{
logger.LogError(e, LoggingGlobals.LoadingException);
}
return result;
}
EDIT: The exception still happens even when FilterInput.Exception is not null

Join two dynamic Linq in Asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'
To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

How to correctly return from stored procedure in Sql to model?

I need to return list of values from stored procedure to my model. How do I do it:
[HttpGet("{id}")]
public DataSource Get(int id)
{
DataSource ds = _dbContext.DataSources.Where(d => d.Id == id)
.Include(d => d.DataSourceParams)
.ThenInclude(p => p.SelectOptions).FirstOrDefault();
foreach(DataSourceParam p in ds.DataSourceParams)
{
if(p.TypeId == 5)
{
p.SelectOptions = _dbContext.SelectOptions.FromSql("Exec " + ds.DataBaseName + ".dbo." + "procGetTop50 " + ds.Id + ", 1").ToList();
}
}
return ds;
}
First, declare your procedure with parameters:
string sql = "myProcedure #param1, #param2";
Second, create parameters
var param1 = new SqlParameter { ParameterName = "param1", Value = param1Value};
var param2 = new SqlParameter { ParameterName = "param2", Value = param2Value };
Finally, exec the code:
info = this.DbContext.Database.SqlQuery<MyModel>(sql, param1, param2).FirstOrDefault();
This is it!
Just remember your model must match with the procedure columns. With means, if your procedure returns a column named 'MyProp' your model 'MyModel' must have a 'MyProp' property.

Resources