Error Using Decimal And Bool - c#

In my syntax below I get an error of
An exception of type 'System.FormatException' occured in mscorlib.dll but was not handled in ther user code
Additional Information: Input string was not in a correct format
And the value being passed that throws the error is 9.7000
And this is my syntax - I have a comment above the line that throws an error
private void calculate()
{
var qtys = val(dropdownlist.SelectedItem.Text) + "|" + val(dropdownlist1.SelectedItem.Text) + "|" + val(dropdownlist2.SelectedItem.Text) ;
var totalitems = dropdownitem.SelectedItem.Text + "|" + dropdownitem1.SelectedItem.Text + "|" + dropdownitem2.SelectedItem.Text + "|" + dropdownitem3.SelectedItem.Text;
var amounts = dropdownamt.SelectedItem.Value + "|" + dropdownamt1.SelectedItem.Value + "|" + dropdownamt2.SelectedItem.Value + "|" + dropdownamt3.SelectedItem.Value;
var totalitems = itemInfo.Split('|');
var qtys = qty.Split('|');
var amounts = amount.Split('|');
for (int i = 0; i < totalitems.Count(); i++)
{
if (totalitems[i] != "" && qtys[i] != "" && qtys[i] != "0")
{
TotalPrice += Math.Round(val(amounts[i]), 2);
TotalTax += Math.Round(val(amounts[i]) * Convert.ToDecimal(0.07), 2);
}
}
}
private decimal val(string p)
{
if (p == null)
return 0;
else if (p == "")
return 0;
//The value of p = 9.7000
return Convert.ToInt16(p);
}

You're trying to return a decimal but calling Convert.ToInt16 try Convert.ToDecimal
Also I would recommend using decimal.TryParse rather than calling Convert directly with some code like this:
public decimal convert(string p)
{
decimal result;
if(decimal.TryParse(p, out result))
return result;
else
return 0;
}

Related

Cannot Access Disposed Object - Xamarin.Forms / FirebaseFirestore, is it bug or my fault?

Hi i am facing issue using Xamarin.Forms with FirebaseFirestore
The code is sometimes throwing "Cannot Access Disposed object" (particularly when it is called second time)
The code is used inside Android Project.
If anyone has experienced this i would like any kind of advices you got.
thanks in advance.
public async Task<ObservableCollection<PortfolioDetails>> GetPortfoliosAsync()
{
ObservableCollection<PortfolioDetails> PortfolioList = new ObservableCollection<PortfolioDetails>();
object _result = await FirebaseFirestore.Instance
.Collection(Firebase.Auth.FirebaseAuth.Instance.CurrentUser.Uid)
.Get();
if (_result is QuerySnapshot docs)
{
foreach (DocumentSnapshot y in docs.Documents)
{
var _tcs = new TaskCompletionSource<PortfolioDetails>();
var secondResult = await FirebaseFirestore.Instance
.Collection(Firebase.Auth.FirebaseAuth.Instance.CurrentUser.Uid)
.Document(y.Id)
.Collection("Transactions")
.Get();
var result = new PortfolioDetails();
if (secondResult is QuerySnapshot _docs)
{
CultureInfo.CurrentCulture = new CultureInfo("en-US", false);
decimal portfolioValue = 0;
decimal portfolioBuyPrice = 0;
foreach (var i in _docs.Documents)
{
portfolioBuyPrice += decimal.Parse(i.GetString("qty")) * decimal.Parse(i.GetString("buyprice"));
switch (i.GetString("type"))
{
case "stock":
var securities = await Yahoo.Symbols(i.Id).Fields(Field.RegularMarketPrice).QueryAsync();
var symbol = securities[i.Id];
portfolioValue += decimal.Parse(symbol[Field.RegularMarketPrice].ToString()) * decimal.Parse(i.GetString("qty"));
break;
case "crypto":
var price = AllClass.Data.Find(x => x.id.Contains(i.Id));
portfolioValue += decimal.Parse(price.current_price) * decimal.Parse(i.GetString("qty"));
break;
}
}
result.Price = "$" + portfolioValue;
if (portfolioValue > 10000 || portfolioValue < -10000)
{
result.Price = "$" + Math.Round(portfolioValue / 1000M, 2) + "K";
}
if (portfolioValue > 1000000 || portfolioValue < -1000000)
{
result.Price = "$" + Math.Round(portfolioValue / 1000000M, 2) + "M";
}
var valueDifference = portfolioValue - portfolioBuyPrice;
var tempValueDifference = valueDifference.ToString();
string valueDifferenceString;
if (valueDifference > 0)
{
result.BuyPrice_Color = "#4bb543";
if (valueDifference > 10000)
{
tempValueDifference = Math.Round(valueDifference / 1000M, 2) + "K";
}
if (portfolioValue > 1000000)
{
tempValueDifference = Math.Round(valueDifference / 1000000M, 2) + "M";
}
valueDifferenceString = "+$" + tempValueDifference;
}
else
{
result.BuyPrice_Color = "#ff0033";
if (valueDifference < -10000)
{
tempValueDifference = Math.Round(valueDifference / 1000M, 2) + "K";
}
if (valueDifference < -1000000)
{
tempValueDifference = Math.Round(valueDifference / 1000000M, 2) + "M";
}
valueDifferenceString = "-$" + tempValueDifference.Replace("-", "");
}
var percentageDifference = Math.Round((portfolioValue - portfolioBuyPrice) / (portfolioBuyPrice / 100), 2);
string percentageDifferenceString;
if (percentageDifference > 0)
{
percentageDifferenceString = "(+" + percentageDifference + "%)";
}
else
{
percentageDifferenceString = "(" + percentageDifference + "%)";
}
result.BuyPrice = valueDifferenceString + " " + percentageDifferenceString;
}
PortfolioDetails PortfolioObj = result;
PortfolioObj.PortfolioName = y.Id;
PortfolioList.Add(PortfolioObj);
}
}
return PortfolioList;
}
The new Instance of the Firebase has sometimes triggered the GC, so before the new instance i handled all my data to C# types, this way, the Java GC wont touch that data.

