Unable to get a table data from SAP - c#

This is a c# method that invokes SAP BAPI.
public Message ReleaseBapi(string orderNumber)
{
Message msg = new Message();
DataTable dt = new DataTable();
_ecc = ERPRfcDestination.InitialiseDestination();
try
{
IRfcFunction api = _ecc.Repository.CreateFunction("BAPI_PRODORD_RELEASE");
IRfcTable orderNumTable = api.GetTable("ORDERS");
orderNumTable.Insert();
IRfcStructure ItemData = orderNumTable.CurrentRow;
orderNumber = orderNumber.PadLeft(12,'0');
ItemData.SetValue("ORDER_NUMBER", orderNumber);
api.SetValue("ORDERS", orderNumTable);
BeginContext();
api.Invoke(_ecc);
//EndContext();
IRfcTable detReturnTable = api.GetTable("DETAIL_RETURN");//On this line I am getting RfcInvalidStateException
IRFCToDatatable convertToDT = new IRFCToDatatable();
dt = convertToDT.ToDataTable(detReturnTable, dt);
if (dt.Rows.Count > 0)
{
msg.Msg = "Order number " + orderNumber + " released";
msg.MsgType = "S";
}
else { RollbackAPI(); }
}
catch (Exception ex)
{
msg.MsgType = "D";
msg.Msg = ex.Message;
RollbackAPI();
}
finally
{
EndContext();
}
return msg;
}
I checked every other instances where similar line of code is written and on debugging I found that it works as expected. Above is the only place where I am getting this error although I was able to invoke the Rfc method.

Related

How to decrease message size in signalR?

I am working with siglarR self host service,my problem is message size,i want to decrease size from 1kb to only 30bytes because i am working on stock market service which send data very frequently but message size is low,but signalR takes minimum message size is 1kb ,it takes huge network bandwidth.if you have any solution please tell me.
Message example like '123|234.52|568'
// Please find the updated code below :
application send message to server code
if (IsConnected)
{
try
{
if (Convert.ToBoolean(ConfigurationManager.AppSettings["IsJsonData"].ToString()))
{
var obj = new
{
id = SymbolId,
head = colName_no,
value = string.Format("{0:0.####}", Double.Parse(newValue))
};
_hub.Invoke("ServerAlert", SymbolId, JsonConvert.SerializeObject(obj));
}
else
{
_hub.Invoke("ServerAlert", SymbolId, data);
}
}
catch (Exception ex)
{
GenerateLog(ex.ToString() + " " + JsonConvert.SerializeObject(dtrow), "server hub");
}
}
##server side code##
public async void ServerAlert(string groupName, string message)
{
//await Clients.All.StockAlert(message);
//string Delimiter = ConfigurationManager.AppSettings["SplitMessage"].ToString();
Clients.Group(groupName).GroupStockAlert(message);
}
client side receive message code
objMainForm._hub.On("GroupStockAlert", (x) =>
{
try
{
objMainForm.LastPingDateTime = DateTime.Now;
string[] ChangeData = x.Split(new string[] { objMainForm.Delimeter }, StringSplitOptions.RemoveEmptyEntries);
DataRow[] row = objMainForm.dtOnlineData.Select("SymbolId='" + ChangeData[0] + "'");
int RowIndex = objMainForm.dtOnlineData.Rows.IndexOf(row[0]);
DataTable Dt_ColumnName = objMainForm.dtAllHeaders.Select("RowNo='" + ChangeData[1] + "'").CopyToDataTable();
string exceldata = "t!!" + ChangeData[0] + "!!" + Dt_ColumnName.Rows[0]["Header"].ToString() + "!!" + ChangeData[2];
if (this.InvokeRequired)
this.Invoke(new livedata(this.ProcessServerData), new object[] { RowIndex, Dt_ColumnName.Rows[0]["Header"], ChangeData[2], ChangeData[0] });
ChangeData = null;
row = null;
RowIndex = 0;
}
catch (Exception ex)
{
}
finally
{
GC.SuppressFinalize(this);
}
});
Thanks All

Invalid attempt to read when no data is present. (Sending database info from dataGridView_CellClick to another form)

