Firebase function transaction handle null value - firebase

I'm trying to use firebase function transaction, but as I see there is no official way to handle the first cached null value...
I'm trying to do the following:
var team = event.data.child('team').val();
var tip = event.data.child('tip').val();
console.log('tip: ' + tip + ' | team: ' +team)
const pathToValue = admin.database().ref('users/' + event.params.userId + '/coins');
const pathToTeamBetsValue = admin.database().ref('matches/' + event.params.matchId + '/opponents/' + team + "/bets");
return pathToValue.transaction(function (coins) {
if (coins) {
if (coins >= tip) {
pathToTeamBetsValue.transaction(function (teamBets) {
if (teamBets) {
teamBets = teamBets + tips;
return teamBets;
}
});
admin.database().ref('bets/' + event.params.matchId + '/' + event.params.userId + '/status').set('inProgress');
coins = coins - tip;
}
else {
console.warn(event.params.userId + " new bet on match " + event.params.matchId + " was not successfull! (not enough coin)")
//return coins;
}
}
return coins;
})
so far as you can see I get some value which what should be decreased from the user's coins... unfortunately till now I could only get the behaviour which sets null in the user's coin value.. please help

Related

How do I use loop in Firebase function?

I want to run loop in Firebase function
sample data set:
I want to loop through it and print
console.log hello
Output should be like:
Try this;
sampleDataSet.forEach((d)=>{
console.log("Hello " + d.firstName + " " + d.lastName);
})
if sampleDataSet is an object then we can loop object as well;
for (let [key, value] of Object.entries(sampleDataSet)) {
console.log("Hello " + value.firstName + " " + value.lastName);
}
database.ref("collection").once("value").then((snapshot) => {
snapshot.forEach((userSnap) => {
console.log('hello ' + userSnap.child(`firstName`).val() + ' ' + userSnap.child(`lastName`).val() );
});
});

Add 10 days with selected date -on-change method -service now

I have 2 date fields issued date and due date.When I choose issued date,due date should be auto populated by adding 10days with selected date. I have written on-change method for this
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
//var issuedDate=new GlideDateTime(g_form.getValue('u_issued_date'))
//var issuedDate=g_form.getValue('u_issued_date')
alert(issuedDate)
var gdt = new GlideDateTime(issuedDate);
gdt.addDays(10)
g_form.setValue('u_due_date',gdt);
}
I am getting an error GlideDateTime is not defined function ().How can I achieve this? Is there any other way?
GlideDateTime is not available on client side. For simple operation like the one you are having you can use javascript Date object. Which is pain to format, but doable, example:
var date = new Date(g_form.getValue('u_issued_date'));
date.setDate(date.getDate() + 10); //add 10 days
g_form.setValue('u_due_date', formatDate(date));
function formatDate (date) {
return date.getFullYear() + '-' +
leadingZero(date.getMonth() + 1) + '-' +
leadingZero(date.getDate()) + ' ' +
date.getHours() + ':' +
date.getMinutes() + ':' +
date.getSeconds();
}
function leadingZero (value) {
return ("0" + value).slice(-2);
}
For more complicated operation you would wish GlideDateTime you will have to use GlideAjax, that will do operations on server side, and provide result.

How to deserialize an array using c# dynamics?

I am trying to deserialize the following JSON to an array using C# dynamics:
[
{
"itemId":"15",
"quantity":101,
"eventTimestamp":"00000000-0000-0000-0000-000000000000",
"salesChannel":"1",
"unlimitedQuantity":false
},
{
"itemId":"15",
"quantity":101,
"eventTimestamp":"00000000-0000-0000-0000-000000000000",
"salesChannel":"2",
"unlimitedQuantity":false
}
]
I have already tried two different approaches, without success:
dynamic itemsBalance = JObject.Parse(content);
and
var itemBalanceType = new {
itemId = "", quantity = 0, eventTimestamp = "", salesChannel = ""
};
var itemsBalance = JsonConvert.DeserializeAnonymousType(content, itemBalanceType);
I am currently using C# dynamics with all other deserializations, and would not like to create classes for each response.
Is there any way to do this ?
Thanks
I found a solution:
JArray itemsBalance = JArray.Parse(content);
if (itemsBalance != null)
{
for (int i = 0; i < itemsBalance.Count; i++)
{
string itemBalanceJSON = itemsBalance[i].ToString();
dynamic itemBalance = JObject.Parse(itemBalanceJSON);
lbxResponse.Items.Add(itemBalance.itemId + " - " + itemBalance.salesChannel +": " + itemBalance.quantity.ToString());
}
}
Should there be any better, please let me know...
You could do it with less amount of code:
dynamic result = JsonConvert.Deserialize(content);
foreach(var entry in result)
{
lbxResponse.Items.Add(entry.itemId + " - " + entry.salesChannel + ": " + entry.quantity);
}

need to download files from client rather than server using asp.net

