Input string was not in a correct format - sql

I have a class in which i calculate the credit limit left. And return the values through a DataTable. But in the IF condition it is throwing error 'Input string was not in a correct format.', Whats wrong in the code.
Please Help,
Thanks in Advance
string cmd2 = "select sum(FacilityAmountINR),sum(LCAmountPaid) from FacilityIssueDetails where Status='open' AND LCType = 'Inland LC'";
DataTable a = DbRdRw.SqlDbRead(cmd2, "FacilityIssueDetails");
decimal AvailInlandLC = 0;
string totcred = Convert.ToString(a.Rows[0]["Column1"]);
string totpaid = Convert.ToString(a.Rows[0]["Column2"]);
if (totcred != null && totpaid != null)
{
decimal TotalAmountCredit = Convert.ToDecimal(totcred);// error here
decimal TotalAmountpaid = Convert.ToDecimal(totpaid); // error here
AvailInlandLC = InlandLC - TotalAmountCredit + TotalAmountpaid;
}
//*************************************************************************
DataTable AvailableLimitTable = new DataTable();
AvailableLimitTable.Columns.Add("LCType",typeof (string));
AvailableLimitTable.Columns.Add("TotalLimit",typeof (decimal));
AvailableLimitTable.Columns.Add("AvailableLimit",typeof (decimal));
DataRow dr = AvailableLimitTable.NewRow();
dr["LCType"] = "Inland LC";
dr["TotalLimit"] = InlandLC;
dr["AvailableLimit"] = AvailInlandLC;
AvailableLimitTable.Rows.InsertAt(dr, 0);

Try to change the if loop condition if you are getting NULL value from database...
if (totcred != null && totpaid != null && totcred != "Null" && totpaid != "Null" )
{
decimal TotalAmountCredit = Convert.ToDecimal(totcred);// error here
decimal TotalAmountpaid = Convert.ToDecimal(totpaid); // error here
AvailInlandLC = InlandLC - TotalAmountCredit + TotalAmountpaid;
}

Related

ODBC-2028 Error SAP B1

