asynchronous datagrid view c# - c#

People would like to ask you for help with the following situation.
I have a monitor where I check if certain machines are online. To make this process I have a script running on the machine feeding the database with the current time. Already on the monitor, I have an asynchronous check in Infinite loop to pick up the last updated time of the bank and update my Data Grid View. However I'm having some locking problems in this loop, someone could help follow my code
private void timer1_Tick(object sender, EventArgs e)
{
if (timerExec)
{
timerExec = false;
selectStatusRobos();
}
//timer1.Enabled = false;
}
public async void selectStatusRobos()
{
String Configuracao = "server=;user=midas_Client;password=;database=;port=3306";
string query = "SELECT i.Usuario_meta, i.Nome_robo, i.Simbolo, i.Periodo, i.Status_op, i.Operacao, i.Hora_criacao, c.Id, i.Corretora FROM int00 AS i INNER JOIN cliente00 AS c ON i.Usuario_meta = c.Usuario_meta AND i.Corretora = c.Corretora";
MySqlConnection conexao = new MySqlConnection(Configuracao);
try
{
await conexao.OpenAsync();
MySqlCommand COMANDO = new MySqlCommand(query, conexao);
MySqlDataAdapter adapter = new MySqlDataAdapter(COMANDO);
DataTable status = new DataTable();
await adapter.FillAsync(status);
bool flag_find = false;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
flag_find = false;
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_exclamation_red_46014;
dataGridView1.Rows[i].Cells["Operacao"].Value = Properties.Resources.if_op_null;
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_op_null;
for (int b = 0; b < status.Rows.Count; b++)
{
if (dataGridView1.Rows[i].Cells["Id"].Value.ToString() == status.Rows[b]["Id"].ToString()
&& dataGridView1.Rows[i].Cells["Usuario_meta"].Value.ToString() == status.Rows[b]["Usuario_meta"].ToString()
&& dataGridView1.Rows[i].Cells["Corretora"].Value.ToString() == status.Rows[b]["Corretora"].ToString()
&& dataGridView1.Rows[i].Cells["Nome_robo"].Value.ToString() == status.Rows[b]["Nome_robo"].ToString()
&& dataGridView1.Rows[i].Cells["Simbolo"].Value.ToString() == status.Rows[b]["Simbolo"].ToString().Substring(0, 3)
&& dataGridView1.Rows[i].Cells["Periodo"].Value.ToString() == status.Rows[b]["Periodo"].ToString())
{
flag_find = true;
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
dataGridView1.Rows[i].Cells["Hora_ultima"].Value = status.Rows[b]["Hora_criacao"].ToString();
if (status.Rows[b]["Operacao"].ToString() == "1") // Compra
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_Raise_32535_16;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
else if (status.Rows[b]["Operacao"].ToString() == "2") // Venda
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_Fall_32468_16;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
else
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_op_null;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
if (status.Rows[b]["Status_op"].ToString() == "2") // Off
{
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_power_off_10214;
dataGridView1.Rows[i].Cells["Status_op"].Value = status.Rows[b]["Status_op"].ToString();
}
else if (status.Rows[b]["Status_op"].ToString() == "1") // On
{
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_power_on_10215;
dataGridView1.Rows[i].Cells["Status_op"].Value = status.Rows[b]["Status_op"].ToString();
}
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
//query = "DELETE FROM `int00` WHERE Usuario_meta = #usuario_meta AND Nome_robo = #nome_robo AND Simbolo = #simbolo AND Periodo = #periodo";
//COMANDO.CommandText = query;
//COMANDO.Parameters.Clear();
//COMANDO.Parameters.Add("#usuario_meta", MySqlDbType.VarChar).Value = status.Rows[b]["Usuario_meta"].ToString();
//COMANDO.Parameters.Add("#nome_robo", MySqlDbType.VarChar).Value = status.Rows[b]["Nome_robo"].ToString();
//COMANDO.Parameters.Add("#simbolo", MySqlDbType.VarChar).Value = status.Rows[b]["Simbolo"].ToString();
//COMANDO.Parameters.Add("#periodo", MySqlDbType.VarChar).Value = status.Rows[b]["Periodo"].ToString();
//COMANDO.ExecuteNonQuery();
//break;
}
if (dataGridView1.Rows[i].Cells["Hora_ultima"].Value != null)
{
DateTime t = Convert.ToDateTime(dataGridView1.Rows[i].Cells["Hora_ultima"].Value.ToString());
// if (dataGridView1.Rows[i].Cells["Hora_ultima"].Value.ToString() != status.Rows[b]["Hora_criacao"].ToString())
if (flag_find)
{
DateTime t1 = DateTime.Now;
DateTime t2 = DateTime.Now.AddSeconds(-30);
System.TimeSpan diff2 = t1.Subtract(t);
if (diff2.TotalSeconds >= 15 && diff2.TotalSeconds <= 45)
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_58_62715;
}
else if (diff2.TotalSeconds < 15 && diff2.TotalSeconds >= 0)
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
}
else
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_exclamation_red_46014;
}
}
}
}
}
//frm = this.MdiParent as frmPrincipal;
//SendMessage send = new SendMessage(frm.SetLabel);
//send(DateTime.Now.ToString("HH:mm :ss") + " - Dados Atualizados...", null, null);
conexao.Close();
}
catch (MySqlException ex)
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Tempo limite excedido na seleção", ex.Message + ex.StackTrace, Properties.Resources.if_Close_Icon_Dark_1398917, 15000);
//MessageBox.Show(ex.Message + ex.StackTrace, "Detalhes Exception");
timerExec = true;
}
catch (TimeoutException ex)
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Tempo limite excedido na seleção", ex.Message + ex.StackTrace, Properties.Resources.if_Close_Icon_Dark_1398917, 15000);
timerExec = true;
}
finally
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Dados Atualizados...", null, null, 15000);
conexao.Close();
timerExec = true;
}
}