I am downloading data from yahoo stocks using the Web.DownloadString(); the site will have multiply users so I need to have the client send the download request rather than the server to avoid getting blocked from sending too many request from the servers Ip address. I can't find a way to run it on the client side and am looking for assistance making it run from client rather than server.
below is a poorly formatted function that I plan to clean up that I am using right now
I plan only do use the part required to get the data run client side and the rest run server I have just yet to clean up my code.
Public void DownloadData()
{
string csvData = null;
string month1 = Convert.ToString(DropDownList1.SelectedIndex);
string month2 = Convert.ToString(DropDownList2.SelectedIndex);
string Temp = "http://ichart.finance.yahoo.com/table.csv?s=" + SymbolName.Text + "&d=" + month2 + "&e=" + TextBox3.Text + "&f=" + TextBox4.Text + "&g=d&a=" + month1 + "&b=" + TextBox1.Text + "&c=" + TextBox2.Text + "&ignore=.csv";
string FileRead;
List<string> Remove1 = new List<string>();
string path = System.AppDomain.CurrentDomain.BaseDirectory;
using (WebClient web = new WebClient())
{
try
{
csvData = web.DownloadString(Temp);
}
catch
{
}
}
if (csvData != null && csvData != "")
{
File.WriteAllText(path + "\\MyTest.txt", csvData);
}
System.IO.StreamReader file = new System.IO.StreamReader(path + "\\MyTest.txt");
while ((FileRead = file.ReadLine()) != null) //reads from file
{
Remove1.Add(FileRead);
}
file.Close();
csvData = csvData.Replace("Date,Open,High,Low,Close,Volume,Adj Close", "");
List<stock> prices = YahooFinance.Parse(csvData);
double Lowest = 0;
foreach (stock price in prices) // finds lowest value to addjust priceing
{
if (Lowest == 0)
{
Lowest = Convert.ToDouble(price.low);
}
if (Lowest > Convert.ToDouble(price.low))
{
Lowest = Convert.ToDouble(price.low);
}
}
// new double[] { Convert.ToDouble(price.low), Convert.ToDouble(price.high), Convert.ToDouble(price.Open), Convert.ToDouble(price.close) }
Chart1.ChartAreas[0].AxisX.Interval = 2;
Chart2.ChartAreas[0].AxisX.Interval = 2;
Chart1.ChartAreas[0].AxisX.Maximum = prices.Count + 20;
Chart1.ChartAreas[0].AxisY.Minimum = Lowest - 3;
foreach (stock price in prices)
{
Chart1.Series[0].Points.AddXY(price.date, Convert.ToDouble(price.low), Convert.ToDouble(price.high), Convert.ToDouble(price.Open), Convert.ToDouble(price.close));
Chart2.Series[0].Points.AddXY(price.date, Convert.ToDouble(price.Volume));
}
}
`

LINQ to SQL Ordering from external method

It seem to me that this was hard...
var MostRated = (from p in db.Posts
let AverageRating = CalculateAverageRatingFromPost(p)
where p.PostStatus == Convert.ToInt32(PostStatusEnum.Published.Value) && p.IsDeleted == false
orderby p.PublishedDate descending
select new
{
PostUrl = Common.PostUrl(p.Section.Name, p.Permalink),
Title = Common.TrimString(p.Title, 50),
Excerpt = Common.TrimString(p.Excerpt, 80),
AverageRate = CalculateAverageRating((from pr in db.Ratings
where pr.ObjectType == Convert.ToInt32(ObjectTypeEnum.Post.Value) && pr.ObjectID == p.ID
select pr).SingleOrDefault()),
PublishedDate = new DateHelper().DateTimeInWords(p.PublishedDate.Value)
}).OrderByDescending(o => o.AverageRate).Take(5).ToList();
and the other method is
private Decimal CalculateAverageRating(Rating pr)
{
if (pr != null)
{
Decimal Average = ((1 * (Decimal)pr.Star1) + (2 * (Decimal)pr.Star2) + (3 * (Decimal)pr.Star3) + (4 * (Decimal)pr.Star4) + (5 * (Decimal)pr.Star5)) / ((Decimal)pr.Star1 + (Decimal)pr.Star2 + (Decimal)pr.Star3 + (Decimal)pr.Star4 + (Decimal)pr.Star5);
return Average;
}
else
{
return 0;
}
}
I get this run time error "no supported translation to SQL".
What i want is to get lists of the posts, and do a small quick calculations of the rating and then sort those from highest to low and take 5 posts only.
Thanks
I haven't tested this, but try defining the function as an Expression object.
Expression<Rating, Decimal> CalculateAverageRating =
pr => (Decimal)(
pr == null ? 0 :
(pr.Star1 + 2*pr.Star2 + 3*pr.Star3 + 4*pr.Star4 + 5*pr.Star5)
/(pr.Star1 + pr.Star2 + pr.Star3 + pr.Star4 + pr.Star5));

Resources