how to get more than 5000 entities by using Factories GetByFilter method with prestasharp

Library Version:
1.2.9
NuGet Package Url:
https://www.nuget.org/packages/PrestaSharp/1.2.9
Prestashop version:
1.7.7.0
Describe the Bug:
PrestaSharp GetByFilter with pagination always return same entity list
Since ProductFactory's GetByFilter method returns null if there are more than 5000 products that match the filter. I decide to get them by pagination like this
_productFactory.GetIdsByFilter(filter, null, "[" + startingIndex.ToString() + "," + count.ToString() + "]");
but even if startingIndex(because of a loop) changes the result is the same
Full code:
filter.Add("date_upd", "[" + dFrom + "," + dTo + "]");
int i = 0;
List<long> AllProducts = new List<long>();
List<long> products;
while (true) // this loop never breaks
{
int startingIndex = i++ * count;
products = _productFactory.GetIdsByFilter(filter, null, "[" + startingIndex.ToString() + "," + (count).ToString() + "]"); // returns same products in every iteration
if (products?.Any() == true) // to check the list is not empty
{
AllProducts.AddRange(products);
if (products.Count < count)
{
break;
}
}
else
break;
}
You just have to remove the brackets from the 'limit' parameter. It is an error in the Github documentation when they give the example with brackets. Here's an own implementation where I send multiple requests in parallel to speed up the processing, regards.
public async Task<List<PS_Entity>> GetElements(int pageSize = 100) {
try {
var numberOfElements = factory.GetIds().Count;
var numberOfParallelTasks = numberOfElements >= pageSize ? numberOfElements / pageSize : 1;
var loadElementsTasks = Enumerable.Range(0, numberOfParallelTasks).Select(taskNumber => factory.GetByFilterAsync(null, "id_ASC", $"{taskNumber * pageSize},{pageSize}")).ToList();
if (numberOfElements % pageSize != 0) {
var skiped = numberOfParallelTasks * pageSize;
loadElementsTasks.Add(factory.GetByFilterAsync(null, "id_ASC", $"{skiped},{numberOfElements - skiped}"));
}
var elements = (await Task.WhenAll(loadElementsTasks)).SelectMany(elements => elements).ToList();
return elements;
} catch (PrestaSharpException e) {
if ((int)e.ResponseHttpStatusCode == 404)
Console.WriteLine($"No existen {RemoveFactoryFromName(factory)}'s.");
return new List<PS_Entity>();
}
}