Related

Excel data reading from Stream and save to the database

In my asp.net MVC application, There is an option to upload data from an excel file. For that, I have used this on my controller.
public ActionResult ImportEmpDetails(HttpPostedFileBase excelFile)
{
try
{
if (excelFile.ContentLength == 0 || excelFile == null)
{
ViewBag.Error = "Please select the excel file";
return View("EmpDetails");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/ExcelFile/" + excelFile.FileName);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelFile.SaveAs(path);
ExcelPath = Server.MapPath("~/ExcelFile/") + path;
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
List<EmpDetailsVM> xcel = new List<EmpDetailsVM>();
for (int i = 2; i <= range.Rows.Count; i++)
{
try
{
EmpDetails emp = new EmpDetails();
int EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 1]).Text);
var EmpId = (from c in db.CreateEmployee where c.EmpNo == EmpNo select c.Id).First();
emp.EmpID = EmpId;
emp.YearOfService = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 2]).Text);
emp.BasicSalary = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 3]).Text);
emp.EmpCatagory = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 4]).Text;
emp.EmpGrade = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 5]).Text;
int SupervisorId = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 6]).Text);
var SupId = (from h in db.CreateEmployee where h.EmpNo == SupervisorId select h.Id).First();
emp.SupervisorId = SupId;
EmpDetailsVM data = new EmpDetailsVM();
data.EmpID = emp.EmpID;
data.YearOfService = emp.YearOfService;
data.BasicSalary = emp.BasicSalary;
data.EmpCatagory = emp.EmpCatagory;
data.EmpGrade = emp.EmpGrade;
data.SupervisorId = emp.SupervisorId;
xcel.Add(data);
}
catch (Exception ex)
{
ViewBag.Error = "Error in " + i + " record";
return View("EmpDetails");
}
}
if (xcel != null)
{
try
{
foreach (var item in xcel)
{
int empID = item.EmpID;
decimal yearOfService = item.YearOfService;
decimal basicSalary = item.BasicSalary;
string catagory = item.EmpCatagory;
string grade = item.EmpGrade;
int supId = item.SupervisorId;
var isEmployeeExists = (from e in dbs.EmpDetails where e.EmpID == empID select e.Id).ToList();
int EmpCount = isEmployeeExists.Count();
if (EmpCount == 0)
{
EmpDetails e = new EmpDetails();
e.EmpID = empID;
e.YearOfService = yearOfService;
e.BasicSalary = basicSalary;
e.EmpCatagory = catagory;
e.EmpGrade = grade;
e.SupervisorId = supId;
dbs.EmpDetails.Add(e);
dbs.SaveChanges();
}
else
{
EmpDetails EmpDetails = dbs.EmpDetails.Where(x => x.EmpID == empID).First();
EmpDetails.YearOfService = yearOfService;
EmpDetails.BasicSalary = basicSalary;
EmpDetails.EmpCatagory = catagory;
EmpDetails.EmpGrade = grade;
EmpDetails.SupervisorId = supId;
db.SaveChanges();
}
}
}
catch (Exception ex)
{
ViewBag.Error = "Error " + ex;
}
TempData["msg"] = "success";
return View("EmpDetails", xcel);
}
else
{
}
return View("EmpDetails");
}
else
{
ViewBag.Error = "Selected excel file not supported";
return View("EmpDetails");
}
}
}
catch (Exception ex)
{
string message = string.Format("<b>Message:</b> {0}<br /><br />", "You do not have access to this view");
message += string.Format("<b>StackTrace:</b> {0}<br /><br />", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>Source:</b> {0}<br /><br />", ex.Source.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>TargetSite:</b> {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
ModelState.AddModelError("Id", message);
}
return View("EmpDetails");
}
This is working properly when I debug the code and run from it using VS. When I applied to the live version, can't upload the excel file there is an exception triggering You do not have access to this view
Want to know how to prevent this or how to do same using stream ?

