Using List<int> in Url.Action Method - c#

i am writing code for search page and i have to pass some filters to the action and depending on those input I have to generate hyper links, hence i am using Url.Action function to generate links.
below is my code
#Url.Action("Index","Search",new SkillKindleWeb.ViewModels.Search.SearchRawInput()
{
CategoryIds = Model.Request.CategoryIds,
SubCategoryIds = Model.Request.SubCategoryIds,
StartDate = Model.Request.StartDate,
EndDate = Model.Request.EndDate,
StartPrice = Model.Request.StartPrice,
LocationGroupIds = Model.Request.LocationGroupIds,
LocationIds = Model.Request.LocationIds,
EndPrice = Model.Request.EndPrice,
City = Model.Request.City,
PageNo = 1,
SearchQuery = Model.Request.SearchQuery,
Segment1 = Model.Request.Segment1,
Segment2 = Model.Request.Segment2,
TargetAge = Model.Request.TargetAge
})
and it is generating url like this
http://someDomain.com/ncr/classes?CategoryIds=System.Collections.Generic.List%601%5BSystem.Int32%5D&StartDate=03%2F30%2F2013%2000%3A00%3A00&StartPrice=0&EndPrice=140000&PageNo=2
My expected Url was
http://SomeDomain.com/ncr/classes?CategoryIds=9&StartDate=3/30/2013&StartPrice=0&EndPrice=140000

What about converting it to string representation yourself like that:
#Url.Action("Index","Search",new SkillKindleWeb.ViewModels.Search.SearchRawInput()
{
CategoryIds = string.Join(",", Model.Request.CategoryIds),
SubCategoryIds = string.Join(",", Model.Request.SubCategoryIds),
StartDate = Model.Request.StartDate.ToShortDateString(),
EndDate = Model.Request.EndDate.ToShortDateString(),
StartPrice = Model.Request.StartPrice,
LocationGroupIds = Model.Request.LocationGroupIds,
LocationIds = Model.Request.LocationIds,
EndPrice = Model.Request.EndPrice,
City = Model.Request.City,
PageNo = 1,
SearchQuery = Model.Request.SearchQuery,
Segment1 = Model.Request.Segment1,
Segment2 = Model.Request.Segment2,
TargetAge = Model.Request.TargetAge
})
That is what a viewmodel should be for. That you convert and format all the values you need in the way the view expects it.
Notice that I added a ToShortDateString() to your dates as well, since it seems you are not interested in the time part.

Related

Can not combine 2 date range queries in Elasticsearch object syntax

I want to search a document in a way that I filter it by exact values for the "from" and "to" fields. I use DateRangeQuery objects that I pass to the bool query instance.
This filter works fine when its only one date being filtered, but when both are active it returns no documents at all. Code bellow
DateRangeQuery fromDateRangeQuery = new DateRangeQuery()
{
Name = "from_query",
Field = "from",
GreaterThanOrEqualTo = dateFrom,
LessThanOrEqualTo = dateFrom,
};
queryContainers.Add(fromDateRangeQuery);
DateRangeQuery ToDateRangeQuery = new DateRangeQuery()
{
Name = "to_query",
Field = "to",
GreaterThanOrEqualTo = dateTo,
LessThanOrEqualTo = dateTo,
};
queryContainers.Add(ToDateRangeQuery);
//more terms filters not related to the 2 fields
var searchRequest = new SearchRequest("0___aggregate_");
searchRequest.SearchType = SearchType.QueryThenFetch;
searchRequest.From = 0;
searchRequest.Size = 10000;
searchRequest.Query = boolQuery;
var searchResponse = Get().SearchAsync<AggregationHolder>(searchRequest);
searchResponse.Wait(60000);
var status = searchResponse.Result;
Both dateFrom and dateTo are regular date time object. What am I doing wrong, why cant I combine these 2 filters?
Maybe, the problem is your date format. Could you please try like below?
ElasticClient elasticClient = new ElasticClient(new ConnectionSettings(
new Uri(connString))
.RequestTimeout(TimeSpan.FromMinutes(5))
.DefaultIndex(defaultIndexName)
);
DateRangeQuery queryFrom = new DateRangeQuery()
{
Name = "from_query",
Field = "from",
GreaterThanOrEqualTo = "05/12/2020 01:03:15",
LessThanOrEqualTo = "05/12/2020 01:03:16",
Format = "dd/MM/yyyy HH:mm:ss"
};
DateRangeQuery queryTo = new DateRangeQuery()
{
Name = "to_query",
Field = "to",
GreaterThanOrEqualTo = "05/12/2020 11:20:32",
LessThanOrEqualTo = "05/12/2020 11:20:33",
Format = "dd/MM/yyyy HH:mm:ss"
};
QueryContainer queryMain = queryFrom & queryTo;
ISearchResponse<AggregationHolder> searchResponse = elasticClient.Search<AggregationHolder>(s => s
.RequestConfiguration(r => r.DisableDirectStreaming())
.From(0)
.Size(100)
.Query(q2 => q2
.Bool(b => b
.Should(queryMain))
)
);