NetSuite Web Services Custom Field in Searches

I cant seem to pull the custom field values of a transaction search using Web Services.
searchTransaction.savedSearchId = "2017";
SearchResult result = netsuite.search(searchTransaction);
if(result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if(searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length; i++)
{
TransactionSearchRow transactionRow = (TransactionSearchRow)searchRows[i];
var iid = transactionRow.basic.internalId[0].searchValue;
double amount = transactionRow.basic.amount[0].searchValue;
string custfild = transactionRow.basic.customFieldList[0].scriptId;
Console.WriteLine("\n Transaction ID: " + iid.internalId);
Console.WriteLine("\n Amount: " + amount.ToString());
Console.WriteLine("\n customfield: " + custfield.ToString());
}
}
}
I know that the field is being returned because I can see it in the xml response. And custfield.ToString() does return the internal ID of the custom field.
I just cant seem to get the actual value.
Figured it out, posting in case anyone else has the same question:
searchTransaction.savedSearchId = "2017";
SearchResult result = netsuite.search(searchTransaction);
if(result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if(searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length; i++)
{
TransactionSearchRow transactionRow = (TransactionSearchRow)searchRows[i];
var iid = transactionRow.basic.internalId[0].searchValue;
double amount = transactionRow.basic.amount[0].searchValue;
string custfild = transactionRow.basic.customFieldList[0].scriptId;
SearchColumnStringCustomField custfild = (SearchColumnStringCustomField)transactionRow.basic.customFieldList[0];
Console.WriteLine("\n Transaction ID: " + iid.internalId);
Console.WriteLine("\n Amount: " + amount.ToString());
Console.WriteLine("\n custfild: " + custfild.searchValue);
}
}
}

Search between two dates not working

I have the following code:
var q = context.Fuels.AsQueryable();
if (dateEdit1.EditValue != null && dateEdit2.EditValue != null)
{
q.Where(d => d.FuelDate >= dateEdit1.DateTime && d.FuelDate <= dateEdit2.DateTime);
}
and it's working, it will get all rows in table.
but when I'm using this code:
if (dateEdit1.EditValue != null && dateEdit2.EditValue != null)
{
var r = context.ExecuteStoreQuery<Fuel>(String.Format("SELECT * FROM Fuel WHERE FuelDate BETWEEN '{0}' AND '{1}'",
dateEdit1.DateTime.Year + "-" + dateEdit1.DateTime.Month + "-" + dateEdit1.DateTime.Day,
dateEdit2.DateTime.Year + "-" + dateEdit2.DateTime.Month + "-" + dateEdit2.DateTime.Day));
}
it's working but I need to use the first way to get relations working.
Any idea what is the problem in the first one?
Inside of your if clause, you need to assign it to q, if you don't do that q is just a query for all Fuels
This should work:
q = q.Where(d => d.FuelDate >= dateEdit1.DateTime && d.FuelDate <= dateEdit2.DateTime);

.NET TextBox does not update SelectedText value after calling Select

I have a .NET Winforms-based program I wrote in C# where I programmatically select text within a TextBox using the Select() method. I can see the selected text on the screen and the SelectionLength member reports an accurate amount of selected characters, but the SelectedText member doesn't contain any text:
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
thisTextbox.Focus();
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
What's going on?
Update Nov 16 2013
I am adding additional code per #KingKing's request:
delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
string strLectureText = String.Empty;
strLectureText = thisTextbox.Text;
int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1
// search the rest of the buffer after the currently-selected string to find the next period
int skipLastChar = 0;
// don't include last selected character in search
try
{
if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
{
skipLastChar = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("exception caught! ex=" + ex.Message);
skipLastChar = 0;
}
int indexStart = 0;
if (currentStartPos == 0)
{
indexStart = 0;
}
else
{
indexStart = currentStartPos + 1;
}
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
thisTextbox.Focus();
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
}

Categories

Resources