I want to get my linq query result back as json format. I have been searching for hours.
Here is my code :
public IEnumerable<callersW> GetAllCallersF()
{
testCDREntities1 context = this.CurrentDataSource;
var query = (
from oneCaller in CurrentDataSource.TestTables
select new
{
Created = oneCaller.Created,
Answered = oneCaller.Answered,
Destroyed = oneCaller.Destroyed,
CallerID = oneCaller.CallerId,
CalledID = oneCaller.CalledId,
DisconnectionCode = oneCaller.DisconnectionCode,
RTP_Caller_G107MOS = oneCaller.RTP_Caller_G107MOS,
RTP_Caller_LostPackets = oneCaller.RTP_Caller_LostPackets,
RTP_Caller_MaxRfc3550Jitter = oneCaller.RTP_Caller_MaxRfc3550Jitter,
RTP_Caller_MeanRfc3550Jitter = oneCaller.RTP_Caller_MeanRfc3550Jitter,
RTP_Called_G107MOS = oneCaller.RTP_Called_G107MOS,
RTP_Called_LostPackets = oneCaller.RTP_Called_LostPackets,
RTP_Called_MaxRfc3550Jitter = oneCaller.RTP_Called_MaxRfc3550Jitter,
RTP_Called_MeanRfc3550Jitter = oneCaller.RTP_Called_MeanRfc3550Jitter,
}).ToList()
.Select(x => new callersW
{
Created = Convert.ToDateTime(x.Created),
Answered = Convert.ToDateTime(x.Answered),
Destroyed = Convert.ToDateTime(x.Destroyed),
CallerID = x.CallerID,
CalledID = x.CalledID,
DisconnectionCode = Convert.ToInt32(x.DisconnectionCode),
RTP_Caller_G107MOS = Convert.ToDouble(x.RTP_Caller_G107MOS),
RTP_Caller_LostPackets = Convert.ToDouble(x.RTP_Caller_LostPackets),
RTP_Caller_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MaxRfc3550Jitter),
RTP_Caller_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MeanRfc3550Jitter),
RTP_Called_G107MOS = Convert.ToDouble(x.RTP_Called_G107MOS),
RTP_Called_LostPackets = Convert.ToDouble(x.RTP_Called_LostPackets),
RTP_Called_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MaxRfc3550Jitter),
RTP_Called_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MeanRfc3550Jitter)
}).ToList();
return query;
}
Can somebody help me with this ?
Add to your project JSON.NET and serialize object eg:
string json = JsonConvert.SerializeObject(query);
More examples here.
Related
I have the LINQ query with the simple select statement which maps the columns from a table to the custom entity.
I have quite a few fields so I'm trying to select one by one and leave one field out. This way seems pretty silly to me. There was an option such as not select in SQL, it should have a counterpart in the entity framework.
I don't want to select the image area in this query. Do I have to write such a long code for this?
var result = from ch in _tenantDbContext.CariHesap
where ch.KartTipi == cariHesapKartTip
select new CariHesap
{
Id = ch.Id,
HesapKodu = ch.HesapKodu,
Unvan = ch.Unvan,
Ad = ch.Ad,
Soyad = ch.Soyad,
AktifPasif = ch.AktifPasif,
KartTipi = ch.KartTipi,
IslemTipi = ch.IslemTipi,
BakGostSekli = ch.BakGostSekli,
DvzTL = ch.DvzTL,
DovizCinsi = ch.DovizCinsi,
KrediLimiti = ch.KrediLimiti,
DvzKrediLimiti = ch.DvzKrediLimiti,
BolgeKod = ch.BolgeKod,
OzelKod = ch.OzelKod,
GrupKod = ch.GrupKod,
TipKod = ch.TipKod,
MhsKod = ch.MhsKod,
MasrafMerkezi = ch.MasrafMerkezi,
VergiDairesi = ch.VergiDairesi,
HesapNo = ch.HesapNo,
FaturaChk = ch.FaturaChk,
IskontoOran = ch.IskontoOran,
OpsiyonGunu = ch.OpsiyonGunu,
OdemeGunu = ch.OdemeGunu,
OdemePlani = ch.OdemePlani,
KulSatisFiyat = ch.KulSatisFiyat,
CHKodu = ch.CHKodu,
KDVTevfikatUygula = ch.KDVTevfikatUygula,
KDVMuaf = ch.KDVMuaf,
KDVMuafAck = ch.KDVMuafAck,
FormBaBsUnvan = ch.FormBaBsUnvan,
SirketEMail = ch.SirketEMail,
SirketWebAdres = ch.SirketWebAdres,
SatIslemEMail = ch.SatIslemEMail,
SatAlmaIslemEMail = ch.SatAlmaIslemEMail,
FinIslemEMail = ch.FinIslemEMail,
UnvanFaturadan = ch.UnvanFaturadan,
EFatSenaryo = ch.EFatSenaryo,
EIrsSenaryo = ch.EIrsSenaryo,
EMMSenaryo = ch.EMMSenaryo,
EFatEtiket = ch.EFatEtiket,
EIrsEtiket = ch.EIrsEtiket,
MusBrmSubeTanim = ch.MusBrmSubeTanim,
MusBrmSubeDeger = ch.MusBrmSubeDeger,
MusCHKoduTanim = ch.MusCHKoduTanim,
MusCHKoduDeger = ch.MusCHKoduDeger,
LegalEntityID = ch.LegalEntityID,
LegalEntityName = ch.LegalEntityName,
EArsivTeslimSekli = ch.EArsivTeslimSekli,
EArsivTeslimEMail1 = ch.EArsivTeslimEMail1,
EArsivTeslimEMail2 = ch.EArsivTeslimEMail2,
EArsivTeslimEMail3 = ch.EArsivTeslimEMail3,
FaturaXSLT = ch.FaturaXSLT,
IrsaliyeXSLT = ch.IrsaliyeXSLT,
SGKChk = ch.SGKChk,
SGKFaturaTipi = ch.SGKFaturaTipi,
KamuChk = ch.KamuChk,
Kod1 = ch.Kod1,
Kod2 = ch.Kod2,
Kod3 = ch.Kod3,
Kod4 = ch.Kod4,
Kod5 = ch.Kod5,
Kod6 = ch.Kod6,
Kod7 = ch.Kod7,
Kod8 = ch.Kod8,
Kod9 = ch.Kod9,
Kod10 = ch.Kod10,
Kod11 = ch.Kod11,
Kod12 = ch.Kod12,
Kod13 = ch.Kod13,
Kod14 = ch.Kod14,
Kod15 = ch.Kod15,
Nesne1 = ch.Nesne1,
Nesne2 = ch.Nesne2,
};
I am consuming trade and quote data with BLPAPI in C#. When I process a LAST_TRADE_PRICE_TIME_TODAY_RT like this using //blp/mktdata service and processing the SUBCRIPTION_DATA event fine except for this message element:
{MarketDataEvents = {
RT_TIME_OF_TRADE = 2022-06-23
INDICATIVE_NEAR =
IMBALANCE_BUY =
IMBALANCE_SELL =
ORDER_IMB_BUY_VOLUME =
ORDER_IMB_SELL_VOLUME =
THEO_PRICE =
IMBALANCE_INDIC_RT =
PREV_CLOSE_VALUE_REALTIME = 11737.5
TRADING_DT_REALTIME = 2022-06-24
PREV_TRADING_DT_REALTIME = 2022-06-23
PX_ASK_LME_OFFICIAL_RT =
NUM_TRADES_RT = 0
PX_OFFICIAL_AUCTION_RT =
LAST_UPDATE_BID_RT = 2022-06-23
LAST_UPDATE_ASK_RT = 2022-06-23
OFFICIAL_AUCTION_VOLUME_RT =
IN_AUCTION_RT =
TURNOVER_TODAY_REALTIME =
OFFICIAL_OPEN_AUCTION_PRICE_RT =
OFFICIAL_OPEN_AUCTION_VOLUME_RT =
OFFICIAL_CLOSE_AUCTION_PRICE_RT =
OFFICIAL_CLOSE_AUCTION_VOLUME_RT =
AUCTION_EXTENSION_RT =
BLOCK_TRADE_ACCUM_VOLUME_RT =
TOTAL_MSG_SCRAPED_OFFERS_RT =
EVENT_TIME = 22:30:00.000
VOLUME_THEO =
OPEN_YLD_TDY_RT =
HIGH_YLD_TDY_RT =
LOW_YLD_TDY_RT =
LAST_YLD_TDY =
MID_TDY =
SIZE_LAST_TRADE_TDY =
RT_PX_CHG_NET_1D = 171.75
RT_PX_CHG_PCT_1D = 1.485
OPEN_TDY =
ASK_SIZE_TDY =
BID_SIZE_TDY =
VOLUME_TDY =
LAST_PRICE_TDY =
BID_TDY =
ASK_TDY =
HIGH_TDY =
LOW_TDY =
BID_YLD_TDY =
ASK_YLD_TDY =
TIME = 2022-06-23
LAST_UPDATE_ALL_SESSIONS_RT =
PX_OPEN_ALL_WITH_SWITCHOVER_RT =
BID_ALL_SESSION_TDY_RT =
ASK_ALL_SESSION_TDY_RT =
CONTINUOUS_TRAD_CLOS_BID_PX_RT =
CONTINUOUS_TRAD_CLOS_ASK_PX_RT =
POST_CLOSING_AUCTION_BID_PX_RT =
POST_CLOSING_AUCTION_ASK_PX_RT =
LAST_TRADE_RECEIVED_TIME_RT =
PRICE_CHANGE_ON_DAY_RT = 171.75
PRICE_LAST_ASK_RT =
PRICE_LAST_BID_RT =
PRICE_HIGH_RT =
PRICE_LOW_RT =
PRICE_OPEN_RT =
LAST_TRADE_PRICE_TODAY_RT =
PREVIOUS_TOTAL_VOLUME_RT = 622197
PREVIOUS_CLOSE_ADJ_BY_GR_DVD_RT =
TIME_AUCTION_CALL_CONCLUSION_RT =
PER_TRADE_VWAP_REALTIME =
PER_TRADE_VWAP_TURNOVER_RT =
PER_TRADE_VWAP_VOLUME_RT =
OPEN_HIGH_PRICE_REALTIME =
OPEN_LOW_PRICE_REALTIME =
CLOSE_HIGH_PRICE_REALTIME =
CLOSE_LOW_PRICE_REALTIME =
EXCHANGE_FOR_PHYSICAL_VOLUME_RT =
EXCHANGE_FOR_SWAP_VOLUME_RT =
LAST_BID_TIME_TODAY_REALTIME =
LAST_ASK_TIME_TODAY_REALTIME =
LAST_MID_TIME_TODAY_REALTIME =
LAST_PRICE_TIME_TODAY_REALTIME =
LAST_TRADE_PRICE_TIME_TODAY_RT =
MINIMUM_ORDER_LIMIT_PRICE_RT =
MAXIMUM_ORDER_LIMIT_PRICE_RT =
MIN_DYNAMIC_TRADING_LIMIT_PX_RT =
MAX_DYNAMIC_TRADING_LIMIT_PX_RT =
15_SECOND_PRICE_CHANGE_RT =
1_MINUTE_PRICE_CHANGE_RT =
5_MINUTE_PRICE_CHANGE_RT =
15_MINUTE_PRICE_CHANGE_RT =
1_HOUR_PRICE_CHANGE_RT =
CIRCUIT_BREAKER_TRIG_SIGNAL_RT =
LAST_CONTINUOUS_TRADE_PRICE_RT =
DYNAMIC_TRADING_LIMITS_REF_PX_RT =
LAST_OFF_BOOK_TRADE_PRICE_RT =
CB_TRIGGER_SIGNAL_START_TIME_RT =
CB_TRIGGER_SIGNAL_END_TIME_RT =
EFFECTIVE_DATE_RT =
OPEN_TRADE_PRICE_TODAY_RT =
HIGH_TRADE_PRICE_TODAY_RT =
LOW_TRADE_PRICE_TODAY_RT =
EXCHANGE_FOR_RISK_VOLUME_RT =
BLOOMBERG_CLOSE_PRICE_TODAY_RT =
PRICE_CLOSE_CC_TODAY_RT =
SUB_SEC_TM_AUCT_CALL_CNCLSN_RT =
THEORETICAL_TIME_TODAY_RT =
ON_EXCHANGE_VOLUME_TODAY_RT =
ON_BOOK_VOLUME_TODAY_RT =
LIT_BOOK_VOLUME_TODAY_RT =
CONTINUOUS_VOLUME_TODAY_RT =
AUCTION_VOLUME_TODAY_RT =
SCHEDULED_AUCT_VOLUME_TODAY_RT =
OPENING_AUCTION_VOLUME_RT =
CLOSING_AUCTION_VOLUME_RT =
INTRADAY_AUCTION_VOLUME_TODAY_RT =
UNSCHEDULED_AUCT_VOLUME_TODAY_RT =
TRADE_LAST_CLOSE_VOLUME_TODAY_RT =
PRE_POST_AUTO_EXECTN_VOL_TDY_RT =
DARK_BOOK_VOLUME_TODAY_RT =
ON_BK_NEG_BTF_OR_CC_VOL_TDY_RT =
ODD_LOT_BOOK_VOLUME_TODAY_RT =
OFF_BOOK_VOLUME_TODAY_RT =
NEGOTIATED_VOLUME_TODAY_RT =
OFF_BK_BLOCK_OR_CC_VOLUME_TDY_RT =
OFF_BOOK_ODD_LOT_VOLUME_TODAY_RT =
OTC_VOLUME_TODAY_RT =
SYSTEMATIC_INTERNAL_VOL_TDY_RT =
REPORTED_DARK_VOLUME_TODAY_RT =
PERCENT_CHANGE_ON_DAY_TODAY_RT =
NET_CHANGE_ON_DAY_TODAY_RT =
LAST_TRADE_AM_SESSION_TODAY_RT =
OPEN_PRICE_AM_SESSION_TODAY_RT =
HIGH_PRICE_AM_SESSION_TODAY_RT =
LOW_PRICE_AM_SESSION_TODAY_RT =
VOLUME_AM_SESSION_TODAY_RT =
LAST_TRADE_PM_SESSION_TODAY_RT =
OPEN_PRICE_PM_SESSION_TODAY_RT =
HIGH_PRICE_PM_SESSION_TODAY_RT =
LOW_PRICE_PM_SESSION_TODAY_RT =
VOLUME_PM_SESSION_TODAY_RT =
EXCHANGE_VWAP_TODAY_RT =
SETTLEMENT_PRESENT_VALUE_RT =
MATURITY_CALIBRATION_RATE_RT =
MATURITY_CALIBRATION_PV_RT =
CONTRIBUTED_RECOVERY_RATE_RT =
PAR_SPREAD_BID_RT =
PAR_SPREAD_ASK_RT =
LIQUIDITY_INDICATOR_RT =
PRICE_BID_CLOSE_TODAY_RT =
PRICE_ASK_CLOSE_TODAY_RT =
OFFICIAL_CLOSE_TODAY_RT =
PREVIOUS_BLOOMBERG_CLOSE_PX_RT = 11737.5
PREVIOUS_LAST_TRADE_PRICE_RT = 11688
BLOOMBERG_SEND_TIME_RT = 2022-06-23T21:31:23.469+00:00
10_MINUTE_PRICE_CHANGE_RT =
30_MINUTE_PRICE_CHANGE_RT =
BLOOMBERG_CLOSE_PX_AM_TODAY_RT =
PERIODIC_AUCT_ON_DMD_VOL_TDY_RT =
PERIODIC_AUCT_ON_DMD_THEO_PX_RT =
CHG_NET_REG_SES_PRV_RG_SES_CL_RT =
CHG_PCT_REG_SES_PRV_RG_SES_CL_RT =
ACTUAL_TRADED_PRICE_RT =
MIN_DYNMC_BID_ORDR_LIMT_PX_RT =
MAXMM_DYNMC_BID_ORDR_LIMT_PX_RT =
MIN_DYNMC_ASK_ORDR_LIMT_PX_RT =
MAXMM_DYNMC_ASK_ORDR_LIMT_PX_RT =
MKTDATA_EVENT_TYPE = SUMMARY
MKTDATA_EVENT_SUBTYPE = NEWDAY
DELTA_AVAT_30_DAY_INTERVAL =
DELTA_AVAT_1_DAY_INTERVAL =
DELTA_AVAT_5_DAY_INTERVAL =
DELTA_AVAT_10_DAY_INTERVAL =
DELTA_AVAT_20_DAY_INTERVAL =
DELTA_AVAT_100_DAY_INTERVAL =
DELTA_AVAT_180_DAY_INTERVAL =
DELTA_ATAT_1_DAY_INTERVAL =
DELTA_ATAT_5_DAY_INTERVAL =
DELTA_ATAT_10_DAY_INTERVAL =
DELTA_ATAT_20_DAY_INTERVAL =
DELTA_ATAT_30_DAY_INTERVAL =
DELTA_ATAT_100_DAY_INTERVAL =
DELTA_ATAT_180_DAY_INTERVAL =
REALTIME_15_SEC_PRICE_PCT_CHG =
REALTIME_ONE_MIN_PRICE_PCT_CHG =
REALTIME_FIVE_MIN_PRICE_PCT_CHG =
REALTIME_15_MIN_PRICE_PCT_CHG =
REALTIME_ONE_HOUR_PRICE_PCT_CHG =
REALTIME_VOLUME_5_DAY_INTERVAL =
CURRENT_SESSION_RT = 4
IMPLIED_BID_PRICE_RT =
IMPLIED_ASK_PRICE_RT =
IMPLIED_BID_SIZE_RT =
IMPLIED_ASK_SIZE_RT =
IS_DELAYED_STREAM = false
}
}
I use this to check the datetime and emit a trade event:
if (message.HasElement(LAST_TIME))
{
if (message.GetElementAsDatetime(LAST_TIME).IsValid())
{
DateTime time = message.GetElementAsDatetime(LAST_TIME).ToSystemDateTime();
if (message.HasElement(LAST) && message.HasElement(SIZE))
{
double last = message.GetElementAsFloat64(LAST);
int last_size = message.GetElementAsInt32(SIZE);
long volume = message.GetElementAsInt64(VOLUME); ...
I receive:
'Bloomberglp.Blpapi.NotFoundException: LAST_TRADE_PRICE_TIME_TODAY_RT has no value in MarketDataUpdate.'
I have tried converting to string first and checking if empty and checking null. Any ideas would be helpful...
I don't think checking the DataType is what you want. The
DataType is part of the schema. It should always be set even when there is no value. If it seems to be working, it is possibly because the element's data type is not DATETIME. For instance, if it is of type DATE, or TIME, GetAsDateTime would still work, but the DataType will never be DATETIME—meaning the code path will never get hit. What you want to check is if it has a value.
HasElement is saying that the schema contains such an element, but if the schema definition allows for there to be zero values (optional), it might not have a value. GetValueAsDatetime() is really GetValueAsDatetime(0), meaning the 0th value which may not exist. Note the same function can be used for array type items that have more than one value. I think the correct way to check this would be:
Element lastTime = message.GetElement(LAST_TIME);
if (lastTime.NumValues > 0) {
DateTime dt = lastTime.GetValueAsDatetime();
I suspect that
if (message.HasElement(LAST_TIME))
returns true because the field is there (but empty). However when you call:
if (message.GetElementAsDatetime(LAST_TIME).IsValid())
GetElementAsDatetime throws an exception because the value (which is empty) is not a valid datetime.
I think something like this may work:
Element lastTime = message.GetElement(LAST_TIME);
if (lastTime.Datatype() == Schema.Datatype.DATETIME) {
DateTime dt = lastTime.GetValueAsDatetime();
my question is fairly simple, which method should I use and why for parsing XML files?
Right now I have function for that:
return new EdiFile
{
SPPLR_MAILBOX = xmlDoc.Element("SPPLR_MAILBOX").Value,
MESSAGE_ID = xmlDoc.Element("MESSAGE_ID").Value,
ATTRIBUTE05 = xmlDoc.Element("ATTRIBUTE05").Value,
Levels0 = (from a in xmlDoc.Element("LEVELS0").Elements("LEVEL0")
select new Level0
{
PLT_NUM = a.Element("PLT_NUM").Value,
PLT_LABEL_ID = a.Element("PLT_LABEL_ID").Value,
BOX_QTY = a.Element("BOX_QTY").Value,
PLT_WEIGHT = a.Element("PLT_WEIGTH").Value,
PLT_DIMENSION = a.Element("PLT_DIMENSION").Value,
PLT_CHEM = a.Element("PLT_CHEM").Value,
PLT_NOT_STACK = a.Element("PLT_NOT_STACK").Value,
PLT_NOTE = a.Element("PLT_NOTE").Value,
ATTRIBUTE01 = a.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = a.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = a.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = a.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = a.Element("ATTRIBUTE05").Value,
Levels1 = (from b in a.Element("LEVELS1").Elements("LEVEL1")
select new Level1
{
BOX_NUM = b.Element("BOX_NUM").Value,
BOX_LABEL_ID = b.Element("BOX_LABEL_ID").Value,
Items = (from c in b.Element("ITEMS").Elements("ITEM")
select new Item
{
SPPLR_ITEM = c.Element("SPPLR_ITEM").Value,
CUST_ITEM = c.Element("CUST_ITEM").Value,
ATTRIBUTE01 = c.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = c.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = c.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = c.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = c.Element("ATTRIBUTE05").Value,
Lots = (from d in c.Element("LOTS").Elements("LOT")
select new Lot
{
LOT_NUM = d.Element("LOT_NUM").Value,
LOT_LABEL_ID = d.Element("LOT_LABEL_ID").Value,
LOT_NOTE = d.Element("LOT_NOTE").Value,
LOT_EXP_DATE = d.Element("LOT_EXP_DATE").Value,
QTY = d.Element("QTY").Value,
UOM = d.Element("UOM").Value,
ATTRIBUTE01 = d.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = d.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = d.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = d.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = d.Element("ATTRIBUTE05").Value
}).ToList()
}).ToList()
}).ToList()
}).ToList()
};
But should I use deserialize? I learnt about serialization yesterday.
I cant really find any source explaining my method, vs deserialization.
Can someone get me any insight please?
Your method is more performance and flexie, because you have control on processing xml file. Serialization is using reflection and it is less performance.
I have an attribute that I'd like to add for faceting: ApprovalFL. When I add the facet in the Algolia dashboard, it works fine until I have to reindex which ends up deleting my facets in the dashboard for some reason. I was thinking, maybe adding the attribute in my code would resolve that. I found the documentation about this step here: https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting/
Here's the C# example they provide:
index.SetSettings(
JObject.Parse(#"{""attributesForFaceting"":[""author"",""filterOnly(category)"",""searchable(publisher)""]}")
);
If I understand correctly, this code needs to go in my backend reindexing code (found in my AdminController.cs):
public async Task<ActionResult> ReIndexData()
{
var algoliaArtistModels = Tools.BuildAlgoliaArtistModels(EntityDataAccess.GetAllAccountInfoes());
var algoliaUnaffiliatedArtistModels = Tools.BuildAlgoliaArtistModels(EntityDataAccess.GetAllUnaffiliatedAccountInfo());
var algoliaSongModels = Tools.BuildAlgoliaSongModels(EntityDataAccess.GetAllAcceptedSongs());
var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
var unaffiliatedArtistIndexHelper = HttpContext.Application.Get("UnaffiliatedArtist") as IndexHelper<ArtistAlgoliaModel>;
var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
await artistIndexHelper.OverwriteIndexAsync(algoliaArtistModels);
await unaffiliatedArtistIndexHelper.OverwriteIndexAsync(algoliaUnaffiliatedArtistModels);
await songIndexHelper.OverwriteIndexAsync(algoliaSongModels);
return View("AlgoliaReIndexData");
}
However, I don't think I put index.setSettings in this block of code, what is the best way to set this attribute for faceting in my backend code? The ApprovalFL attribute is stored in my Song indices.
Possibly it should go somewhere here in my Tools.cs?
public static SongAlgoliaModel BuildAlgoliaSongModel(Song song)
{
var model = new SongAlgoliaModel();
var album = EntityDataAccess.GetAlbumByID(song.AlbumID);
model.AccountImageURL = album.AccountInfo.ImageURL;
model.AccountInfoID = album.AccountInfoID;
model.AccountType = album.AccountInfo.CreatorFL == true ? "Creator" : "Artist";
model.AlbumID = song.AlbumID;
model.AlbumName = album.AlbumName;
model.ApprovalFL = song.ApprovalFL;
model.Artist = album.AccountInfo.DisplayName;
model.BPM = song.BPM;
model.Duration = song.Duration;
model.FeaturedArtist = song.Artist;
model.FreeFL = album.FreeFL;
model.ImageURL = album.ImageURL;
model.iTunesURL = album.iTunesURL;
model.LabelName = album.LabelName;
model.LicenseFL = album.LicenseFL;
model.SongID = song.SongID;
model.Title = song.Title;
model.UploadDate = song.UploadDate;
model.URL = song.URL;
model.UserID = album.AccountInfo.UserID;
return model;
}
public static List<SongAlgoliaModel> BuildAlgoliaSongModels(AccountInfo accountInfo)
{
var list = new List<SongAlgoliaModel>();
var songs = EntityDataAccess.GetSongsByUserID(accountInfo.UserID).Where(x => x.ApprovalFL == true).ToList();
foreach(var item in songs)
{
var model = new SongAlgoliaModel();
model.AccountImageURL = item.Album.AccountInfo.ImageURL;
model.AccountInfoID = item.Album.AccountInfoID;
model.AccountType = item.Album.AccountInfo.CreatorFL == true ? "Creator" : "Artist";
model.AlbumID = item.AlbumID;
model.AlbumName = item.Album.AlbumName;
model.ApprovalFL = item.ApprovalFL;
model.Artist = item.Album.AccountInfo.DisplayName;
model.BPM = item.BPM;
model.Duration = item.Duration;
model.FeaturedArtist = item.Artist;
model.FreeFL = item.Album.FreeFL;
model.ImageURL = item.Album.ImageURL;
model.iTunesURL = item.Album.iTunesURL;
model.LabelName = item.Album.LabelName;
model.LicenseFL = item.Album.LicenseFL;
model.SongID = item.SongID;
model.Title = item.Title;
model.UploadDate = item.UploadDate;
model.URL = item.URL;
model.UserID = item.Album.AccountInfo.UserID;
list.Add(model);
}
return list;
}
OK for those using C# .NET it's as simple as adding it to your Global.asax.cs for example for me:
var songIndexHelper = new IndexHelper<SongAlgoliaModel>(algoliaClient, "Song", "SongID");
songIndexHelper.SetSettings(JObject.Parse(#"{""attributesForFaceting"":[""ApprovalFL""]}"));
Why do you have to re-index by the way? Best practice is to set up your index only initially.
C#, Linq2Sql, .NET 2.0, SQL 2005 Express
When I run the following code I get a
InvalidCastException unable to cast of type System.Byte[] to System.String
This does not occur on all rows in the table i.e. this code runs fine soemtimes.
I checked there are no columns in the table that linq declares as SYstem.Byte[]
The stack trace says the exception occurs on the linq statement and when I F11
into the code the GetProject is never called the exception occurs before this method
is called.
So I think it is Linq framework bug.
This has got me stumped? any ideas?
[code]
public Project GetProject(int id)
{
var project = (from row in _dbctx.Projects
where row.ProjectID == id
select row).SingleOrDefault();
Project proj = GetProject(project);
return proj;
}
private Project GetProject(TBRServices.Domain.TBR.DataContext.Project sqlproject)
{
Project project = new Project();
project.ProjectID = sqlproject.ProjectID;
project.ProjectName = sqlproject.ProjectName;
project.ProjectDescription = sqlproject.ProjectDescription;
project.ClientID = sqlproject.ClientID;
project.PurchaseOrderNumber = sqlproject.PurchaseOrderNumber;
project.ProjectTotalBillingEstimate = sqlproject.ProjectTotalBillingEstimate;
project.EmployeeID = sqlproject.EmployeeID;
project.ProjectBeginDate = sqlproject.ProjectBeginDate.ToString();
project.ProjectEndDate = sqlproject.ProjectEndDate.ToString();
project.Active = sqlproject.Active;
project.InclGST = sqlproject.InclGST;
project.ContractRate = sqlproject.ContractRate;
project.MarginRate = sqlproject.MarginRate;
project.Notes = sqlproject.Notes;
project.PayrollTax = sqlproject.PayrollTax;
project.EmployeeReference = sqlproject.EmployeeReference;
project.PayReference = sqlproject.PayReference;
project.ProjectLocation = sqlproject.ProjectLocation;
project.ContractTypeID = sqlproject.ContractTypeID;
project.DoNotCalcMarginOrGST = sqlproject.DoNotCalcMarginOrGST;
project.ConvertToInvoice = sqlproject.ConvertToInvoice;
project.AuthFirstname = sqlproject.AuthFirstname;
project.AuthLastname = sqlproject.AuthLastname;
project.AuthEmail = sqlproject.AuthEmail;
project.CapturedDocumentType = sqlproject.CapturedDocumentType;
project.TimesheetProcessingType = sqlproject.TimesheetProcessingType;
project.TimesheetFrequency = sqlproject.TimesheetFrequency;
project.AggregateTimesheet = sqlproject.AggregateTimesheet;
project.AggregateAutomatically = sqlproject.AggregateAutomatically;
project.BusProcEmpCut = sqlproject.BusProcEmpCut;
project.BusProcAgencyCut = sqlproject.BusProcAgencyCut;
project.SendCopyTimesheet = sqlproject.SendCopyTimesheet;
project.TimesheetRecipient1 = sqlproject.TimesheetRecipient1;
project.TimesheetRecipient2 = sqlproject.TimesheetRecipient2;
project.SendCopyInvoice = sqlproject.SendCopyInvoice;
project.PublishedOn = sqlproject.PublishedOn.ToString();
project.SendAggTimesheetsWhenReceived = sqlproject.SendAggTimesheetsWhenReceived;
project.AuthoriseInvoice = sqlproject.AuthoriseInvoice;
project.HourlyDailyMthly = sqlproject.HourlyDailyMthly;
project.EmployeeCategory = sqlproject.EmployeeCategory;
project.AgencyRate = sqlproject.AgencyRate;
project.ConsultantID = sqlproject.ConsultantID;
project.SendCopyInvoiceEmployee = sqlproject.SendCopyInvoiceEmployee;
project.UseClientDetailsForTimesheet = sqlproject.UseClientDetailsForTimesheet;
project.FaxedTimesheet = sqlproject.FaxedTimesheet;
project.TimesheetEditable = sqlproject.TimesheetEditable;
project.IncludeInReport = sqlproject.IncludeInReport;
project.SendLogonEmail = sqlproject.SendLogonEmail;
project.NoticePeriodID = sqlproject.NoticePeriodID;
project.ManagerCanViewPaidUnpaid = sqlproject.ManagerCanViewPaidUnpaid;
project.LesterSalesStaff = sqlproject.LesterSalesStaff;
project.IncludeSalesReport = sqlproject.IncludeSalesReport;
project.CurrencyAccount = sqlproject.CurrencyAccount;
project.LeaveMustBeAuthorisedTimesheet = sqlproject.LeaveMustBeAuthorisedTimesheet;
project.LeaveMustBeAuthorisedLeaveForm = sqlproject.LeaveMustBeAuthorisedLeaveForm;
project.DefaultHoursWorkedWeek = sqlproject.DefaultHoursWorkedWeek;
project.DefaultHoursWorkedDay = sqlproject.DefaultHoursWorkedDay;
project.AccruedLeaveStartDate = sqlproject.AccruedLeaveStartDate.ToString();
project.AllowLeaveMoreThanAccrued = sqlproject.AllowLeaveMoreThanAccrued;
project.IsPaidASalary = sqlproject.IsPaidASalary;
project.AgencyID = sqlproject.AgencyID;
project.SendEmailToManagerToOKLeave = sqlproject.SendEmailToManagerToOKLeave;
project.SpecialPayrollNotes = sqlproject.SpecialPayrollNotes;
project.SpecialInvoicingNotes = sqlproject.SpecialInvoicingNotes;
project.InvoiceTermsMessage = sqlproject.InvoiceTermsMessage;
project.AuthManagerPhone = sqlproject.AuthManagerPhone;
project.LMF = sqlproject.LMF;
project.LMFPercent = sqlproject.LMFPercent;
project.LMFInclInPayRate = sqlproject.LMFInclInPayRate;
project.LMFOnTop = sqlproject.LMFOnTop;
project.AgencyComm = sqlproject.AgencyComm;
project.AgencyCommPercent = sqlproject.AgencyCommPercent;
project.AgencyCommInclInPayRate = sqlproject.AgencyCommInclInPayRate;
project.AgencyCommOnTop = sqlproject.AgencyCommOnTop;
project.PayRateInclMargin = sqlproject.PayRateInclMargin;
project.MarginRatePercent = sqlproject.MarginRatePercent;
project.MarginRateGST = sqlproject.MarginRateGST;
project.MarginRateInclInPayRate = sqlproject.MarginRateInclInPayRate;
project.MarginRateOnTop = sqlproject.MarginRateOnTop;
project.PayRateInclSuper = sqlproject.PayRateInclSuper;
project.PayrollTaxAmount = sqlproject.PayrollTaxAmount;
project.PayrollTaxPercent = sqlproject.PayrollTaxPercent;
project.PayrollTaxInclInPayRate = sqlproject.PayrollTaxInclInPayRate;
project.PayrollTaxOnTop = sqlproject.PayrollTaxOnTop;
project.TypeOfArrangement = sqlproject.TypeOfArrangement;
project.ParameterRequired = sqlproject.ParameterRequired;
project.SpecialPayrollEnabled = sqlproject.SpecialPayrollEnabled;
project.ClientContactUsedReceiptOfInvoiceID = sqlproject.ClientContactUsedReceiptOfInvoiceID;
project.ExcludeEmpNameOnInvoice = sqlproject.ExcludeEmpNameOnInvoice;
project.BPForReporting = sqlproject.BPForReporting;
project.UseGemteqInvoiceFormat = sqlproject.UseGemteqInvoiceFormat;
project.TreatPayrollDetailsSameAsBP = sqlproject.TreatPayrollDetailsSameAsBP;
return project;
}
[/code]
Check the answer to a similar SO question. It will not be the exact answer but may help you find the problem in your query -
Problem with Linq to SQL
unable to cast of type System.Byte[] to System.String
Indicates that a property in sqlproject is stored as byte[] while the corresponding property in project is a string