EF inserting values in table failed after some time - c#

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();
}
}

Related

SaveChanges() doesn't insert any records to database

I'm using Entity Framework to add new records to the database, everything goes ok without any errors, but I don't see the new record in the database.
Update code works, but insert code doesn't work. No errors appear, but no records are inserted into the database.
My code :
var DBs2 = ConnectionTools.OpenConn();
DBs2.Configuration.AutoDetectChangesEnabled = false;
DBs2.Configuration.ValidateOnSaveEnabled = false;
var resList = CreatedSerials.Where(u => u.Item4 == VID).ToList();
foreach (var r in resList)
{
// if serial id ==0 => new then add it as new
if ( r.Item7 == 0)
{
try
{
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
ss.Add(purchasesItemSerials);
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
}
else
{
var DBs350 = ConnectionTools.OpenConn();
var UpdateSerial = DBs350.purchases_item_seriels.Find(r.Item7);
UpdateSerial.pitem_ID = pitem_ID;
UpdateSerial.stitems_ID = r.Item1;
UpdateSerial. pmain_ID = PurchasesID;
UpdateSerial.pitem_virtualID = r.Item4;
UpdateSerial.pis_CustomSerial = r.Item2;
UpdateSerial.pis_ExpireDate = r.Item3;
UpdateSerial.pis_Statues = r.Item6;
UpdateSerial.ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID"));
UpdateSerial.Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice"));
DBs350.SaveChanges();
}
}
try
{
DBs2.purchases_item_seriels.AddRange(ss);
DBs2.SaveChanges();
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
I also tried :
DBs2.Configuration.AutoDetectChangesEnabled = true;
DBs2.Configuration.ValidateOnSaveEnabled = true;
but again: no data is inserted, no errors appear
I also tried :
int returnCode = DBs2.SaveChanges();
and returnCode = 0
**I also tried : inserting just a single item then SaveChanges **
// if this serial is new
var NewSerialresList = CreatedSerials.Where(u => u.Item4 == VID && u.Item7 == 0).ToList();
if (NewSerialresList.Count() > 0)
{
var ss = new List<purchases_item_seriels>();
foreach (var r in NewSerialresList)
{
try
{
mrsalesdbEntities DBs002 = new mrsalesdbEntities();
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
//ss.Add(purchasesItemSerials);
DBs002.purchases_item_seriels.Add(purchasesItemSerials);
DBs002.SaveChanges();
}
catch (Exception ex)
{
Msg.Show("", ex.ToString(), 0);
}
}
int CC = ss.Count();
}
i use this function to change the connection variables at run-time :
public static mrsalesdbEntities OpenConn()
{
mrsalesdbEntities MrSalesContext = new mrsalesdbEntities();
MrSalesContext.ChangeDatabase
(
initialCatalog: myconn.database,
port: Convert.ToUInt32( myconn.port),
userId: myconn.uid,
password: myconn.password,
dataSource: myconn.server
);
return MrSalesContext;
}
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
uint port = 3307,
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "mrsalesdbEntities")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new MySqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.Database = initialCatalog;
if ((port) != 0)
sqlCnxStringBuilder.Port = port;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.Server = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
//sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}

Using ffmpeg.autogen, Video is captured from an IP camera , but the audio is not captured, is anything missing in the code?

Here is the code: This is the content of the main of a console
application, the code compiles and runs, the video is captured but not
the audio.
FFmpegBinariesHelper.RegisterFFmpegBinaries();
ffmpeg.av_register_all();
ffmpeg.avcodec_register_all();
ffmpeg.avformat_network_init();
AVFormatContext* context = ffmpeg.avformat_alloc_context();
int video_stream_index = 0;
ffmpeg.av_register_all();
ffmpeg.avcodec_register_all();
ffmpeg.avformat_network_init();
//open rtsp
if (ffmpeg.avformat_open_input(&context, "rtsp://user:pass#IPAddress/axis-media/media.amp?", null, null) != 0)
{
return ;
}
if (ffmpeg.avformat_find_stream_info(context, null) < 0)
{
return;
}
//search video stream
for (int i = 0; i < context->nb_streams; i++)
{
if (context->streams[i]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO)
video_stream_index = i;
}
AVPacket packet;
ffmpeg.av_init_packet(&packet);
//open output file
AVOutputFormat* fmt = ffmpeg.av_guess_format("mp4", null, null);
// AVFormatContext* oc = ffmpeg.avformat_alloc_context();
AVFormatContext* oc = null;
ffmpeg.avformat_alloc_output_context2(&oc, fmt, null, null);
oc->oformat = fmt;
ffmpeg.avio_open2(&oc->pb, "test.mp4", ffmpeg.AVIO_FLAG_WRITE, null, null);
AVStream* stream = null;
int cnt = 0;
//start reading packets from stream and write them to file
ffmpeg.av_read_play(context);//play RTSP
while (ffmpeg.av_read_frame(context, &packet) >= 0 && cnt < 1000)
{//read 100 frames
if (packet.stream_index == video_stream_index)
{//packet is video
if (stream == null)
{//create stream in file
stream = ffmpeg.avformat_new_stream(oc, context->streams[video_stream_index]->codec->codec);
ffmpeg.avcodec_copy_context(stream->codec, context->streams[video_stream_index]->codec);
stream->sample_aspect_ratio = context->streams[video_stream_index]->codec->sample_aspect_ratio;
ffmpeg.avformat_write_header(oc, null);
}
packet.stream_index = stream->id;
ffmpeg.av_interleaved_write_frame(oc, &packet);
cnt++;
}
ffmpeg.av_free_packet(&packet);
ffmpeg.av_init_packet(&packet);
}
ffmpeg.av_read_pause(context);
ffmpeg.av_write_trailer(oc);
ffmpeg.avio_close(oc->pb);
ffmpeg.avformat_free_context(oc);
I found the way to add the code for the audio, and now the audio is copying and in sync with the video. Here is the code:
AVFormatContext* ifcx = null;
AVCodecContext* v_iccx = null;
AVCodec* v_icodec = null;
AVStream* v_ist = null;
int v_index;
AVCodecContext* a_iccx = null;
AVCodec* a_icodec = null;
AVStream* a_ist = null;
int a_index;
DateTime timenow, timestart;
AVFormatContext* ofcx;
AVOutputFormat* ofmt;
AVStream* ost;
AVPacket packet;
string sFileInput;
string sFileOutput;
sFileInput = rtspUrl;
var startNumber = 0;
var filePrefix = "camera" + cameraId;
// create folder if not exist
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
}
var files = Directory.GetFiles(destinationFolder, "*" + filePrefix + "*");
if (files.Any())
{
var lastFile = files.Last();
var temp = lastFile.Substring(lastFile.Length - 7, 3);
if (int.TryParse(temp, out startNumber))
{
startNumber++;
}
}
string NextFile = string.Format("{0}\\{1}-{2:000}.mp4", destinationFolder, filePrefix, startNumber);
//EventLog.WriteEntry(sSource, "Capturing " + NextFile );
sFileOutput = NextFile;
FFmpegBinariesHelper.RegisterFFmpegBinaries();
// Initialize library
ffmpeg.av_log_set_level(ffmpeg.AV_LOG_DEBUG);
ffmpeg.av_register_all();
ffmpeg.avcodec_register_all();
ffmpeg.avformat_network_init();
//
// Input
//
AVFormatContext** tmpIfcx = &ifcx;
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
var task = new Task<int>(() => Avformat_open_input_async(tmpIfcx, sFileInput),ct);
task.Start();
task.Wait(2000);
if (!task.IsCompleted)
{
ts.Cancel();
//EventLog.WriteEntry(sSource, "Waiting on task Avformat_open_input_async ", EventLogEntryType.Warning);
task.Wait(2000);
//EventLog.WriteEntry(sSource, "Timeout callling " + sFileInput, EventLogEntryType.Error);
return;
}
var result = task.Result;
//open rtsp
// ifcx = tmpIfcx;
if (result != 0)
{
EventLog.WriteEntry(sSource, "ERROR: Cannot open input file " + sFileInput, EventLogEntryType.Error);
return;
}
if (ffmpeg.avformat_find_stream_info(ifcx, null) < 0)
{
EventLog.WriteEntry(sSource, "ERROR: Cannot find stream info\n", EventLogEntryType.Error);
ffmpeg.avformat_close_input(&ifcx);
return;
}
//search video stream
v_index = -1;
a_index = -1;
for (int ix = 0; ix < ifcx->nb_streams; ix++)
{
if (ifcx->streams[ix]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO)
{
v_ist = ifcx->streams[ix];
v_icodec = ifcx->video_codec;
v_index = ix;
v_iccx = ifcx->streams[ix]->codec;
}
if (ifcx->streams[ix]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_AUDIO)
{
a_ist = ifcx->streams[ix];
a_icodec = ifcx->video_codec;
a_index = ix;
a_iccx = ifcx->streams[ix]->codec;
}
}
if (v_index < 0)
{
EventLog.WriteEntry(sSource, "ERROR: Cannot find input video stream\n",EventLogEntryType.Error);
ffmpeg.avformat_close_input(&ifcx);
return;
}
//
// Output
//
//open output file
ofmt = ffmpeg.av_guess_format(null, sFileOutput, "mp4");
// ffmpeg.format
ofcx = ffmpeg.avformat_alloc_context();
ofcx->oformat = ofmt;
ffmpeg.avio_open(&ofcx->pb, sFileOutput, ffmpeg.AVIO_FLAG_WRITE);
// Create output stream
ost = ffmpeg.avformat_new_stream( ofcx, (AVCodec *) v_iccx->codec );
AVStream* a_ost = ffmpeg.avformat_new_stream(ofcx, (AVCodec*)a_iccx->codec);
//ost = ffmpeg.avformat_new_stream(ofcx, ifcx->video_codec);
ffmpeg.avcodec_copy_context(ost->codec, v_iccx);
ffmpeg.avcodec_copy_context(a_ost->codec, a_iccx);
ffmpeg.avcodec_open2(v_iccx, v_icodec, null);
ffmpeg.avcodec_open2(a_iccx, a_icodec, null);
// Assume r_frame_rate is accurate
var avRational = new AVRational();
avRational.den = ost->r_frame_rate.den * 2;
avRational.num = ost->r_frame_rate.num ;
var aaRational = new AVRational();
aaRational.den = a_ost->r_frame_rate.den ;
aaRational.num = a_ost->r_frame_rate.num ;
ost->r_frame_rate = avRational;
ost->avg_frame_rate = ost->r_frame_rate;
ost->time_base = av_inv_q(ost->r_frame_rate);
ost->codec->time_base = ost->time_base;
a_ost->r_frame_rate = aaRational;
a_ost->avg_frame_rate = a_ost->r_frame_rate;
a_ost->time_base = av_inv_q(a_ost->r_frame_rate);
a_ost->codec->time_base = a_ost->time_base;
ffmpeg.avformat_write_header(ofcx, null);
//start reading packets from stream and write them to file
ffmpeg.av_dump_format(ifcx, 0, ifcx->filename.ToString(), 0);
ffmpeg.av_dump_format(ofcx, 0, ofcx->filename.ToString(), 1);
timestart = timenow = DateTime.Now;
ffmpeg.av_init_packet(&packet);
if (segmentLength == 0)
segmentLength = 15;
var dateToEnd = DateTime.Now.AddMinutes(segmentLength);
//EventLog.WriteEntry(sSource, "date to end capture " + dateToEnd.ToString());
while ( (dateToEnd - DateTime.Now).TotalMinutes > 0 && IsCapturing)
{
if (endDateTime.HasValue && DateTime.Compare(DateTime.Now, endDateTime.Value) >= 0)
{
ffmpeg.av_packet_unref(&packet);
ffmpeg.av_init_packet(&packet);
IsCapturing = false;
break;
}
int readFrame = -1;
try
{
readFrame = ffmpeg.av_read_frame(ifcx, &packet);
}
catch(Exception ex)
{
EventLog.WriteEntry(sSource, $"Error av_read_frame {ex.ToString()}", EventLogEntryType.Error);
break;
}
if (readFrame < 0)
{
EventLog.WriteEntry(sSource, "reafFrame < 0 " + NextFile, EventLogEntryType.Error);
ffmpeg.av_packet_unref(&packet);
ffmpeg.av_init_packet(&packet);
break;
}
if (packet.stream_index == v_index)
{ //packet is video
packet.stream_index = v_ist->index;
ffmpeg.av_interleaved_write_frame(ofcx, &packet);
}
if (packet.stream_index == a_index)
{ //packet is audio
SetPacketProperties(&packet, a_iccx, a_ist);
ffmpeg.av_interleaved_write_frame(ofcx, &packet);
}
ffmpeg.av_packet_unref(&packet);
ffmpeg.av_init_packet(&packet);
}
ffmpeg.av_read_pause(ifcx);
ffmpeg.av_write_trailer(ofcx);
ffmpeg.avio_close(ofcx->pb);
ffmpeg.avformat_free_context(ofcx);
ffmpeg.avformat_network_deinit();
private unsafe void SetPacketProperties(AVPacket* packet, AVCodecContext* codecContext, AVStream* stream)
{
packet->pts = ffmpeg.av_rescale_q_rnd(packet->pts, codecContext->time_base, stream->time_base, AVRounding.AV_ROUND_NEAR_INF | AVRounding.AV_ROUND_PASS_MINMAX);
packet->dts = ffmpeg.av_rescale_q_rnd(packet->dts, codecContext->time_base, stream->time_base, AVRounding.AV_ROUND_NEAR_INF | AVRounding.AV_ROUND_PASS_MINMAX);
packet->duration = (int)ffmpeg.av_rescale_q(packet->duration, codecContext->time_base, stream->time_base);
packet->stream_index = stream->index;
}