How to fill entry with missing when nothing was writte in in xamarin app?

I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
collectionPlane.IsVisible = false;
collectionAirline.IsVisible = false;
collectionLivery.IsVisible = false;
collectionRegistration.IsVisible = false;
collectionAirport.IsVisible = false;
try
{
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
if (planeEntry.Text != null && airlineEntry.Text != null)
{
var url = PhotoPick();
int i = 1;
int same = 0;
string fileName = registrationEntry.Text;
for (int b = 1; b <= GetNumberPhotos(); b++)
{
if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
string match = rowData.Registration;
if (fileName == match)
{
same++;
}
}
}
i = 1 + same;
fileName = registrationEntry.Text + "-" + i;
var thumbUrl = CreateThumbnail(await url, fileName);
var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
Airplane airplane = new Airplane()
{
Id = (maxPK == null ? 1 : maxPK.Id + 1),
SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
Plane = planeEntry.Text.ToUpper(),
Airline = airlineEntry.Text,
Livery = liveryEntry.Text,
Registration = registrationEntry.Text.ToUpper(),
Airport = airportEntry.Text.ToUpper(),
Date = datePicker.Date,
Comment = commentEntry.Text,
Url = await url,
ThumbnailUrl = thumbUrl
};
db.Insert(airplane);
await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
planeEntry.Text = "";
airlineEntry.Text = "";
liveryEntry.Text = "";
registrationEntry.Text = "";
airportEntry.Text = "";
commentEntry.Text = "";
}
else
await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
}
catch
{
await DisplayAlert("Error", "Something went wrong", "Try again");
}
}
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.

WPF, C# TPL AggregateException never fired

