I'm trying to use Bloomberg API to get holiday information about a ticker, the request below produces the dates correctly but I would also like to include the name of the holiday
Could there be an override that will also include the name of the date as on "New Year"
ReferenceDataRequest = {
securities[] = {
LQ45 Index
}
fields[] = {
CALENDAR_HOLIDAYS
}
overrides[] = {
overrides = {
fieldId = "SETTLEMENT_CALENDAR_CODE"
value = "JA"
}
overrides = {
fieldId = "CALENDAR_START_DATE"
value = "20190101"
}
overrides = {
fieldId = "CALENDAR_END_DATE"
value = "20191231"
}
}
tableOverrides[] = {
}
}
the c# code I am using was suggested on another question that I can no longer find, and it is:
Request request = this._service.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement(BloombergConstants.SECURITIES);
securities.AppendValue(ticker);
Element fields = request.GetElement(BloombergConstants.FIELDS);
fields.AppendValue("CALENDAR_HOLIDAYS");
//Element overridefields = request.GetElement(BloombergConstants.OVERRIDES);
Element overrides = request.GetElement(BloombergConstants.OVERRIDES);
Element override1 = overrides.AppendElement();
override1.SetElement(BloombergConstants.FIELDID, "SETTLEMENT_CALENDAR_CODE");
override1.SetElement(BloombergConstants.VALUE, calendarCode);
override1 = overrides.AppendElement();
override1.SetElement(BloombergConstants.FIELDID , "CALENDAR_START_DATE");
override1.SetElement(BloombergConstants.VALUE, startDate.ToString("yyyyMMdd"));
Element override2 = overrides.AppendElement();
override2.SetElement(BloombergConstants.FIELDID, "CALENDAR_END_DATE");
override2.SetElement(BloombergConstants.VALUE, endDate.ToString("yyyyMMdd"));
Sadly not.
see Official Bloomberg API-Core-Developer-Guide.pdf
see Unofficial Bloomberg .Net API Implementation
Unfortunately it looks like there is no override code to add this behaviour. This is a bit non intuitive, but if you search for the relevant code CALENDAR_HOLIDAYS you actually receive information on the code CALENDAR_NON_SETTLEMENT_DATES (possibly this was renamed and aliased to this at some point?)
fieldInfoRequest = {
id[] = {
"CALENDAR_HOLIDAYS"
}
}
fieldResponse = {
fieldData[] = {
fieldData = {
id = "ZS090"
fieldInfo = {
mnemonic = "CALENDAR_NON_SETTLEMENT_DATES"
description = "Calendar Non-Settlement Dates"
datatype = String
categoryName[] = {
}
property[] = {
}
overrides[] = {
"ZS089", "ZS087", "ZS088"
}
ftype = BulkFormat
}
}
}
}
These overrides correspond to
id mnemonic
ZS087 SETTLEMENT_CALENDAR_CODE
ZS088 CALENDAR_START_DATE
ZS089 CALENDAR_END_DATE
Non of which adds functionality to return a description of the holiday the date corresponds to.
Related
I'm trying to convert a java project to C#. In the following piece I don't know how to convert the Json part.
Cursor resultSet = helper.openDataBase().rawQuery("Select * from word where wname=?", new String[] {String.valueOf(editable)});
TextView TextView_FA = findViewById(R.id.textView_FA);
if( resultSet.moveToFirst())
{
String str_json = resultSet.getString(2);
try {
JSONObject obj = new JSONObject(str_json);
String trans = obj.getJSONArray("ss").optJSONObject(0) .getString("s");
TextView_FA.setText(trans);
} catch (JSONException e) {
TextView_FA.setText(e.getLocalizedMessage());
}
}
else {
TextView_FA.setText("no translation found");
}
This is what I've tried:
EditText EditText_en = FindViewById<EditText>(Resource.Id.EditText_en);
Java.IO.File fil = new Java.IO.File(db_src);
SQLiteDatabase db = SQLiteDatabase.OpenDatabase(fil,null);
Android.Database.ICursor resultSet = db.RawQuery("Select * from word where wname =? ",new[]{ EditText_en.Text});
TextView TextView_FA = FindViewById<TextView>(Resource.Id.TextView_fa);
if (resultSet.MoveToFirst())
{
String str_json = resultSet.GetString(2);
try
{
// JSONObject obj = new JSONObject(str_json);
// String trans = obj.getJSONArray("ss").optJSONObject(0).getString("s");
TextView_FA.Text = trans;
}
catch (Exception e)
{
TextView_FA.Text = e.Message;
}
}
else
{
TextView_FA.Text = "no translation found" ;
}
The two line I've commented is the question.
I tried to use System.Text.Json or System.Json as some of the internet docs has said but VS2019
intellisense doesn't recognize them as a valid library.
To use the NewtonSoft.JSon i probably the most common way to Deserialize json and a bit easier (forgiving) than the System.Text.Json. It is also easier to work with JSon if you have a known type. I don't know how your JSon sttring look like but I have made my own example string
//[
// {
// color: "red",
// value: "#f00"
// },
// {
// color: "green",
// value: "#0f0"
// },
// {
// color: "blue",
// value: "#00f"
// }
//]
string myJson = "[\r\n\t{\r\n\t\t\"color\": \"red\",\r\n\t\t\"value\": \"#f00\"\r\n\t},\r\n\t{\r\n\t\t\"color\": \"green\",\r\n\t\t\"value\": \"#0f0\"\r\n\t},\r\n\t{\r\n\t\t\"color\": \"blue\",\r\n\t\t\"value\": \"#00f\"\r\n\t}\r\n\t\r\n]";
If you have a class or can define it, it will be easier to work with the JSon, but I have created an example without use of the class to
public class custColor
{
public string color { get; set; }
public string value { get; set; }
}
Examples with both NewtonSoft and System.Text.Json
//NewtonSoft JSON
var arrayOfColors = JsonConvert.DeserializeObject<custColor[]>(myJson);
var valueFromArray = arrayOfColors[0].value; //Will give #f00
var dynamicColorArray = JsonConvert.DeserializeObject<dynamic>(myJson);
var valueFromDynArray = dynamicColorArray[0].value; //Will also give #f00
//System.Text.Json
var stjArrayOfColors = System.Text.Json.JsonSerializer.Deserialize<custColor[]>(myJson);
var stjValueFromArray = stjArrayOfColors[0].value; //Will give #f00
I made a bot in C# using BotFramework, Adaptive Cards, LUIS and FormFlow. It/he is responsible for managing meetings in a team.
return new FormBuilder<MeetingRequestInput>()
...
.Field(
nameof(MeetingRequestInput.RequestedDate),
"What date would you like to meet?"
)
...
.Build();
During tests we noticed problems when a user was supposed to type the desired meeting date/time (people would type dd/mm/yy, mm/dd/yy, dd-mm-yy, only dd, etcetra) so we would like to use some kind of "Form" with formatted inputs to avoid parsing problems and retaining usability.
I think we can't change the desired keyboard type (kinda like in mobile, where sometimes the keyboard only shows numbers, or shows a DateTime Picker), nor apply a pattern auto-complete, at least using BotFramework.
To solve this, I'd like to use an AdaptiveCard with Date and Time pickers in my FormFlow prompt, at least when the user is asked to type the requested date, like so:
Input example using Adaptive Cards
In this example, the user would fill the AdaptiveDateInput and the AdaptiveTimeInput, then press the Confirm button. Doing so, it would grab the values inside the inputs, then "type and send" for the user the desired DateTime in a specific template, avoiding the previous parsing problems.
Problem is, I can't replace the "normal" FormFlow Card (who's expecting a simple string as a prompt parameter) with an entire Adaptive Card. How do I solve this problem? Are AdaptiveCards the best answer or are there alternatives?
Right now I'm displaying the card manually like so:
AdaptiveCard card = new AdaptiveCard();
card.Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "What date would you like to meet?"
},
new AdaptiveDateInput()
{
Value = DateTime.Now.ToShortDateString(),
Id = "dateInp"
},
new AdaptiveTimeInput()
{
Value = DateTime.Now.ToShortTimeString(),
Id = "timeInp"
}
};
card.Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Type = "Action.Submit",
Title = "Confirm"
}
};
var msg = context.MakeMessage();
msg.Attachments.Add(
new Attachment()
{
Content = card,
ContentType = "application/vnd.microsoft.card.adaptive",
Name = "Requested Date Adaptive Card"
}
);
await context.PostAsync(msg);
I've read this question, but I don't know if we have the exact same problem. And their solution does not apply to me: even though I made the examples above in english, the bot will actually expect inputs in other languages, so yeah we can parse "February 2th" using a Recognizer, but we don't have the same luck with "2 de Fevereiro" nor "2 Fevralya".
Using the FormBuilder.Prompter, you can customize FormFlow messages any way you like. However, since AdaptiveCards send responses in the .Value, the code will need to transfer .Value to .Text property before validation.
Here is an example of a FormFlow form that sends an AdaptiveCard for a RequestedDate field:
[Serializable]
public class AdaptiveCardsFormFlow
{
public string Name { get; set; }
public DateTime? RequestedDate { get; set; }
public static IForm<AdaptiveCardsFormFlow> BuildForm()
{
IFormBuilder<AdaptiveCardsFormFlow> formBuilder = GetFormbuilder();
var built = formBuilder
.Field(nameof(Name), "What is your name?")
.Field(nameof(RequestedDate))
.Confirm("Is this information correct? {*}")
.Build();
return built;
}
private static AdaptiveCard GetDateCard()
{
AdaptiveCard card = new AdaptiveCard();
card.Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "What date would you like to meet?"
},
new AdaptiveDateInput()
{
Value = DateTime.Now.ToShortDateString(),
Id = "dateInp"
},
new AdaptiveTimeInput()
{
Value = DateTime.Now.ToShortTimeString(),
Id = "timeInp"
}
};
card.Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Type = "Action.Submit",
Title = "Confirm"
}
};
return card;
}
private static IFormBuilder<AdaptiveCardsFormFlow> GetFormbuilder()
{
IFormBuilder<AdaptiveCardsFormFlow> formBuilder = new FormBuilder<AdaptiveCardsFormFlow>()
.Prompter(async (context, prompt, state, field) =>
{
var preamble = context.MakeMessage();
var promptMessage = context.MakeMessage();
if (prompt.GenerateMessages(preamble, promptMessage))
{
await context.PostAsync(preamble);
}
if (field != null && field.Name == nameof(AdaptiveCardsFormFlow.RequestedDate))
{
var attachment = new Attachment()
{
Content = GetDateCard(),
ContentType = AdaptiveCard.ContentType,
Name = "Requested Date Adaptive Card"
};
promptMessage.Attachments.Add(attachment);
}
await context.PostAsync(promptMessage);
return prompt;
}).Message("Please enter your information to schedule a callback.");
return formBuilder;
}
}
Using this class:
private class DateTimeInp
{
public string dateInp { get; set; }
public string timeInp { get; set; }
public DateTime? ToDateTime()
{
string fullDateTime = dateInp + " " + timeInp;
DateTime toDateTime;
if(DateTime.TryParse(fullDateTime, out toDateTime))
{
return toDateTime;
}
return null;
}
}
Then, in the Messages Controller, add the Adaptive Card's return value to the .Text property of the activity:
if(activity.Value != null)
{
DateTimeInp input = JsonConvert.DeserializeObject<DateTimeInp>(activity.Value.ToString());
var toDateTime = input.ToDateTime();
if(toDateTime != null)
{
activity.Text = toDateTime.ToString();
}
}
I'm trying to access Amazon MWS API from my .Net application, using Products API Section Client Library - C# (https://developer.amazonservices.com/doc/products/products/v20111001/cSharp.html/138-8219342-3408216)
Everything works fine, except for GetMyFeesEstimate calls.
I use this method from example:
public GetMyFeesEstimateResponse InvokeGetMyFeesEstimate()
{
// Create a request.
GetMyFeesEstimateRequest request = new GetMyFeesEstimateRequest();
string sellerId = "example";
request.SellerId = sellerId;
string mwsAuthToken = "example";
request.MWSAuthToken = mwsAuthToken;
FeesEstimateRequestList feesEstimateRequestList = new FeesEstimateRequestList();
request.FeesEstimateRequestList = feesEstimateRequestList;
return this.client.GetMyFeesEstimate(request);
}
And I add item to FeesEstimateRequestList like this:
feesEstimateRequestList.FeesEstimateRequest.Add(new FeesEstimateRequest
{
MarketplaceId = marketplaceId,
IdType = "ASIN",
IdValue = "B0078LENZC",
PriceToEstimateFees = new PriceToEstimateFees { ListingPrice = new MoneyType { Amount = 30.49M, CurrencyCode = "GBP" }, Shipping = new MoneyType { Amount = 3.5M, CurrencyCode = "GBP" }, Points = new Points { PointsNumber = 0 } },
Identifier = "request_" + Guid.NewGuid().ToString(),
IsAmazonFulfilled = false
});
But constantly get MalformedInput error with no message describing what is wrong:
<ErrorResponse
xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<Error>
<Type>Sender</Type>
<Code>MalformedInput</Code>
</Error>
<RequestId>f79b9147-90d7-4ea2-b51c-d6c37c6a1bd0</RequestId>
</ErrorResponse>
Have someone any ideas how to make it work?
I have found solution:
Due to my OS regional settings, decimal separator in price had being set to comma, instead of dot when converting parameters to string.
I have to modify method putValue of MwsAQCall class like this:
private void putValue(object value)
{
if (value==null)
{
return;
}
if (value is IMwsObject)
{
parameterPrefix.Append('.');
(value as IMwsObject).WriteFragmentTo(this);
return;
}
string name = parameterPrefix.ToString();
if (value is DateTime)
{
parameters.Add(name, MwsUtil.GetFormattedTimestamp((DateTime)value));
return;
}
string valueStr = value.ToString();
if (value is decimal)
{
valueStr = valueStr.Replace(",", ".");
}
if (valueStr==null || valueStr.Length==0)
{
return;
}
if (value is bool)
{
valueStr = valueStr.ToLower();
}
parameters.Add(name, valueStr);
}
I am trying to use one attach to the EF to update all the records I need.
public void UpdateSale(Sale s)
{
Context.Sales.Attach(s);
Context.Entry(s).State = System.Data.Entity.EntityState.Modified;
Context.SaveChanges();
}
Lets Say like so. The above code gives me an error because it says the primary keys I am trying to add already exist(They arent automatically generated yet)
Now Sale has a number of different other Entity Models inside it like:
SavedForm, ProductSale
Now the code calling the UpdateSale is here
public JsonResult AddNewForms(string Anamaka, string NispahB, string Hazaot, string ManufactorerID, string ClientStatus, string TypeFile)
{
BL.FormConnectorLogic fcl = new BL.FormConnectorLogic();
DAL.SavedForm AnamakaForm = MakeSavedForm(Boolean.Parse(Anamaka),"מסמך הנמקה",ClientStatus);
DAL.SavedForm NispahBForm = MakeSavedForm(Boolean.Parse(NispahB), "נספח ב", ClientStatus);
DAL.SavedForm HazaotForm = MakeSavedForm(Boolean.Parse(Hazaot), TypeFile, ClientStatus, ManufactorerID);
var results = new { A = AnamakaForm, N = NispahBForm, H = HazaotForm };
return Json(results, JsonRequestBehavior.AllowGet);
}
public DAL.SavedForm MakeSavedForm(bool Authorized, string FormName, string ClientStatus, string ManufactorerID = "")
{
DAL.Sale s = (DAL.Sale)Session["SaleSave"];
DAL.SavedForm sf = new DAL.SavedForm();
if (Authorized)
{
sf = new DAL.SavedForm();
sf.FormName = new BL.FormConnectorLogic().getFormByName(FormName, ClientStatus, ManufactorerID).FormName;
sf.DateFormed = DateTime.Now;
sf.AgentID = s.AgentID;
sf.Status = "פתוח";
sf.SaleID = s.ID;
s.SavedForms.Add(sf);
new BL.SaleLogic().UpdateSale(s);
Session["SaleSave"] = s;
return sf;
}
else return null;
}
Now I've read up on the State and there is a difference between Added and Modified.
While I can't really seem to tell when I am going to add and when I am going to modify.
Is there anyway to disregard everything and to just shove my whole class and all its relationships to the database?
I am currently trying to create a list of custom objects using data I get back from isolatedstorage, and deserializing it.
it worked perfectly yesterday and just keeps givin me this exception today, and I am not sure what to do?
{System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
at System.String.Substring(Int32 startIndex, Int32 length)
at LandbouWP.ViewModel.StoryVM.GetStories(List`1 news_items)}
the code for getting the data and deserializing it:
var loaded_result = settings["mainlist"].ToString();
var s = JsonConvert.DeserializeObject<List<Object>>(loaded_result);
the deserializing works perfectly, so I don't think the issue is here, however does it maybe add another property or something to the list?
then I create a custom list of the returned items
App.StoryViewModel.GetStories(s);
and that code is:
public void GetStories(List<Object> news_items)
{
List<Story> a = new List<Story>();
List<Story> b = new List<Story>();
//loop over all items and add them for a viewmodel
int i = 0;
foreach (var item in news_items)
{
if (item.IsDeleted == true)
{
//do not add the item
}
else
{
try
{
a.Add(new Story
{
ID = news_items[i].ID,
IsDeleted = news_items[i].IsDeleted,
IsActive = news_items[i].IsActive,
Title = news_items[i].Title,
Author = news_items[i].Author,
Synopsis = news_items[i].Synopsis,
Body = news_items[i].Body,
ImageUrl = news_items[i].ImageUrl,
//CreationDate = DateTime.Parse(news_items[i].CreationDate),
CreationDate = news_items[i].CreationDate.Substring(0, news_items[i].CreationDate.IndexOf('T')),
LastUpdateDate = news_items[i].LastUpdateDate.Substring(0, news_items[i].LastUpdateDate.IndexOf('T')),
DisplayUntilDate = news_items[i].DisplayUntilDate.Substring(0, news_items[i].DisplayUntilDate.IndexOf('T')),
TotalViews = news_items[i].TotalViews,
Gallery = news_items[i].Gallery
});
i++;
}
catch (Exception ex)
{
string msg = ex.ToString();
string msg2 = msg;
}
}
}
//try here to remove duplicates?
foreach (var item in a)
{
if (!b.Contains(item))
{
b.Add(item);
}
else
{
b.Remove(item);
}
}
var new_list = b.OrderByDescending(x => x.CreationDate).ToList();
//save all the stories
story = new_list;
I cannot even go through each item individually that I am trying to set, it just throws length cannot be less than zero, and I am not sure what its talking about, I do not have a parameter in my class named Length?
Check carefully this place
CreationDate = news_items[i].CreationDate.Substring(0, news_items[i].CreationDate.IndexOf('T')),
LastUpdateDate = news_items[i].LastUpdateDate.Substring(0, news_items[i].LastUpdateDate.IndexOf('T')),
DisplayUntilDate = news_items[i].DisplayUntilDate.Substring(0, news_items[i].DisplayUntilDate.IndexOf('T')),
I suppose one of your dates just in wrong format and has no "T"