Convert string array to another type - c#

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
};

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))
)
);

Converting 1000s ExpandoOject / dynamic to static type takes forever

I am trying to convert a list of 1000s dynamic (that I get from CsvHelper reading csv file) into static type but its taking forever.
Here's code:
dynamic object
MyObj {
id =1, prop1=1,prop2=2,prop3=3...
}
result
PObj1 { oid = 1 , name = "Property 1", value = "1" }
PObj2 { oid = 1 , name = "Property 2", value = "2" }
PObj3 { oid = 1 , name = "Property 3", value = "3" }
Code to convert
var imp = rows.SelectMany(x => map.Keys.ToList().Select(k => new PObj
{
OID = (((IDictionary<string, object>)x)["oid"] ?? "").ToString(),
Name = k,
Value = ToDate((((IDictionary<string, object>)x)[map[k]] ?? "").ToString())
}).ToList()).ToList();
map contains list of properties about 40-50
map<string,string>{
{"Property 1","prop1"},
{"Property 1","prop2"},
{"Property 1","prop3"}
...
}
ToDate function
private DateTime? ToDate(string strDate)
{
strDate = strDate.Split(' ')[0];
strDate = strDate.Replace('-', '/').Replace('.', '/');
DateTime? dt = null;
try
{
dt = DateTime.ParseExact(strDate, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
} catch { }
return dt;
}
map can contain any number of peroperties hence expandoObject will have dynamic number of properties.
Is there any way I can improve the performance?
The reason I need to do this conversion is because I need to than send this as table to a stored procedure therefore converting expandoObject straight into table creates issue if number properties in object changes as this mean number of column will also change in table.
I am open to other solutions as well if works in above situation.
seems like it was my pc (running windows on mac). Same code now works fine
rows.ToList().ForEach(x => imps.AddRange(map.Keys.Select(k => new ImportMilestone
{
JVSiteID = (((IDictionary<string, object>)x)[siteid] ?? "").ToString(),
Milestone = k,
MilestoneValue = ToDate((((IDictionary<string, object>)x)[map[k]] ?? "").ToString())
}).ToList()));

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 to add brand to existing eBay item?

In my application I would like add Brand and MPN to existing eBay item via API on C#, so, I run code:
string eCommerceID = (dr["eCommerceID"] ?? "").ToString().Trim();
string upc = (dr["UPC"] ?? "").ToString().Trim();
string manufacturerName = (dr["ManufacturerName"] ?? "").ToString().Trim();
string brandMPN = (dr["BrandMPN"] ?? "").ToString().Trim();
ReviseItemRequestType reviseItemRequestType = new ReviseItemRequestType();
reviseItemRequestType.Version = version;
reviseItemRequestType.Item = new ItemType();
reviseItemRequestType.Item.ItemID = eCommerceID;
reviseItemRequestType.Item.ProductListingDetails = new ProductListingDetailsType();
reviseItemRequestType.Item.ProductListingDetails.UPC = upc;
reviseItemRequestType.Item.ProductListingDetails.BrandMPN = new BrandMPNType();
reviseItemRequestType.Item.ProductListingDetails.BrandMPN.Brand = manufacturerName;
reviseItemRequestType.Item.ProductListingDetails.BrandMPN.MPN = brandMPN;
ReviseItemResponseType reviseItemResponseType = ebayService.ReviseItem(reviseItemRequestType);
but when I execute this code, eBay returns error:
"The item specific Brand is missing. Add Brand to this listing, enter a valid value, and then try again."
What I'm doing wrong?
Appreciate any help. Thanks.
Error:
As the error messages says:
The item specific Brand is missing
Don't use the Item.ProductListingDetails.BrandMPN in your request. Instead you will need to create two Item Specifics called Band and MPN.
<ItemSpecifics>
<NameValueList>
<Name>Brand</Name>
<Value>[BRAND VALUE]</Value>
</NameValueList>
<NameValueList>
<Name>MPN</Name>
<Value>[MPN VALUE]</Value>
</NameValueList>
</ItemSpecifics>
Here is copy paste code snippet of the C# solution.
ItemType itemType = new ItemType(); // = class eBay.Service.Core.Soap.ItemType
Int32 condCodeAsInt = 1000; // upto you to derrive this from your use case.
String myBrandValue = "Some BRAND";
String myMpnValue = "some MPN";
String myUpcValue = "Does not apply";
....
//if condition is "New" or "New with Details" then we need to set extra REQUIRED fields
if (condCodeAsInt == 1000 || condCodeAsInt == 1500)
{
//if it is "new" then remove inputted desc text completely REQUIRED
if (condCodeAsInt == 1000)
{
itemType.ConditionDescription = "";
}
// set UPC value HERE, not in ItemSpecifics.
ProductListingDetailsType pldt = new ProductListingDetailsType();
pldt.UPC = myUpcValue;
itemType.ProductListingDetails = pldt;
//init Item specifics ( and set BRAND and MPN )
itemType.ItemSpecifics = new NameValueListTypeCollection();
//brand
NameValueListType nvBrand = new NameValueListType();
nvBrand.Name = "Brand";
StringCollection brandStringCol = new StringCollection();
brandStringCol.Add(myBrandValue);
nvBrand.Value = brandStringCol;
itemType.ItemSpecifics.Add(nvBrand);
//MPN
NameValueListType nvMpn = new NameValueListType();
nvMpn.Name = "MPN";
StringCollection mpnStringCol = new StringCollection();
mpnStringCol.Add(myMpnValue);
nvMpn.Value = mpnStringCol;
itemType.ItemSpecifics.Add(nvMpn);
}

Using List<int> in Url.Action Method

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.

Categories