how to get history info from QC using OTA

Below My Code that gets info of Bug history from QC. I have problem with
AuditPropertyFactoryFilter which does not filter. AuditPropertyFactory has more than thousand rows.
If I comment
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text); and uncomment
next line, auditPropertyFactory has several rows only but it isn't filtered as i need.
Can anyone get some advice?
public List<QCBugHistory> retrieveHistoryFromBug(string bugId)
{
List<QCBugHistory> history = new List<QCBugHistory>();
try
{
TDConnection qcConnection = new TDConnection();
qcConnection.InitConnectionEx(qcUrl);
qcConnection.ConnectProjectEx(qcDomain, qcProject, qcLogin);
if (qcConnection.Connected)
{
AuditRecordFactory auditFactory = qcConnection.AuditRecordFactory as AuditRecordFactory;
TDFilter historyFilter = auditFactory.Filter;
historyFilter["AU_ENTITY_TYPE"] = "BUG";
historyFilter["AU_ENTITY_ID"] = bugId;
historyFilter["AU_ACTION"] = "Update";
historyFilter.Order["AU_TIME"] = 1;
historyFilter.OrderDirection["AU_TIME"] = 1;
var auditRecordList = auditFactory.NewList(historyFilter.Text);
log.Info("кол-во в истории " + auditRecordList.Count);
if (auditRecordList.Count > 0)
{
foreach (AuditRecord audit in auditRecordList)
{
QCBugHistory bugHistory = new QCBugHistory();
bugHistory.actionType = audit["AU_ACTION"];
bugHistory.changeDate = audit["AU_TIME"];
AuditPropertyFactory auditPropertyFactory = audit.AuditPropertyFactory;
var changesHistoryFilter = auditPropertyFactory.Filter;
changesHistoryFilter["AP_PROPERTY_NAME"] = "Status";
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text);
//var changesList = auditPropertyFactory.NewList("");
if (changesList.Count > 0)
{
foreach (AuditProperty prop in changesList)
{
//prop.EntityID
if (prop["AP_PROPERTY_NAME"] == "Status")
{
bugHistory.oldValue = prop["AP_OLD_VALUE"];
bugHistory.newValue = prop["AP_NEW_VALUE"];
history.Add(bugHistory);
}
}
}
}
}
}
}
catch (Exception e)
{
log.Error("Проблема соединения и получения данных из QC ", e);
}
return history;
}
Try this (in C#):
1) Having only BUG ID param (BUGID below):
BugFactory bgFact = TDCONNECTION.BugFactory;
TDFilter bgFilt = bgFact.Filter;
bgFilt["BG_BUG_ID"] = BUGID; // This is a STRING
List bugs = bgFilt.NewList();
Bug bug = bugs[1]; // is 1-based
bug.History;
2) Having the Bug object itself, just do:
bug.History;