I am trying to add a purchase order by DI API for SAP B1. My code is working on my client but I tried it as an addon on another company that has different data. And it gives the error: "No matching records found(ODBC-2028)". Here is a part of my code:
public void createPOrderFor(int id,
string itemCode,
string itemName,
int qty,
int satisSip,
string cardCode,
string cardName,
string releaseDate)
{
SAPbobsCOM.Documents BO_item;
BO_item = (SAPbobsCOM.Documents)getCompany().GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseOrders);
base.doConnectionInfo();
server = base.server;
database = base.database;
user = base.user;
pass = base.pass;
string year = releaseDate.Substring(0, 4);
string month = releaseDate.Substring(4, 2);
string day = releaseDate.Substring(6, 2);
releaseDate = year + "-" + month + "-" + day;
BO_item.Lines.ItemCode = itemCode;
BO_item.Lines.ItemDescription = itemName;
BO_item.Lines.Quantity = qty;
BO_item.Lines.ShipDate = DateTime.Parse(releaseDate);
BO_item.Lines.UserFields.Fields.Item("U_SatisSip").Value = satisSip;
BO_item.Lines.Add();
BO_item.Comments = satisSip + " numaralı satış siparişine istinaden";
BO_item.CardCode = cardCode;
BO_item.CardName = cardName;
BO_item.NumAtCard = "";
BO_item.Series = 13;//birincil
//BO_item.Segment -- it is read only.
BO_item.TaxDate = DateTime.Now;
BO_item.DocDate = DateTime.Now;
BO_item.DocDueDate = DateTime.Parse(releaseDate);
BO_item.SalesPersonCode = 4;//default Hakan Yılmaz
BO_item.DocumentsOwner = 4;
BO_item.DiscountPercent = 0.0;
BO_item.Address2 = "TURKEY";
BO_item.Address = "";
BO_item.TransportationCode = 1;
BO_item.AgentCode = null;
BO_item.JournalMemo = "Satınalma siparişleri - " + cardCode;
BO_item.GroupNumber = 1;//net30
BO_item.PaymentMethod = null;
BO_item.Project = null;
BO_item.UserFields.Fields.Item("U_SatSip").Value = satisSip;
var retVal = BO_item.Add();
int errorCode = 0;
string errMsg = "";
if (retVal != 0)
{
getCompany().GetLastError(out errorCode, out errMsg);
SAPbouiCOM.Framework.Application.SBO_Application.StatusBar.SetText("Error: " + errMsg , SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
}
First of all remove all null fields. If there are DI Object fields that you cannot provide a value for, you should not set them equal to null.
BO_item.AgentCode = null;
BO_item.PaymentMethod = null;
BO_item.Project = null;
Just remove them completely. Also instead of Date.Time.Now try setting a date in this format: 20180531 for all date fields as a test.
BO_item.DocDate = "20180531"
If it returns the same error, attempt to test this in an SAP Business One Demo Database (can be obtained from sap partneredge).
Also, Ensure the User Defined Fields you are trying to set values for exist in your new customer's database
let me know how it works for you so we can continue.

How to handle null data when null is returned

I have the code below that is returning data for me. If result equals "Success" then there is data. I am not getting any data
back but getting a null. Data is diplayed on a web grid and when the webgrid sees that the data is Null, the page crashes.
How can I handle null from here?
public Chemicalsdetails GetChemicalDataGeneratedForMonth(string branchcode, string departmentnumber, string previousMonth, string currentMonth)
{
string result = string.Empty;
result = _chemmeterprocessor.CopyPreviousMonthData(branchcode, departmentnumber, previousMonth, currentMonth);
Chemicalsdetails objChem = null;
if (result == "Success")
{
objChem = new Chemicalsdetails();
List<Chemicaltransactiondto> objAllData = new List<Chemicaltransactiondto>();
objAllData = _chemmeterprocessor.GetAllChemicalEntries(branchcode, departmentnumber, currentMonth);
objChem.GetAllChemicalsInformation = objAllData;
}
else
{
Chemicalsdetails objNoData = new Chemicalsdetails();
}
return objChem;
}
Check for null after you retrieve your data.
public Chemicalsdetails GetChemicalDataGeneratedForMonth(string branchcode, string departmentnumber, string previousMonth, string currentMonth)
{
string result = string.Empty;
result = _chemmeterprocessor.CopyPreviousMonthData(branchcode, departmentnumber, previousMonth, currentMonth);
Chemicalsdetails objChem = null;
List<Chemicaltransactiondto> objAllData = new List<Chemicaltransactiondto>();
//****Check for "Success"
if (result == "Success")
{
//****Retrieve chemical data
objAllData = _chemmeterprocessor.GetAllChemicalEntries(branchcode, departmentnumber, currentMonth);
//****End Retrieve chemical data
}
//****Check for non-null data.
if ((result == "Success") && (objAllData!=null))
{
objChem = new Chemicalsdetails();
objChem.GetAllChemicalsInformation = objAllData;
}
else
{
Chemicalsdetails objNoData = new Chemicalsdetails();
}
return objChem;
}

How to write a query in groovy while the field value can be null or not null

public boolean isDuplicateAccountMaterChartOfAccountsBySQL(MasterChartOfAccounts masterChartOfAccounts) {
String query = """
SELECT
COUNT(mcoa.id) as mcoaCount
FROM master_chart_of_accounts as mcoa
WHERE
mcoa.parent_account_id = ${masterChartOfAccounts.parentAccount?.id}
AND mcoa.account_code = '${masterChartOfAccounts.accountCode}'
AND mcoa.country_id = ${masterChartOfAccounts.countryId}
AND mcoa.account_status_id = ${AccountsConstants.DOMAIN_STATUS_ACTIVE}
"""
Sql db = new Sql(dataSource)
List<GroovyRowResult> resultList = db.rows(query)
return resultList.get(0).mcoaCount
}
here the field parent_account_id can be NULL or can be Not Null . But sql query doesn't work for a null value in this way . we have to write
where mcoa.parent_account_id IS NULL .
So what can i do in the situation where the field can be NULL or Not NULL
#Transactional(readOnly = true)
public boolean isDuplicateAccountMaterChartOfAccountsBySQL(MasterChartOfAccounts masterChartOfAccounts) {
String query = """
SELECT
COUNT(mcoa.id) as mcoaCount
FROM master_chart_of_accounts as mcoa
WHERE
mcoa.account_code = '${masterChartOfAccounts.accountCode}'
AND mcoa.country_id = ${masterChartOfAccounts.countryId}
AND mcoa.account_status_id = ${AccountsConstants.DOMAIN_STATUS_ACTIVE}
"""
if (masterChartOfAccounts.parentAccount?.id) {
query += " AND mcoa.parent_account_id = ${masterChartOfAccounts.parentAccount?.id}"
}
Sql db = new Sql(dataSource)
List<GroovyRowResult> resultList = db.rows(query)
return resultList.get(0).mcoaCount
}
Yes I solved it. :D

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'

I'm trying to assign the value to dtLancamentoReceitaDespesaDataVencimento and the condition is: if value dtLancamentoReceitaDespesaDataPagamento is null assigns the value dtLancamentoReceitaDespesaDataVencimento but assigns the value of dtLancamentoReceitaDespesaDataPagamento.
But is giving the following error:
Can not implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)
dtLancamentoReceitaDespesaDataVencimento =
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento == null ?
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataVencimento :
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento
LINQ:
public List<LancamentoReceitaDespesa> GetLancamentoReceitaDespesaByintCodigoGrupoUsuarioByParametro(int intCodigoGrupoUsuario, int mes, int ano)
{
return (from lancamentoReceitaDespesa in _DatabaseContext.LancamentoReceitaDespesa
where lancamentoReceitaDespesa.intCodigoGrupoUsuario == intCodigoGrupoUsuario &&
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataVencimento.Month == mes &&
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataVencimento.Year == ano
select new LancamentoReceitaDespesa
{
intLancamentoReceitaDespesaId = lancamentoReceitaDespesa.intLancamentoReceitaDespesaId,
intCategoriaId = lancamentoReceitaDespesa.intCategoriaId,
strLancamentoReceitaDespesaCartaoCreditoContaBancaria = lancamentoReceitaDespesa.strLancamentoReceitaDespesaCartaoCreditoContaBancaria,
intContaContabilId = lancamentoReceitaDespesa.intContaContabilId,
intFormaPagamentoId = lancamentoReceitaDespesa.intFormaPagamentoId,
intClienteFornecedorId = lancamentoReceitaDespesa.intClienteFornecedorId,
intEventoId = lancamentoReceitaDespesa.intEventoId,
strLancamentoReceitaDespesaDescricao = lancamentoReceitaDespesa.strLancamentoReceitaDespesaDescricao,
strLancamentoReceitaDespesaDocumento = lancamentoReceitaDespesa.strLancamentoReceitaDespesaDocumento,
strLancamentoReceitaDespesaTipoLancamento = lancamentoReceitaDespesa.strLancamentoReceitaDespesaTipoLancamento,
dtLancamentoReceitaDespesaDataVencimento = lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento == null ? lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataVencimento : lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento,
decLancamentoReceitaDespesaValor = lancamentoReceitaDespesa.decLancamentoReceitaDespesaValor,
dtLancamentoReceitaDespesaDataPagamento = lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento,
decLancamentoReceitaDespesaValorPago = lancamentoReceitaDespesa.decLancamentoReceitaDespesaValorPago,
dtLancamentoReceitaDespesaDataRecebimento = lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataRecebimento,
decLancamentoReceitaDespesaValorRecebido = lancamentoReceitaDespesa.decLancamentoReceitaDespesaValorRecebido,
dtLancamentoReceitaDespesaDataCompra = lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataCompra,
intCodigoGrupoUsuario = lancamentoReceitaDespesa.intCodigoGrupoUsuario,
bitLancamentoReceitaDespesaPagarAutomatico = lancamentoReceitaDespesa.bitLancamentoReceitaDespesaPagarAutomatico,
bitLancamentoReceitaDespesaLancamentoPago = lancamentoReceitaDespesa.bitLancamentoReceitaDespesaLancamentoPago,
dtLancamentoReceitaDespesaDataAlteracao = lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataAlteracao,
dtLancamentoReceitaDespesaDataCriacao = lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataCriacao
}).ToList();
}
If dtLancamentoReceitaDespesaDataVencimento is of DateTime type, then just add nullable type Value selector at the end:
dtLancamentoReceitaDespesaDataVencimento =
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento == null ?
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataVencimento :
lancamentoReceitaDespesa.dtLancamentoReceitaDespesaDataPagamento.Value