I am trying to develop a small application with WPF, C#. I encountered a problem when trying to use the library TPL, especially exception handling. The problem is that AggregateException is never captured, and the program displays an exception in the method I passed as a task. here's my code. I removed unnecessary code :
private void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (e == null || processIt == true)
{
TaskInProgress = true;
SBMessage = "Query In progress...";
var uischeduler = TaskScheduler.FromCurrentSynchronizationContext();
var refreshold = Task.Factory.StartNew(() =>
RefreshOldDossierFinancement(DossierFinancementEnteredKey));
refreshold.ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler);
try
{
refreshold.Wait();
}
catch (AggregateException aex) //This Exception is never fired
{
Messenger.Default.Send(new ExceptionMessageRefresh(aex), "DossierFinancement");
}
}
}
private void RefreshOldDossierFinancement(long dfId)
{
TotalContrats = 0.000M;
TotalMefs = 0.000M;
TotalCommandes = 0.000M;
decimal phb = 0.000M;
decimal pctr = 0.000M;
decimal pmef = 0.000M;
PercentageHorsBilan = "(0%)";
PercentageContrats = "(0%)";
PercentageMef = "(0%)";
DossierNumber = "";
using (UnitOfWork cx = new UnitOfWork(_currentLog))
{
// try
{
IDossierFinancementRepository sr = new DossierFinancementRepository(cx, _currentLog);
IDossierFinancementManagementService dfms = new DossierFinancementManagementService(_currentLog, sr);
IDataTraceRepository dtr = new DataTraceRepository(cx, _currentLog);
IDataTraceManagementService dtms = new DataTraceManagementService(_currentLog, dtr);
CurrentDossierFinancement = dfms.FindById(dfId);
//I put this code in comment to force a nullReferenceException exception
/*if (CurrentDossierFinancement == null) //Not Found
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Dossier Financement n° " + dfId.ToString() + " introuvable."),"DossierFinancementError");
else*/
{
//The debugger stops here with NullRefrenceException Exception
// I want this exception to be captured in AggregateException
DossierFinancementEnteredKey = CurrentDossierFinancement.DossierId;
DossierNumber = "N° " + DossierFinancementEnteredKey.ToString();
RequestNature = (CurrentDossierFinancement.InvestmentGoal == 0) ? "Création" : (CurrentDossierFinancement.InvestmentGoal == 1) ? "Renouvellement" : "Extension";
EtatDossier = (CurrentDossierFinancement.Status == 1) ? "En cours" : (CurrentDossierFinancement.Status == 2) ? "Approuvé" : "Rejeté";
if (CurrentDossierFinancement.ClientId != null)
{
CustomerCode = (long)CurrentDossierFinancement.ClientId;
CustomerName = CurrentDossierFinancement.Client.NomCli;
}
else
{
CustomerCode = 0;
if (CurrentDossierFinancement.ClientType == 1)
CustomerName = CurrentDossierFinancement.Name + " " + CurrentDossierFinancement.FirstName;
else
CustomerName = CurrentDossierFinancement.CompanyName;
}
if (CurrentDossierFinancement.Contrat != null)
{
TotalContrats = CurrentDossierFinancement.Contrat.Montant;
TotalHorsBilan = CurrentDossierFinancement.Contrat.Montant;
pctr = Math.Round((TotalContrats / CurrentDossierFinancement.Montant) * 100, 0);
PercentageContrats = "(" + pctr.ToString() + "%)";
if (CurrentDossierFinancement.Contrat.Mefs != null)
{
TotalMefs = CurrentDossierFinancement.Contrat.Mefs.Sum(x => x.Montant);
pmef = Math.Round((TotalMefs / CurrentDossierFinancement.Montant) * 100, 0);
PercentageMef = "(" + pmef.ToString() + "%)";
}
TotalHorsBilan = TotalContrats - TotalMefs;
phb = Math.Round((TotalHorsBilan / CurrentDossierFinancement.Montant) * 100, 0);
PercentageHorsBilan = "(" + phb.ToString() + "%)";
}
//Extraire la trace
List<DataTrace> traceList = dtms.GetTrace(DossierFinancementEnteredKey, "DossierFinancement").ToList();
DataTrace newRecord = traceList.Where(xx => string.Equals(xx.ActionLib, "New", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (newRecord != null)
{
CreatedBy = newRecord.Coduser;
CreatedAt = newRecord.ActionDate.ToString();
}
}
}
/*
catch (Exception ex)
{
throw ex;
}*/
}
}
I tested the following code and it still doesn't work :
Task.Run(() =>
{
RefreshOldDossierFinancement(DossierFinancementEnteredKey);
}
catch (AggregateException aex)
{
Messenger.Default.Send(new ExceptionMessageRefresh(aex), "DossierFinancement");
}}).ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler
);
A simpler approach to using continuations is to use async-await. When we execute a delegate using Task.Run, and want to asynchronously wait for it's completion, we can await it:
private async void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (!processIt)
return;
TaskInProgress = true;
SBMessage = "Query In progress...";
try
{
await Task.Run(() => RefreshOldDossierFinancement(DossierFinancementEnteredKey));
}
catch (Exception e)
{
// Do stuff
}
finally
{
TaskInProgress = false;
}
}
This way, you don't need to explicitly capture the SynchronizationContext, and you don't block the UI thread while the operation is on-going.
Finally i found a solution, I dont know if it is the best.
I modified my code as follows :
private void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (e == null || processIt == true)
{
TaskInProgress = true;
SBMessage = "Query in progress...";
var uischeduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() =>
{
RefreshOldDossierFinancement(DossierFinancementEnteredKey);
}).ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler);
}
}
and i capture the exception in RefreshOldDossierFinancement Method. The trick lies to add a Dispatch.BeginInvoke in code behind of the window.
Here The code of RefreshOldDossierFinancement Method :
private void RefreshOldDossierFinancement(long dfId)
{
TotalContrats = 0.000M;
TotalMefs = 0.000M;
TotalCommandes = 0.000M;
decimal phb = 0.000M;
decimal pctr = 0.000M;
decimal pmef = 0.000M;
PercentageHorsBilan = "(0%)";
PercentageContrats = "(0%)";
PercentageMef = "(0%)";
DossierNumber = "";
using (UnitOfWork cx = new UnitOfWork(_currentLog))
{
try
{
IDossierFinancementRepository sr = new DossierFinancementRepository(cx, _currentLog);
IDossierFinancementManagementService dfms = new DossierFinancementManagementService(_currentLog, sr);
IDataTraceRepository dtr = new DataTraceRepository(cx, _currentLog);
IDataTraceManagementService dtms = new DataTraceManagementService(_currentLog, dtr);
CurrentDossierFinancement = dfms.FindById(dfId);
/*if (CurrentDossierFinancement == null) //Not Found
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Dossier Financement n° " + dfId.ToString() + " introuvable."),"DossierFinancementError");
else*/
{
DossierFinancementEnteredKey = CurrentDossierFinancement.DossierId;
DossierNumber = "N° " + DossierFinancementEnteredKey.ToString();
RequestNature = (CurrentDossierFinancement.InvestmentGoal == 0) ? "Création" : (CurrentDossierFinancement.InvestmentGoal == 1) ? "Renouvellement" : "Extension";
EtatDossier = (CurrentDossierFinancement.Status == 1) ? "En cours" : (CurrentDossierFinancement.Status == 2) ? "Approuvé" : "Rejeté";
if (CurrentDossierFinancement.ClientId != null)
{
CustomerCode = (long)CurrentDossierFinancement.ClientId;
CustomerName = CurrentDossierFinancement.Client.NomCli;
}
else
{
CustomerCode = 0;
if (CurrentDossierFinancement.ClientType == 1)
CustomerName = CurrentDossierFinancement.Name + " " + CurrentDossierFinancement.FirstName;
else
CustomerName = CurrentDossierFinancement.CompanyName;
}
if (CurrentDossierFinancement.Contrat != null)
{
TotalContrats = CurrentDossierFinancement.Contrat.Montant;
TotalHorsBilan = CurrentDossierFinancement.Contrat.Montant;
pctr = Math.Round((TotalContrats / CurrentDossierFinancement.Montant) * 100, 0);
PercentageContrats = "(" + pctr.ToString() + "%)";
if (CurrentDossierFinancement.Contrat.Mefs != null)
{
TotalMefs = CurrentDossierFinancement.Contrat.Mefs.Sum(x => x.Montant);
pmef = Math.Round((TotalMefs / CurrentDossierFinancement.Montant) * 100, 0);
PercentageMef = "(" + pmef.ToString() + "%)";
}
TotalHorsBilan = TotalContrats - TotalMefs;
phb = Math.Round((TotalHorsBilan / CurrentDossierFinancement.Montant) * 100, 0);
PercentageHorsBilan = "(" + phb.ToString() + "%)";
}
//Extraire la trace
List<DataTrace> traceList = dtms.GetTrace(DossierFinancementEnteredKey, "DossierFinancement").ToList();
DataTrace newRecord = traceList.Where(xx => string.Equals(xx.ActionLib, "New", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (newRecord != null)
{
CreatedBy = newRecord.Coduser;
CreatedAt = newRecord.ActionDate.ToString();
}
}
}
catch (Exception ex)
{
//Here i send a message to Window to display The Exception Message in a custom Dialog
Messenger.Default.Send(new ExceptionMessageRefresh(ex), "DossierFinancement");
}
}
}
And finally here The code Behind of The window :
public partial class Dossier : Window
{
public Dossier()
{
InitializeComponent();
Messenger.Default.Register<ExitMessage>(this, "DossierFinancement", (action) => CloseWindow(action));
Messenger.Default.Register<ExceptionMessageRefresh>(this, "DossierFinancement", (action) => ShowExceptionMessage(action));
Messenger.Default.Register<NotificationMessage>(this, "DossierFinancementInfo", (action) => ProcessNotification(action));
Messenger.Default.Register<NotificationMessage>(this, "DossierFinancementError", (action) => ProcessErrorDialogNotification(action));
}
private void ProcessNotification(NotificationMessage action)
{
MessageBox.Show(action.Notification.ToString(), "Information", MessageBoxButton.OK,MessageBoxImage.Information);
}
private void ProcessErrorDialogNotification(NotificationMessage action)
{
MessageBox.Show(action.Notification.ToString(), "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
}
private void CloseWindow(ExitMessage action)
{
this.Close();
Messenger.Default.Unregister<ExitMessage>(this, "DossierFinancement");
}
private void ShowExceptionMessage(ExceptionMessageRefresh obj)
{
//Without the following Call of Dispatcher, An exception "Thread must be STA... will be fired
Dispatcher.BeginInvoke(new Action(() =>
{
UICommon.ShowErrorMessage(obj.ExceptionToRefresh);
}));
}
}
and that's all.
Thanks.

How can we deploy finger print reader to C# web application?

I am developing a payroll system in which the attendance should be recorded from finger print machine.I have installed the SDK software, but I don't know how to deploy this in my web application. Also how can we save the finger print in our database so that we could save the attendance details according to finger print
thanks in advance
Fareeda Hussain
We have a project like this one before. You need an sdk (software development kit) to go to your device. Add that to your project references so you can communicate with it. And I believe there is a sample code in the SDK site that you could find in the case of your finger print reader which you could modify.
Anyway here is our sample code for saving fingerprint directly in the database.
private void SaveButton_Click(object sender, EventArgs e)
{
MemoryStream fingerprintData = new MemoryStream();
Template.Serialize(fingerprintData);
fingerprintData.Position = 0;
BinaryReader br = new BinaryReader(fingerprintData);
Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
//Insert the file into database
SqlConnection cn = new SqlConnection("Data Source=10.115.5.3; Initial Catalog=EnrollmentSampledb;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO tblUser VALUES(#ID_NUMBER, #FIRSTNAME, #LASTNAME, #FINGERPRINT, #DATE_ADDED, #DATE_MODIFIED)", cn);
cmd.Parameters.Add("ID_NUMBER", SqlDbType.NVarChar).Value = tboxIdNum.Text;
cmd.Parameters.Add("FIRSTNAME", SqlDbType.NVarChar).Value = tboxFname.Text;
cmd.Parameters.Add("LASTNAME", SqlDbType.NVarChar).Value = tboxLname.Text;
cmd.Parameters.Add("FINGERPRINT", SqlDbType.Image).Value = bytes;
cmd.Parameters.Add("DATE_ADDED", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("DATE_MODIFIED", SqlDbType.DateTime).Value = DateTime.Now;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
tboxIdNum.Text = "";
tboxFname.Text = "";
tboxLname.Text = "";
}
see also my similar question here for saving fingerprint directly in the database.
region Funsional FingerPrint
protected void ReaderFPMachine()
{
_readerCollection = ReaderCollection.GetReaders();
foreach (Reader Reader in _readerCollection)
{
_fPMachineID = Reader.Description.SerialNumber;
break;
}
this.CheckFingerPrint();
}
protected void CheckFingerPrint()
{
try
{
_finger = null;
_reader = _readerCollection[0];
if (!OpenReader())
{
//this.Close();
}
if (!StartCaptureAsync(this.OnCaptured))
{
//this.Close();
}
}
catch (Exception ex)
{
}
}
private void OnCaptured(CaptureResult captureResult)
{
try
{
_finger = null;
// Check capture quality and throw an error if bad.
if (!CheckCaptureResult(captureResult)) return;
//SendMessage(Action.SendMessage, "A finger was captured.");
DataResult<Fmd> resultConversion = FeatureExtraction.CreateFmdFromFid(captureResult.Data, Constants.Formats.Fmd.ANSI);
if (resultConversion.ResultCode != Constants.ResultCode.DP_SUCCESS)
{
_reset = true;
throw new Exception(resultConversion.ResultCode.ToString());
}
_finger = resultConversion.Data;
_fingerPrintID = Fmd.SerializeXml(_finger);
//MsVisitorHd _msVisitorHd = this._vMSBL.GetSingleMsVisitorHdByFingerPrintID(_fingerXML);
//List<MsVisitorHd> _listMsVisitorHd = this._vMSBL.GetListMsVisitorHd();
bool _exist = false;
//foreach (var _item in _listMsVisitorHd)
//{
// Fmd _fmd = Fmd.DeserializeXml(_fingerPrintID);
// Fmd _fmd2 = Fmd.DeserializeXml(_item.FingerPrintID);
// CompareResult compareResult = Comparison.Compare(_fmd, 0, _fmd2, 0);
// if (compareResult.ResultCode != Constants.ResultCode.DP_SUCCESS)
// {
// _reset = true;
// throw new Exception(compareResult.ResultCode.ToString());
// }
// else
// {
// if (compareResult.Score < (PROBABILITY_ONE / 100000))
// {
// //_visitorExist = new MsVisitorHd();
// //_visitorExist = _item;
// _exist = true;
// break;
// }
// else
// {
// }
// }
//}
if (!CheckCaptureResult(captureResult)) return;
// Create bitmap
foreach (Fid.Fiv fiv in captureResult.Data.Views)
{
this.FingerPictureBox.BackgroundImage = CreateBitmap(fiv.RawImage, fiv.Width, fiv.Height);
}
if (_exist)
{
_fgMember = "Y";
//MessageBox.Show("Sidik jadi terdaftar sebagai " + _visitorExist.VisitorName);
}
else
{
_fgMember = "N";
}
//SendMessage(Action.SendMessage, secondFinger.Bytes.ToString() + "Comparison resulted in a dissimilarity score of " + compareResult.Score.ToString() + (compareResult.Score < (PROBABILITY_ONE / 100000) ? " (fingerprints matched)" : " (fingerprints did not match)"));
//SendMessage(Action.SendMessage, "Place a finger on the reader.");
// count = 0;
//}
}
catch (Exception ex)
{
// Send error message, then close form
//SendMessage(Action.SendMessage, "Error: " + ex.Message);
}
}
public bool OpenReader()
{
_reset = false;
Constants.ResultCode result = Constants.ResultCode.DP_DEVICE_FAILURE;
// Open reader
result = _reader.Open(Constants.CapturePriority.DP_PRIORITY_COOPERATIVE);
if (result != Constants.ResultCode.DP_SUCCESS)
{
MessageBox.Show("Error: " + result);
_reset = true;
return false;
}
return _reset;
}
public void GetStatus()
{
Constants.ResultCode result = _reader.GetStatus();
if ((result != Constants.ResultCode.DP_SUCCESS))
{
_reset = true;
throw new Exception("" + result);
}
if ((_reader.Status.Status == Constants.ReaderStatuses.DP_STATUS_BUSY))
{
Thread.Sleep(50);
}
else if ((_reader.Status.Status == Constants.ReaderStatuses.DP_STATUS_NEED_CALIBRATION))
{
_reader.Calibrate();
}
else if ((_reader.Status.Status != Constants.ReaderStatuses.DP_STATUS_READY))
{
throw new Exception("Reader Status - " + _reader.Status.Status);
}
}
public bool CheckCaptureResult(CaptureResult captureResult)
{
if (captureResult.Data == null)
{
if (captureResult.ResultCode != Constants.ResultCode.DP_SUCCESS)
{
_reset = true;
throw new Exception(captureResult.ResultCode.ToString());
}
// Send message if quality shows fake finger
if ((captureResult.Quality != Constants.CaptureQuality.DP_QUALITY_CANCELED))
{
throw new Exception("Quality - " + captureResult.Quality);
}
return false;
}
return true;
}
public bool CaptureFingerAsync()
{
try
{
GetStatus();
Constants.ResultCode captureResult = _reader.CaptureAsync(Constants.Formats.Fid.ANSI, Constants.CaptureProcessing.DP_IMG_PROC_DEFAULT, _reader.Capabilities.Resolutions[0]);
if (captureResult != Constants.ResultCode.DP_SUCCESS)
{
_reset = true;
throw new Exception("" + captureResult);
}
return true;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
return false;
}
}
public Bitmap CreateBitmap(byte[] bytes, int width, int height)
{
byte[] rgbBytes = new byte[bytes.Length * 3];
for (int i = 0; i <= bytes.Length - 1; i++)
{
rgbBytes[(i * 3)] = bytes[i];
rgbBytes[(i * 3) + 1] = bytes[i];
rgbBytes[(i * 3) + 2] = bytes[i];
}
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
for (int i = 0; i <= bmp.Height - 1; i++)
{
IntPtr p = new IntPtr(data.Scan0.ToInt64() + data.Stride * i);
System.Runtime.InteropServices.Marshal.Copy(rgbBytes, i * bmp.Width * 3, p, bmp.Width * 3);
}
bmp.UnlockBits(data);
return bmp;
}
public bool StartCaptureAsync(Reader.CaptureCallback OnCaptured)
{
// Activate capture handler
_reader.On_Captured += new Reader.CaptureCallback(OnCaptured);
// Call capture
if (!CaptureFingerAsync())
{
return false;
}
return true;
}
#endregion

virtual sub domains has error

I create a project that check the sub domain and redirect to the exist subdomain ( username ) but I can't find out why when the username is in database it can't show it and show this error :
Object reference not set to an instance of an object.
My code is this in page load :
Uri MyUrl = new Uri(Request.Url.ToString());
string Url = MyUrl.Host.ToString();
//Uri MyUrl = new Uri("http://Subdomain.Mydomain.com/");
//string Url = MyUrl.Host.ToString();
string St1 = Url.Split('.')[0];
if ((St1.ToLower() == "Mydomain") || (St1.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else if (St1.ToLower() == "www")
{
string St2 = Url.Split('.')[1];
if ((St2.ToLower() == "Mydomain") || (St2.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else
{
object Blogger = ClsPublic.GetBlogger(St2);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
}
else
{
object Blogger = ClsPublic.GetBlogger(St1);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
and my class :
public static object GetBlogger(string User)
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT fUsername FROM tblMembers WHERE fUsername = #fUsername", scn);
scm.Parameters.AddWithValue("#fUsername", User);
scn.Open();
object Blogger = scm.ExecuteScalar();
if (Blogger != null)
{
SqlCommand sccm = new SqlCommand("SELECT COUNT(fId) AS Exp1 FROM tblImages WHERE (fxSender = #fxSender) AND (fxAccepted = 1)", scn);
sccm.Parameters.AddWithValue("fxSender", Blogger);
object HasQuty = sccm.ExecuteScalar();
scn.Close();
if (HasQuty != null)
{
int Count = Int32.Parse(HasQuty.ToString());
if (Count < 10)
{
Blogger = null;
}
}
}
return Blogger;
}
Which place if my code has problem ?

Categories

Resources