I am working on EF. I am trying to insert into a table, the insert function is in a thread.
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
//string indata = sp.ReadExisting();
Thread.Sleep(50);
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
//Thread.Sleep(100);
Console.WriteLine("Thread Going to Start");
new Thread(() => {
SaveData(finalData);
}).Start(); // starting the thread
port.DiscardOutBuffer();
port.DiscardInBuffer();
}
And this is my save data function
public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
thread = Thread.CurrentThread;
mdc_dbEntities e = new mdc_dbEntities();
var msn = e.mdc_meter_config.Where(m => m.m_hex == sr).Select(s => new { s.msn, s.p_id, s.meter_id }).ToList();
var H = finalData.Substring(0, 2);
using (mdc_dbEntities u = new mdc_dbEntities())
{
foreach (var res in msn)
{
var cust_id = e.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
u.SaveChanges();
}
Console.WriteLine(LineNumber() + "Data Saved");
Thread.Sleep(50);
}
try
{
thread.Abort(); // aborting it after insertion
//Thread.Sleep(50);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
The above code runs for some time, but after that I encountered an error at u.SaveChanges();
System.Data.Entity.Core.EntityException: 'An error occurred while closing the provider connection. See the inner exception for details.'
MySqlException: Fatal error encountered during command execution.
MySqlException: Fatal error encountered attempting to read the resultset.
MySqlException: Reading from the stream has failed.
IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I have looked into each solution and tried them but still unable to resolve this issue. I must be missing something that I don't know.
Update 1 My whole code
Calling constructor
public CommunicationEngine()
{
port.ReadTimeout = 500;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
port.Open();
Console.WriteLine("Port opened successfully");
Console.WriteLine("I am Recieving");
}
Calling handler
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
Thread.Sleep(50);
Console.WriteLine("Bytes are ok..." + port.BytesToRead + " Recieved ");
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
//Thread.Sleep(100);
Console.WriteLine("Thread Going to Start");
try
{
new Thread(() => {
SaveData(finalData);
}).Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
port.DiscardOutBuffer(); port.DiscardInBuffer();
}
Saving data into DB
public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
thread = Thread.CurrentThread;
if (finalData.Length == 138)
{
comm = true;
var H = finalData.Substring(0, 2);
var FC = finalData.Substring(2, 9);
var len = finalData.Substring(10, 2);
var sr = finalData.Substring(12, 12);
var energy_tag = finalData.Substring(24, 4);
var e_val = hexToDec(finalData.Substring(28, 8)) / 10;
var a_curr_tag = finalData.Substring(36, 4);
var a_curr_val = hexToDec(finalData.Substring(40, 8)) / 1000;
var b_curr_tag = finalData.Substring(48, 4);
var b_curr_val = hexToDec(finalData.Substring(52, 8)) / 1000;
var c_curr_tag = finalData.Substring(60, 4);
var c_curr_val = hexToDec(finalData.Substring(64, 8)) / 1000;
var a_vol_tag = finalData.Substring(72, 4);
var a_vol_val = hexToDec(finalData.Substring(76, 8)) / 10;
var b_vol_tag = finalData.Substring(84, 4);
var b_vol_val = hexToDec(finalData.Substring(88, 8)) / 10;
var c_vol_tag = finalData.Substring(96, 4);
var c_vol_val = hexToDec(finalData.Substring(100, 8)) / 10;
var a_pf_tag = finalData.Substring(108, 4);
var a_pf_val = hexToDec(finalData.Substring(112, 4)) / 1000;
var b_pf_tag = finalData.Substring(116, 4);
var b_pf_val = hexToDec(finalData.Substring(120, 4)) / 1000;
var c_pf_tag = finalData.Substring(124, 4);
var c_pf_val = hexToDec(finalData.Substring(128, 4)) / 1000;
var crc = finalData.Substring(132, 4);
var ftr = finalData.Substring(136, 2);
var d_type = "600";
DateTime theDate = DateTime.Now;
string format = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(LineNumber() + "Data Ready to be inserted in DB");
using (mdc_dbEntities u = new mdc_dbEntities())
{
var msnList = u.mdc_meter_config.Where(m => m.m_hex == sr)
.Select(s => new { s.msn, s.p_id, s.meter_id })
.ToList();
foreach (var res in msnList)
{
var cust_id = u.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
try
{
u.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Console.WriteLine(LineNumber() + "Data Saved");
Thread.Sleep(50);
}
else if(finalData.Length == 30)
{
var msn_no = finalData.Substring(12, 12);
mdc_dbEntities p = new mdc_dbEntities();
var update = p.meter_control.Where(c => (c.comm_executed == 0))
.Where(o => (o.m_hex == msn_no))
.SingleOrDefault();
if(update.comm_sent == "Disconnect")
{
update.comm_executed = 1;
update.comm = 0;
p.SaveChanges();
Console.WriteLine("Meter Disconnected....");
}
else if(update.comm_sent == "Connect")
{
update.comm_executed = 1;
update.comm = 1;
p.SaveChanges();
Console.WriteLine("Meter Connected....");
}
comm = true;
}
else
{
comm = true;
}
try
{
thread.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Any help would be highly appreciated.
Executing EF related changes in a manually initiated thread is not a good idea. Try to run the EF changes in the same thread. If you are bothered with processing incoming requests, use Async, and Await feature. I have modified your code to accommodate this feature. Please try this.
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = port.BytesToRead;
//string indata = sp.ReadExisting();
try
{
receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
var finalData = receiveData.Replace("-", "");
Console.WriteLine("Thread Going to Start");
SaveDataAsync(finalData).Wait(); // this call will become sync and runs under main thread.
port.DiscardOutBuffer();
port.DiscardInBuffer();
}
public async Task<bool> SaveDataAsync(string finalData)
{
mdc_dbEntities e = new mdc_dbEntities();
var msn = e.mdc_meter_config.Where(m => m.m_hex == sr).Select(s => new { s.msn, s.p_id, s.meter_id }).ToList();
var H = finalData.Substring(0, 2);
var isSaveSuccess = false;
using (mdc_dbEntities u = new mdc_dbEntities())
{
foreach (var res in msn)
{
var cust_id = e.mdc_meter_cust_rel.Where(m => m.msn == res.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
mdc_meters_data data = new mdc_meters_data()
{
msn = res.msn,
cust_id = cust_id,
device_id = res.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = res.p_id,
};
u.mdc_meters_data.Add(data);
}
isSaveSuccess = (await u.SaveChangesAsync())>0; // if records inserted, the count will be more than 0
}
return isSaveSuccess;
}
}
this is easier to read and may help
saying all this please ensure that you can actually make a connection to the db
double check connectionString
public void SaveData(string finalData)
{
Console.WriteLine(LineNumber() + "Data Transmiting...");
using (mdc_dbEntities dbContext = new mdc_dbEntities())
{
var msnList = dbContext.mdc_meter_config.Where(m => m.m_hex == sr)
.Select(s => new { s.msn, s.p_id, s.meter_id })
.ToList();
//put debug point here and check that msnList is populated
foreach (var item in msnList)
{
//this is slow as it will be a db query for each loop
var cust_id = dbContext.mdc_meter_cust_rel.Where(m => m.msn == item.msn)
.Select(s => s.cust_id)
.FirstOrDefault();
var data = new mdc_meters_data()
{
msn = item.msn,
cust_id = cust_id,
device_id = item.meter_id.ToString(),
kwh = e_val.ToString(),
voltage_p1 = a_vol_val.ToString(),
voltage_p2 = b_vol_val.ToString(),
voltage_p3 = c_vol_val.ToString(),
current_p1 = a_curr_val.ToString(),
current_p2 = b_curr_val.ToString(),
current_p3 = c_curr_val.ToString(),
data_date_time = Convert.ToDateTime(theDate.ToString(format)),
d_type = d_type.ToString(),
pf1 = a_pf_val.ToString(),
pf2 = b_pf_val.ToString(),
pf3 = c_pf_val.ToString(),
p_id = item.p_id,
};
dbContext.mdc_meters_data.Add(data);
}
//depending on how many you added this may take some time.
dbContext.SaveChanges();
}
}
I am running on TestNet. I am trying to add multiple transaction inputs TxIn() so as to spend from these inputs. When I broadcast my transaction, it returns successful but I can't see it on the block-explorer. I have handled a transaction with a single TxIn() and when I broadcast it, it was successful and i could view it on the block-explorer. I have been on this for more than 2 days now. Will greatly appreciate your help guys
var bitcoinPrivateKey = new BitcoinSecret("cNZupUgfs54DmsShwxa1wpomQcszUtuJYFvx9zWPbXrT7KsWtiUd");
var network = bitcoinPrivateKey.Network;
var address = bitcoinPrivateKey.GetAddress();
var client = new QBitNinjaClient(network);
var balance = client.GetBalance(address).Result;
var transactionId = uint256.Parse("06c0aec7543467951abad0c28998a2c1fc1cdc34e01113f8ec1fdb22be854771");
var transactionResponse = client.GetTransaction(transactionId).Result;
var tx = new Transaction();
foreach (var operation in balance.Operations)
{
OutPoint spendOutPoint = null;
var coinsReceived = operation.ReceivedCoins;
foreach (var coin in coinsReceived)
{
if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey)
{
spendOutPoint = coin.Outpoint;
tx.Inputs.Add(new TxIn()
{
PrevOut = spendOutPoint
});
}
}
}
var chimaTestDestinationAddress = new BitcoinPubKeyAddress("mxgN2AiqHjKfGvo6Y57fAe4Y754rPdKf4P");
TxOut chimaTestDestinationAddressTxOut = new TxOut()
{
Value = new Money((decimal)0.50, MoneyUnit.BTC),
ScriptPubKey = chimaTestDestinationAddress.ScriptPubKey
};
TxOut ugoChangeBackTxOut = new TxOut()
{
Value = new Money((decimal)2.98, MoneyUnit.BTC),
ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
};
tx.Outputs.Add(chimaTestDestinationAddressTxOut);
tx.Outputs.Add(ugoChangeBackTxOut);
var msg = "ugo the jedi master";
var msgBytes = Encoding.UTF8.GetBytes(msg);
TxOut txDesc = new TxOut()
{
Value = Money.Zero,
ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(msgBytes)
};
tx.Outputs.Add(txDesc);
tx.Inputs[0].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[1].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[2].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[3].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[4].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Sign(bitcoinPrivateKey, false);
BroadcastResponse broadcast = client.Broadcast(tx).Result;
if (!broadcast.Success)
{
Console.WriteLine("ErrorCode: " + broadcast.Error.ErrorCode);
Console.WriteLine("Error message: " + broadcast.Error.Reason);
}
else
{
Console.WriteLine("Success, you can now checkout the transaction in any block explorer");
Console.WriteLine("Hash: " + tx.GetHash());
}
I am new in stripe, how can we set default payment method in stripe.
And can we pass cardId/sourceId to charge customer along with customerId.
Code:-
private static async Task<string> ChargeCustomer(string customerId)
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
And 1 more question, how to get charge-list, I am using below code but getting exception(conversion error):-
private IEnumerable<StripeCharge> GetChargeList()
{
var chargeService = new StripeChargeService();
return chargeService.List();
}
This is what I ended up doing. Not sure why Stripe Checkout didn't set the card for the subscription setup as the default. Anyway, this fires triggered from the payment_intent.succeeded web hook. Sure there is a better way, but...
var customerService = new CustomerService(Configs.STRIPE_SECRET_KEY);
var c = customerService.Get(pi.CustomerId);
if (!string.IsNullOrEmpty(c.InvoiceSettings.DefaultPaymentMethodId)) {
status = "already has default payment method, no action";
hsc = HttpStatusCode.OK;
return;
}
var paymentMethodService = new PaymentMethodService(Configs.STRIPE_SECRET_KEY);
var lopm = paymentMethodService.ListAutoPaging(options: new PaymentMethodListOptions {
CustomerId = pi.CustomerId,
Type = "card"
});
if (!lopm.Any()) {
status = "customer has no payment methods";
hsc = HttpStatusCode.BadRequest;
return;
}
var pm = lopm.FirstOrDefault();
customerService.Update(pi.CustomerId, options: new CustomerUpdateOptions {
InvoiceSettings = new CustomerInvoiceSettingsOptions {
DefaultPaymentMethodId = pm.Id
}
});
hsc = HttpStatusCode.OK;
return;
We can pass cardId/BankAccountId/TokenId/SourceId in SourceTokenOrExistingSourceId property of StripeChargeCreateOptions,
private static async Task<string> ChargeCustomer(string customerId, string cardId)
{
try
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId,
SourceTokenOrExistingSourceId = cardId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
catch(Exception ex)
{
return "";
}
}
To set/change default payment method:-
public void ChangeDefaultPayment(string customerId, string sourceId)
{
var myCustomer = new StripeCustomerUpdateOptions();
myCustomer.DefaultSource = sourceId;
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Update(customerId, myCustomer);
}
Still looking for how to get charge-list.
This is my publisher. There are two consumers. MailConsumer and SmsConsumer.
using(var bus = RabbitHutch.CreateBus("host=localhost").Advanced) {
var queueName = "my.queue";
var queueName2 = "my.queue2";
var queue = bus.QueueDeclare(queueName);
var queue2 = bus.QueueDeclare(queueName2);
var channel = bus.ExchangeDeclare("MyFanout", ExchangeType.Fanout);
bus.Bind(channel, queue, "sms");
bus.Bind(channel, queue2, "mail");
var input = "";
Console.WriteLine("Enter a message. 'q' to quit.");
while((input = Console.ReadLine()) != "q") {
for(int i = 1; i < 2; i++) {
var message = new Message<TextMessage>(new TextMessage {
Text = input + i
});
bus.Publish(channel, "", false, false, message);
}
}
}
I can subscribe with this code:
using(var bus = RabbitHutch.CreateBus("host=localhost").Advanced) {
var queueName = "my.queue2";
var queue = bus.QueueDeclare(queueName);
bus.Consume(queue, x => x.Add<TextMessage>((message, info) => {
Thread.Sleep(1000);
Console.WriteLine("SMS: {0}", message.Body.Text);
}));
Console.WriteLine("Listening for messages. Hit <return> to quit.");
Console.ReadLine();
}
How can I achieve it via AutoSubscriber? There is no option for Queue Name in AutoSubscriber, there is "Subscription Id"
There's a property on the AutoSubscriber called 'GenerateSubscriptionId', which you can set to generate the subscription id for a consumer:
subscriber.GenerateSubscriptionId = subscriptionInfo =>
{
return "MyApplication:" + subscriptionInfo.ConcreteType.Name);
};
Then the subscription id will be used by the default conventions to generate a queue name.
Update:
I think you can achieve what you want just with normal pub-sub without declaring any queue.
In your publisher you can do this:
var bus = RabbitHutch.CreateBus("host=localhost")
while((input = Console.ReadLine()) != "q") {
for(int i = 1; i < 2; i++) {
var message = new Message<TextMessage>(new TextMessage {
Text = input + i
});
bus.Publish(message);
}
}
Then just create 2 consumers to subscribe to your message, and your message will be handled by both:
class SmsConsumer : IConsume<TextMessage>{
...
}
class LogConsumer : IConsume<TextMessage>{
...
}
and in your startup:
var bus = RabbitHutch.CreateBus("host=localhost")
var subscriber = new AutoSubscriber(bus,"my_applications_subscriptionId_prefix");
subscriber.Subscribe(Assembly.GetExecutingAssembly());
Console.ReadLine()
EasyNetQ will declare the exchange, queues and bindings for you. Just make sure your TextMessage class is in an assembly shared by both projects.
I'm issue when I get +CDS in AT COMMAND throught c# using SerialPort, any times I get this +CDS truncated, example:
+CDS: 25
0002970C91555868047414212181414094882121814140948830
Why I've this problem, why any times work nice?
I'm starting SerialPort:
public PortCOM(string porta)
: base(porta, 115200, Parity.None, 8, StopBits.One)
{
this.StatusPort = StatusPorta.Ready;
this.DiscardNull = true;
this.ReadTimeout = 21000;
this.RtsEnable = true;
this.DtrEnable = true;
this.ReceivedBytesThreshold = 9;
this.NewLine = "\r\n";
this.ReadBufferSize = 1024;
}
public static void TestPort()
{
var p = new PortCom("COM12");
if (!p.IsOpen)
p.Open();
p.StatusPort = StatusPorta.Ready;
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceivedSample);
p.PinChanged += new SerialPinChangedEventHandler(p_PinChanged);
p.ErrorReceived += new SerialErrorReceivedEventHandler(p_ErrorReceived);
p.Disposed += new EventHandler((obj, porta) =>
{
Console.WriteLine(((PortaCOM)obj).ToString());
});
if (Console.ReadKey().Key == ConsoleKey.B)
{
p.Close();
p.Dispose();
}
}
static void p_DataReceivedSample(object sender, SerialDataReceivedEventArgs e)
{
var p = (PortaCOM)sender;
try
{
Console.WriteLine(p.ReadExisting());
var sb = new StringBuilder();
sb.Append(p.ReadExisting());
int y = sb.ToString().IndexOf("\r\n");
var stop = Stopwatch.StartNew();
stop.Start();
while (y == -1)
{
sb.Append(p.ReadExisting());
y = sb.ToString().IndexOf("\r\n");
if (stop.Elapsed.TotalSeconds > 10)
break;
}
stop.Stop();
var _retorno = sb.ToString();
var cmt = regCMT.Match(_retorno);
var succ = regSucess.Match(_retorno);
var report = regStatusReport.Match(_retorno);
var erro = regError.Match(_retorno);
#region Resposta
if (cmt.Success)
{
var smss = new SMS();
var source = cmt.Groups[3].Value;
SMS.Fetch(smss, ref source);
var resposta = new Resposta()
{
Mensagem = smss.Message,
Data = smss.ServiceCenterTimeStamp,
Sender = smss.PhoneNumber,
Operadora = p.OperadoraName.NomeOperadora.ToString()
};
GravaResposta().ToAsync(Scheduler.TaskPool).Invoke(p, cmt.Groups[3].Value);
p.IsError = false;
}
#endregion
#region StatusReport
if (report.Success)
{
RecebeReport(p, report.Groups[2].Value.Trim());
p.IsError = false;
}
#endregion
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
Please I really need help with it, I'm glad for any help!
+cds is alert for incoming message with message location on SIM memeory.
so here its seems in PDU mode data. and it is seems may be flash message content.
Convert the data PDU mode to Text mode to receive message.
review this ATSMS library