how to get the xtragrid filtered and sorted datasource?

I have an xtraGrid control (v12.1) binded to a bindingSource, this last gets its data from a LINQ to entities query (EF4.3.1), the end user can filter and sort the gridView, I have a Stimulsoft report that shows the content of the gridView when the user clicks on a PrintListButton, how to get the xtragrid filtered and sorted datasource, in order to attach it to the report?
Thanks.
var data = GetDataView(xtraGridControl1);
report.RegData("List", data.ToTable());
public DataView GetDataView(GridControl gc)
{
DataView dv = null;
if (gc.FocusedView != null && gc.FocusedView.DataSource != null)
{
var view = (ColumnView)gc.FocusedView;
var currentList = listBindingSource.List.CopyToDataTable().DefaultView; //(DataView)
var filterExpression = GetFilterExpression(view);
var sortExpression = GetSortExpression(view);
var currentFilter = currentList.RowFilter;
//create a new data view
dv = new DataView(currentList.Table) {Sort = sortExpression};
if (filterExpression != String.Empty)
{
if (currentFilter != String.Empty)
{
currentFilter += " AND ";
}
currentFilter += filterExpression;
}
dv.RowFilter = currentFilter;
}
return dv;
}
public string GetFilterExpression(ColumnView view)
{
var expression = String.Empty;
if (view.ActiveFilter != null && view.ActiveFilterEnabled
&& view.ActiveFilter.Expression != String.Empty)
{
expression = view.ActiveFilter.Expression;
}
return expression;
}
public string GetSortExpression(ColumnView view)
{
var expression = String.Empty;
foreach (GridColumnSortInfo info in view.SortInfo)
{
expression += string.Format("[{0}]", info.Column.FieldName);
if (info.SortOrder == DevExpress.Data.ColumnSortOrder.Descending)
expression += " DESC";
else
expression += " ASC";
expression += ", ";
}
return expression.TrimEnd(',', ' ');
}