I have a problem while trying to send elements from dataGridView to the form, where I edit the whole row.
The function catches the error and displays it as "Invalid attempt to read when no data is present", but the problem is that I have rows inserted in the database, so row is not empty.
Here is the code:
private void urediIzbranoKnjigoToolStripMenuItem_Click(object sender, EventArgs e)
{
string naslovKnjige = "";
string avtorKnjige = "";
string datumIzdaje = "";
string kategorijaID = "";
string zalozbaID = "";
string knjiznicaID = "";
string statusID = "";
this.urejanje = false;
try
{
this.stavekSQL = "SELECT naslovKnjige, avtorKnjige, datumIzdaje, kategorijaID, zalozbaID, knjiznicaID, statusID FROM Knjiga WHERE ID=#ID";
this.izvediSQL = new SqlCommand(this.stavekSQL, this.povezavaDB);
this.izvediSQL.Parameters.AddWithValue("#ID", this.zadnjiIzbran);
this.povezavaDB.Open();
this.reader = this.izvediSQL.ExecuteReader();
this.reader.Read();
naslovKnjige = this.reader["naslovKnjige"].ToString();
avtorKnjige = this.reader["avtorKnjige"].ToString();
datumIzdaje = this.reader["datumIzdaje"].ToString();
kategorijaID = this.reader["kategorijaID"].ToString();
zalozbaID = this.reader["zalozbaID"].ToString();
knjiznicaID = this.reader["knjiznicaID"].ToString();
statusID = this.reader["statusID"].ToString();
this.reader.Close();
this.urejanje = true;
}
catch (Exception ex)
{
MessageBox.Show("Napaka pri izvajanju: " + ex.Message);
}
finally
{
this.povezavaDB.Close();
if (this.urejanje)
{
UrediKnjigo uredi = new UrediKnjigo(this, this.zadnjiIzbran, naslovKnjige, avtorKnjige, datumIzdaje, kategorijaID, zalozbaID, knjiznicaID, statusID);
uredi.ShowDialog();
}
}
}

Thread started by windows service stops without error and yet it supposed to run an infinite loop