How to compare date in linq c#

i have 'created date' and 'closed date' in my file and i'm converting it in json so i have that dates in json.
in my method i have two parameter like from date and to date and i want to count particular column data of my file between from date and to date.so how can we write code to fetch it using linq.
i tried this...
public JsonResult StatusDerails(DateTime from,DateTime to)
{
string csvurl = WebConfigurationManager.AppSettings["csvfileurl"];
var lines = System.IO.File.ReadAllLines(csvurl).Skip(1);
List<Product> prdt = new List<Product>();
foreach (string line in lines)
{
Product c1 = new Product();
var split = line.Split(',');
c1.ID = Int32.Parse(split[0]);
c1.Area_Path = split[1];
c1.IterationPath = split[2];
c1.State = split[3];
c1.Reason = split[4];
c1.Priority = Int32.Parse(split[5]);
c1.Severity = split[6];
c1.Tags = split[7];
c1.Title = split[8];
c1.CreatedDate = split[9];
c1.CreatedBy = split[10];
c1.ResolvedDate = split[11];
c1.ResolvedBy = split[12];
c1.ClosedDate = split[13];
c1.AssignedTo = split[14];
prdt.Add(c1);
}
//var list = prdt.GroupBy(a=>a.AreaPath).Select(a=>new UIproduct() {
var productName = prdt.Select(a => a.Area_Path).Distinct();
List<StatusDetail> statusdetail = new List<StatusDetail>();
foreach (var Name in productName)
{
StatusDetail sd = new StatusDetail();
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date.ToString() && a.ClosedDate <= to.Date.ToShortDateString
}
return Json(statusdetail, JsonRequestBehavior.AllowGet);
}
The comparison of DateTime as string will not be a good option and that wont gives you the exact result, So I recommend you to change the type of CreatedDate and ClosedDate to DateTime. and compare two DateTime values in linq. I think instead of splitting json for creating object of certain types you can use json converters.
Fix for your scenario:
c1.CreatedDate = DateTime.Parse(split[9]);
c1.ClosedDate = DateTime.Parse(split[13]);
Don't forget to change the type in the class, Now its fine to use the linq as like the following:
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date && a.ClosedDate <= to.Date);

How can i do recursive linq function?

I want to make a menu, and this is my code. I need recursive function.
var newTopMenu = new TopMenuVm
{
TopMenus = (from amp in allMasterPages
orderby amp.DisplayOrder
select new TopMenuVm
{
DisplayOrder = amp.DisplayOrder,
Url = string.IsNullOrEmpty(amp.Url) ? GenerateUrl(amp.Page1.OrderBy(x => x.DisplayOrder).FirstOrDefault()) : amp.Url,
PageId = amp.PageId,
PageTitle = amp.PageTitle,
TopMenus = (from submenu in amp.Page1
orderby amp.DisplayOrder
select new TopMenuVm
{
DisplayOrder = submenu.DisplayOrder,
PageTitle = submenu.PageTitle,
PageId = submenu.PageId,
Url = string.IsNullOrEmpty(submenu.Url) ? GenerateUrl(submenu) : submenu.Url,
}).ToList()//Here is go on infinite...,
}).ToList()
};
How can i do that with linq, please help...
Is something like this what you are looking for?
// allMasterPages is type List<MyPage> - change to whatever it really is
Func<List<MyPage>, List<TopMenuVM>> funcTopMenuVM = null;
funcTopMenuVM = ((pages) => {
return
(from amp in pages
orderby amp.DisplayOrder
select new TopMenuVM()
{
DisplayOrder = amp.DisplayOrder,
Url = string.IsNullOrEmpty(amp.Url) ? GenerateUrl(amp.Page1.OrderBy(x => x.DisplayOrder).FirstOrDefault()) : amp.Url,
PageId = amp.PageId,
PageTitle = amp.PageTitle,
TopMenus = funcTopMenuVM(amp.Page1)
}).ToList();
});
var newTopMenu = new TopMenuVM()
{
TopMenus = funcTopMenuVM(allMasterPages)
};
Of course, it doesn't have to be a Func<>, it could just be a regular method that returns a List<TopMenuVM> and takes a List<MyPage> (or whatever allMasterPages is).

How do i get data by calling a method in Entity Framework