Is my PLINQ code threadsafe?

I have the following code:
static void Main(string[] args)
{
DateTime currentDay = DateTime.Now;
List<Task> taskList = new List<Task>();
List<string> markets = new List<string>() { "amex", "nasdaq", "nyse", "global" };
Parallel.ForEach(markets, market =>
{
Downloads.startInitialMarketSymbolsDownload(market);
}
);
Console.WriteLine("All downloads finished!");
}
public static void startInitialMarketSymbolsDownload(string market)
{
try
{
object valueTypeLock = new object();
List<string> symbolList = new List<string>() { "GOOG", "YHOO", "AAP" }
var historicalGroups = symbolList.AsParallel().Select((x, i) => new { x, i })
.GroupBy(x => x.i / 100)
.Select(g => g.Select(x => x.x).ToArray());
historicalGroups.AsParallel().ForAll(g => {
lock (valueTypeLock) {
getHistoricalStockData(g, market);
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public static void getHistoricalStockData(string[] symbols, string market)
{
// download data for list of symbols and then upload to db tables
Uri uri;
string url, line;
decimal open = 0, high = 0, low = 0, close = 0, adjClose = 0;
DateTime date;
Int64 volume = 0;
string[] lineArray;
List<string> symbolError = new List<string>();
Dictionary<string, string> badNameError = new Dictionary<string, string>();
System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
Parallel.ForEach(symbols, symbol =>
{
url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=1&c=1900&d=" + (DateTime.Now.Month - 1) + "&e=" + DateTime.Now.Day + "&f=" + DateTime.Now.Year + "&g=d&ignore=.csv";
uri = new Uri(url);
using (ooplesfinanceEntities entity = new ooplesfinanceEntities())
using (WebClient client = new WebClient())
using (Stream stream = client.OpenRead(uri))
using (StreamReader reader = new StreamReader(stream))
{
entity.Database.Connection.Open();
while (reader.EndOfStream == false)
{
line = reader.ReadLine();
lineArray = line.Split(',');
// if it isn't the very first line
if (lineArray[0] != "Date")
{
switch (market)
{
case "amex":
DailyAmexData amexData = new DailyAmexData();
var amexQuery = from r in entity.DailyAmexDatas.AsParallel().AsEnumerable()
where r.Date == date
select new StockData { Close = r.AdjustedClose };
List<StockData> amexResult = amexQuery.AsParallel().ToList();
if (amexResult.AsParallel().Count() > 0) // **never hits this breakpoint line**
{
// add the row to the table if it isn't there
// now checks for stock splits and updates if necessary
if (amexResult.AsParallel().FirstOrDefault().Close != adjClose)
{
// this means there is a stock split so it needs to have the other adjusted close prices updated
amexResult.AsParallel().FirstOrDefault().Close = adjClose;
}
else
{
continue;
}
}
else
{
// set the data then add it
amexData.Symbol = symbol;
entity.DailyAmexDatas.Add(amexData);
}
break;
default:
break;
}
}
}
// now save everything
entity.SaveChanges();
Console.WriteLine(symbol + " added to the " + market + " database!");
}
}
);
}
Everything starts fine and I get no exceptions but I'm getting no results and the code gets stuck one the line that I marked and the memory keeps shooting up. I figured the problem was with the above code because maybe I was doing something wrong. I just don't know where to start as this is my first time dealing with plinq/parallel processing and the tutorials don't show anything this complex.

Issue with +CDS AT COMMAND

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

Categories

Resources