I am trying to create a windows service that calls a thread in a library. This is all in c#. The library has a function that reads from an oracle database, processes the data, stores it in a SQL Server database and updates the records in the oracle database. I run tests on this and saw that the loop runs about 80,000 times and then without throwing any errors (i even checked the event log) nothing happens. Please help with this
This is the code
Windows Service
protected override void OnStart(string[] args)
{
try
{
base.OnStart(args);
controller = new BillingController();
thread = new Thread(new ThreadStart(controller.dowork));
thread.Start();
AppLogs.LogtoFile("SmartCDRBillingService.log", string.Format("SmartCDRBillingService started successfully"));
}
catch (Exception ex)
{
AppLogs.LogtoFile("SmartCDRBillingService.log", string.Format("Start Service error: {0}: {1}:", ex.Message.ToString(), ex.InnerException));
}
}
Controller
public BillingController()
{
AppConfig.LoadSettings();
}
public void dowork()
{
try
{
BillingQueue nLogic = new BillingQueue();
nLogic.QueueWorkItems();
}
catch (Exception ex)
{
//log
AppLogs.LogtoFile("BillingController.log", string.Format("dowork error: {0}: {1}:", ex.Message.ToString(), ex.InnerException));
}
}
Queue
public void QueueWorkItems()
{
new System.Threading.Thread(new System.Threading.ThreadStart(doQueueWork)).Start();
}
private void doQueueWork()
{
counter = 1;
while (true)
{
counter++;
List<EventUsageObject> eList = new List<EventUsageObject>();
try
{
eList = _osqlcon.getallusageevents();
if (eList.Count == 0)
{
continue;
}
else
{
ProcessUsageRequest(eList);//for Event Usage
}
}
catch (Exception ex)
{
//log the error
AppLogs.LogtoFile("BillingQueue.log", string.Format("doQueueWork error: {0}: {1}:", ex.Message.ToString(), ex.InnerException));
}
}
}
public List<EventUsageObject> getallusageevents()
{
List<EventUsageObject> recobjec = new List<EventUsageObject>();
OracleConnection conn = new OracleConnection();
try
{
conn.ConnectionString = osql.getOracleConnectionString();
conn.Open();
OracleCommand command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
string query = "SMART_DWH_OBJECT.GETALLEVENTSUSAGE";
command.CommandText = query;
OracleParameter myParameter = new OracleParameter("rc", OracleDbType.RefCursor);
command.Parameters.Add("OUT_DATA", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
using (OracleDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.FetchSize = 10000;
while (reader.Read())
{
try
{
EventUsageObject info = new EventUsageObject();
info.CallStart = Convert.ToDateTime(reader["E_TIME"].ToString());
info.CallingMsisdn = reader["ACC_NBR"].ToString();
info.CalledMsisdn = reader["CALLED_MSISDN"].ToString();
info.Re_Id = Convert.ToInt32(reader["RE_ID"].ToString());
info.EventName = reader["EVENT_NAME"].ToString();
info.Duration = Convert.ToInt32(reader["DURATION"].ToString());
info.Duration2 = Convert.ToInt32(reader["DURATION2"].ToString());
info.Duration3 = Convert.ToInt32(reader["DURATION3"].ToString());
info.Duration4 = Convert.ToInt32(reader["DURATION4"].ToString());
info.Uplink = Convert.ToInt32(reader["UPLINK"].ToString());
info.Downlink = Convert.ToInt32(reader["DOWNLINK"].ToString());
info.PriceList = reader["PRICE_LIST"].ToString();
info.Cell_A = reader["CELL_A"].ToString();
info.Cell_B = reader["CELL_B"].ToString();
info.Acct_item_Type_Id1 = Convert.ToInt32(reader["ACCT_ITEM_TYPE_ID1"].ToString());
info.Acct_item_Type_Id2 = Convert.ToInt32(reader["ACCT_ITEM_TYPE_ID2"].ToString());
info.Acct_item_Type_Id3 = Convert.ToInt32(reader["ACCT_ITEM_TYPE_ID3"].ToString());
info.Acct_item_Type_Id4 = Convert.ToInt32(reader["ACCT_ITEM_TYPE_ID4"].ToString());
info.BalanceType1 = reader["BALANCE_TYPE1"].ToString();
info.BalanceType2 = reader["BALANCE_TYPE2"].ToString();
info.BalanceType3 = reader["BALANCE_TYPE3"].ToString();
info.BalanceType4 = reader["BALANCE_TYPE4"].ToString();
string d1 = reader["CHARGE1"].ToString();
string d2 = reader["CHARGE2"].ToString();
string d3 = reader["CHARGE3"].ToString();
string d4 = reader["CHARGE4"].ToString();
info.Charge1 = Convert.ToInt32(reader["CHARGE1"].ToString());
info.Charge2 = Convert.ToInt32(reader["CHARGE2"].ToString());
info.Charge3 = Convert.ToInt32(reader["CHARGE3"].ToString());
info.Charge4 = Convert.ToInt32(reader["CHARGE4"].ToString());
info.Prebalance1 = Convert.ToDouble(reader["PRE_BALANCE1"].ToString());
info.Prebalance2 = Convert.ToDouble(reader["PRE_BALANCE2"].ToString());
info.Prebalance3 = Convert.ToDouble(reader["PRE_BALANCE3"].ToString());
info.Prebalance4 = Convert.ToDouble(reader["PRE_BALANCE4"].ToString());
info.Recstatus = 0;
recobjec.Add(info);
}
catch (Exception ex)
{
continue;
}
}
}
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
AppLogs.LogtoFile("DBAPIError.log", string.Format("DBAPI error on getallusageevents error: {0}: {1}:", ex.Message.ToString(), ex.StackTrace));
}
return recobjec;
}
public void ProcessUsageRequest(List<EventUsageObject> list)
{
try
{
//log the eventusage into the database.
if (list.Count == 0)
//do nothing
return;
else
_mssqlcon.logEventUsage(list, _osqlcon);
}
catch (Exception ex)
{
AppLogs.LogtoFile("BillingQueue.log", string.Format("ProcessUsageRequest error on loggingeventusage: {0}: {1}:", ex.Message.ToString(), ex.InnerException));
}
}
public void logEventUsage(List<EventUsageObject> ilist, DBAPI osql)
{
int counter = 0;
try
{
foreach (EventUsageObject log in ilist)
{
try
{
counter++;
sql.executeNonQueryStoredProcedure("dbo.sp_dwh_eventusage", log.CallStart.ToString(), log.CallingMsisdn, log.CalledMsisdn, log.Re_Id.ToString(),
log.EventName.ToString(), log.Duration.ToString(), log.Duration2.ToString(), log.Duration3.ToString(),
log.Duration4.ToString(), log.Uplink.ToString(), log.Downlink.ToString(), log.PriceList, log.Cell_A,
log.Cell_B, log.Acct_item_Type_Id1.ToString(), log.Acct_item_Type_Id2.ToString(), log.Acct_item_Type_Id3.ToString(),
log.Acct_item_Type_Id4.ToString(), log.BalanceType1, log.Charge1.ToString(), log.BalanceType2, log.Charge2.ToString(),
log.BalanceType3, log.Charge3.ToString(), log.BalanceType4, log.Charge4.ToString(), log.Recstatus.ToString(), log.Prebalance1.ToString(),
log.Prebalance2.ToString(), log.Prebalance3.ToString(), log.Prebalance4.ToString());
string query = "UPDATE dwh_ug_eventusage SET recstatus = 1" +
" WHERE E_TIME = TO_DATE('" + log.CallStart + "', 'MM/DD/YYYY HH:MI:SS PM') AND ACC_NBR = '" + log.CallingMsisdn + "'";
osql.executeNonQueryText(query);
AppLogs.LogtoFile("BillingQueue.log",
string.Format("ProcesssubscriptionRequest has processed: {0} record",
log.Msisdn));
}
catch (SqlException ex)
{
if (ex.Number == 2601)
{
string query = "UPDATE dwh_ug_eventusage SET recstatus = 1" +
" WHERE E_TIME = TO_DATE('" + log.CallStart + "', 'MM/DD/YYYY HH:MI:SS PM') AND ACC_NBR = '" + log.CallingMsisdn + "'";
osql.executeNonQueryText(query);
}
AppLogs.LogtoFile("DBAPIError.log", string.Format("DBAPI error on logEventUsage: {0}: {1}:",
continue;
}
}
}
catch (Exception ex)
{
AppLogs.LogtoFile("DBAPIError.log", string.Format("DBAPI error on logEventUsage: {0}: {1}:",
ex.Message.ToString(), ex.StackTrace));
}
}

Connect to a Webservice - convert C# to PHP code

I have a sample code I got from a documentation provided by a merchant. I think the code is in C#. I need to write a code for PHP but I don't have any idea about C# so I'm having a problem with this. I've tried to write a PHP code for this but it doesn't seem right.
By the way, this is a webservice kind of setup and it uses WCF to expose various endpoints. Here's the endpoint they've provided to me: http://services.scorpion.biz/Public/Leads/ExternalLead.svc
Here's the C# code:
public bool SubmitLead(string contactName, string contactNumber) {
bool outcome = false;
string message = string.Empty;
if (contactNumber.Length <= 9) {
message = "Telephone number is too short";
outcome = false;
} else if (contactNumber.Length > 11) {
message = "Telephone number is too long";
outcome = false;
} else if (contactNumber.Length == 10 && contactNumber[0] != '0') {
message = "Telephone must start with a ZERO";
outcome = false;
} else if (contactNumber.Length == 11 && contactNumber.Substring(0, 2) != "27") {
message = "Telephone must start with a 27";
outcome = false;
} else {
WSExternalLead.LeadRequestMessage request = new
WSExternalLead.LeadRequestMessage();
request.Message = “Your Keyword” + ". Contact Name: " + contactName + ".
Contact Number: " + contactNumber;
request.TelephoneNumber = contactNumber;
request.Network = “IMU”;
request.ReceivedTime = DateTime.Now;
using (WSExternalLead.ExternalLeadClient client = new WSExternalLead.ExternalLeadClient()) {
try {
WSExternalLead.LeadResponseMessage response = null;
response = client.GenerateLead(request);
if (response.Result != true) {
message = "We were unable to process your request at this
time. Error: " + response.ErrorMessage;
outcome = false;
} else {
message = "Thank you for your interest in Scorpion Legal
Protection. We will get back to you shortly.";
outcome = true;
}
} catch (FaultException fx) {
message = "We were unable to process your request at this time.
Fault: " + fx.Message;
outcome = false;
} catch (Exception ex) {
message = "We were unable to process your request at this time.
Exception: " + ex.Message;
outcome = false;
}
}
}
HttpContext.Current.Session["OUTCOME"] = outcome;
HttpContext.Current.Session["MESSAGE"] = message;
return outcome;
}
Here's the PHP code that I've written:
// Read values to variables
$username = $_GET['un'];
$usersurname = $_GET['ul'];
$phonesubmit= $_GET['up'];
$useremail = $_GET['ue'];
$aff_id = $_GET['aff'];
$unique_id = $_GET['uid'];
$rdate = date('m/d/Y G:i:s');
$rdate = date("c", strtotime($rdate));
$wsdlFile = "http://services.scorpion.biz/Public/Leads/ExternalLead.svc?WSDL";
$client = new SoapClient($wsdlFile);
$variables->TelephoneNumber = $phonesubmit;
$variables->Message = "IMU. Name: $username $usersurname. Contact Number: $phonesubmit";
$variables->Network = "IMU";
$variables->ReceivedTime = $rdate;
$result = $client->GenerateLead($variables);
$returnMessage = $result->Result;
$returnMessage = trim($returnMessage);
if ($returnMessage == ""){
$returnMessage = $result->ErrorMessage;
}
Any idea on how to solve this would be greatly appreciated. Thanks.

This IfxTransaction has completed; it is no longer usable

Q:
When I use the transactions ,I'll get the following error on about 1 out of every 100 record.
This IfxTransaction has completed; it
is no longer usable
I can't expect when the error happen or what is the reason of this error.
I try to insert about 607 record in the same transaction.
My code:
public static int InsertGroups(List<Group> groups)
{
DBConnectionForInformix con = new DBConnectionForInformix("");
con.Open_Connection();
con.Begin_Transaction();
int affectedRow = -1;
Dictionary<string, string> groupsParameter = new Dictionary<string, string>();
try
{
foreach (Group a in groups)
{
groupsParameter.Add("id", a.GroupId.ToString());
groupsParameter.Add("name", a.Name);
groupsParameter.Add("studentcount", a.StudentCount.ToString());
groupsParameter.Add("divisiontag", a.DivisionTag.ToString());
groupsParameter.Add("entireclass", a.EntireClass.ToString());
groupsParameter.Add("classid", a.ClassId.ToString());
groupsParameter.Add("depcode", a.DepCode.ToString());
groupsParameter.Add("studycode", a.StudyCode.ToString());
groupsParameter.Add("batchnum", a.BatchNum.ToString());
affectedRow = DBUtilities.InsertEntityWithTrans("groups", groupsParameter, con);
groupsParameter.Clear();
if (affectedRow < 0)
{
break;
}
}
if (affectedRow > 0)
{
con.current_trans.Commit();
}
}
catch (Exception ee)
{
string message = ee.Message;
}
con.Close_Connection();
return affectedRow;
}
public void Begin_Transaction()
{
if (this.connection.State == ConnectionState.Open)
{
this.current_trans = this.connection.BeginTransaction(IsolationLevel.Serializable);
}
}
public static int InsertEntityWithTrans(string tblName, Dictionary<string, string> dtParams, DBConnectionForInformix current_conn)
{
int Result = -1;
string[] field_names = new string[dtParams.Count];
dtParams.Keys.CopyTo(field_names, 0);
string[] field_values = new string[dtParams.Count];
string[] field_valuesParam = new string[dtParams.Count];
dtParams.Values.CopyTo(field_values, 0);
for (int i = 0; i < field_names.Length; i++)
{
field_valuesParam[i] = "?";
}
//----------------------------------------------------------------------------------------------------------------------------------------------
string insertCmd = #"INSERT INTO " + tblName + " (" + string.Join(",", field_names) + ") values (" + string.Join(",", field_valuesParam) + ")";
//----------------------------------------------------------------------------------------------------------------------------------------------
IfxCommand com = new IfxCommand(insertCmd);
for (int j = 0; j < field_names.Length; j++)
{
com.Parameters.Add("?", field_values[j]);
}
try
{
Result = current_conn.Execute_NonQueryWithTransaction(com);
if (current_conn.connectionState == ConnectionState.Open && Result > 0)//OK: logging
{
# region // Log Area
#endregion
}
}
catch (Exception ex)
{
throw;
}
return Result;
}
public int Execute_NonQueryWithTransaction(IfxCommand com)
{
string return_msg = "";
int return_val = -1;
Open_Connection();
com.Connection = this.connection;
com.Transaction = current_trans;
try
{
return_val = com.ExecuteNonQuery();
}
catch (IfxException ifxEx)// Handle IBM.data.informix : mostly catched
{
return_val = ifxEx.Errors[0].NativeError;
return_msg = return_val.ToString();
}
catch (Exception ex)// Handle all other exceptions.
{
return_msg = ex.Message;
}
finally
{
if (!string.IsNullOrEmpty(return_msg))//catch error
{
//rollback
current_trans.Rollback();
Close_Connection();
connectionstate = ConnectionState.Closed;
}
}
return return_val;
}
You seem to be handling errors and rolling back the transaction in two places (in Execute_NonQueryWithTransaction and in InsertGroups.
And the return from Execute_NonQueryWithTransaction is used both to return error codes and to return rows affected. But in InsertGroups it is checked purely as a rows affected.
Could you have an error code from Execute_NonQueryWithTransaction (so transaction rolled back) being treated as success (rows inserted) in InsertGroups and the commit then fails?
Overall the code needs significant cleanup:
A catch block to only throw is pointless and just adds noise.
Just use exceptions for error handling, all normal returns should indicate success.

Categories