I want to get ResourceNames on the base of Id in EntityFramework but it is giving error: "LINQ to Entities does not recognize the method 'System.String GetResourceNameById(Int32)' method, and this method cannot be translated into a store expression."
Following ismy code.
public string GetResourceNameById(int Id)
{
return _DBContex.Employees.Where(x => x.Id == Id).FirstOrDefault().FirstName;
}
public CygnusInternalResponseViewModel GetAllTimeEntriesForGrid(int start = 0, int perPage = -1, string sortColumn = "", string sortDirection = "")
{
List<TimeEntryViewModel> te = new List<TimeEntryViewModel>();
te = (from jb in _DBContex.TimeEntries
select new TimeEntryViewModel
{
Id = jb.Id,
ResourceId = (int)jb.ResourceId,
TicketId = (int)jb.TicketId,
WorkType = (WorkTypeCatalog)jb.WorkType,
HoursWorked = (float)jb.HoursWorked,
Status = (TimeEntryStatusCatalog)jb.Status,
Role = (RoleCatalog)jb.Role,
StartTime = (TimeSpan)jb.StartTime,
EndTime = (TimeSpan)jb.EndTime,
SummaryNotes = jb.SummaryNotes,
InternalNotes = jb.InternalNotes,
Contract = (DateTime)jb.Contract,
Date = (DateTime)jb.Date,
ResourceName = GetResourceNameById((int)jb.ResourceId) // ERRORR Line
}).ToList();
You might need to create in memory representation of your database table.
public CygnusInternalResponseViewModel GetAllTimeEntriesForGrid(int start = 0, int perPage = -1, string sortColumn = "", string sortDirection = "")
{
List<TimeEntryViewModel> te = new List<TimeEntryViewModel>();
var query=_DBContex.TimeEntries.ToList();//create in-memory representation
te = (from jb in query
select new TimeEntryViewModel
{
Id = jb.Id,
ResourceId = (int)jb.ResourceId,
TicketId = (int)jb.TicketId,
WorkType = (WorkTypeCatalog)jb.WorkType,
HoursWorked = (float)jb.HoursWorked,
Status = (TimeEntryStatusCatalog)jb.Status,
Role = (RoleCatalog)jb.Role,
StartTime = (TimeSpan)jb.StartTime,
EndTime = (TimeSpan)jb.EndTime,
SummaryNotes = jb.SummaryNotes,
InternalNotes = jb.InternalNotes,
Contract = (DateTime)jb.Contract,
Date = (DateTime)jb.Date,
ResourceName = GetResourceNameById((int)jb.ResourceId)
}).ToList();
te = (from jb in _DBContex.TimeEntries
select new TimeEntryViewModel
{
Id = jb.Id,
ResourceId = (int)jb.ResourceId,
TicketId = (int)jb.TicketId,
WorkType = (WorkTypeCatalog)jb.WorkType,
HoursWorked = (float)jb.HoursWorked,
Status = (TimeEntryStatusCatalog)jb.Status,
Role = (RoleCatalog)jb.Role,
StartTime = (TimeSpan)jb.StartTime,
EndTime = (TimeSpan)jb.EndTime,
SummaryNotes = jb.SummaryNotes,
InternalNotes = jb.InternalNotes,
Contract = (DateTime)jb.Contract,
Date = (DateTime)jb.Date
}).ToList();
te.Foreach(t=>t.ResourceName = GetResourceNameById((int)t.ResourceId);
First you get the records then you set the ResourceName
You can call ToList() method before your SELECT and then call your function.

Convert string array to another type

I'm trying to convert the string separated by commas which has 7 values of:
2014-21-2,1207.81,1209.87,1202.84,1203.79,1862300,1203.79
To another model which is:
return lines[1].Split(',').Select(i => new StockModel
{
StockDate = DateTime.ParseExact(i.ToString(), "yyyy-MM-dd", null),
StockOpen = float.Parse(i.ToString()),
StockHigh = float.Parse(i.ToString()),
StockLow = float.Parse(i.ToString()),
StockClose = float.Parse(i.ToString()),
StockVolume = Convert.ToInt32(i.ToString()),
StockAdjustedClose = float.Parse(i.ToString()),
StockSymbol = stockSymbol
}).SingleOrDefault();
However I get errors such as: Additional information: Input string was not in a correct format. http://s17.postimg.org/ro4k3tzct/Screenshot_1.png
If I do it manually like: DateTime date = DateTime.Parse(lines[1].Split(',')[0]), it works fine.
Whatever value I'm trying to put into the new Model, I get errors such as this one.
OK, I see the problem. You shouldn't use Select here. Try following instead:
var i = lines[1].Split(',');
return new StockModel()
{
StockDate = DateTime.ParseExact(i[0].ToString(), "yyyy-MM-dd", null),
StockOpen = float.Parse(i[1].ToString()),
StockHigh = float.Parse(i[2].ToString()),
StockLow = float.Parse(i[3].ToString()),
StockClose = float.Parse(i[4].ToString()),
StockVolume = Convert.ToInt32(i[5].ToString()),
StockAdjustedClose = float.Parse(i[6].ToString()),
StockSymbol = stockSymbol
};

Categories