I have got 3-tier where carry out my code in business layer I run code for update
public override bool LoadProperties2List(string TypeOfOperation)
{
SortedList Sl = new SortedList();
Sl.Add("#CommandType", TypeOfOperation);
Sl.Add("#UserName",UserName);
Sl.Add("#SecondarySchool",SecondarySchool);
Sl.Add("#University",University);
Sl.Add("#Qualification",Qualification);
Sl.Add("#JobTitle",JobTitle);
Sl.Add("#Company",Company);
Sl.Add("#PhotoUrl", PhotoUrl);
ProcedureName = "MangeUserInfo";
if (db.RunProcedure(ProcedureName, Sl) == 1)
return true;
else
return false;
}
public bool updateUser(string User, string SecondaryS, string Unvi, string Qua, string jobtitle, string company)
{
this.UserName = User;
this.SecondarySchool = SecondaryS;
this.University = Unvi;
this.Qualification = Qua;
this.JobTitle = jobtitle;
this.Company = company;
if (Update())
return true;
else
return false;
}
and in data access layer
public void ConnectDB(CommandType CT,string ProNameSQl)
{
cn = new SqlConnection("Data Source=.;Initial Catalog=Conversation;Integrated Security=True");
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CT;
cmd.CommandText = ProNameSQl;
cn.Open();
}
public int RunProcedure(string ProcedureName, SortedList Paraval)
{
ConnectDB(CommandType.StoredProcedure, ProcedureName);
for (int x = 0; x < Paraval.Count; x++)
{
try
{
cmd.Parameters.AddWithValue(Paraval.GetKey(x).ToString(), Paraval.GetByIndex(x));
}
catch
{
;
}
}
return ExceNoneQuery();
}
and then in another layer I use this method to call procedure process kind and run
public bool Update()
{
return LoadProperties2List("u");
}
at last layer presentation layer
I do that
protected void btnsave_Click(object sender, EventArgs e)
{
//upadate info
bool Result = false;
UsersInfo Upd = new UsersInfo();
try
{
Result = Upd.updateUser(username, TxtSecondarySchool.Text, TxtUniversity.Text, TxtQualification.Text, TxtJobTitle.Text, TxtCompany.Text);
if (Result==true)
lblMessage.Text = "Record Updated Successfully.";
else
lblMessage.Text = "Record couldn't updated";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
} finally
{
Upd = null;
}
}
When I run the code only the result is
lblMessage.Text = "Record couldn't updated";
What is the error which makes it not to work correctly?
I also find something strange that the textboxes doesn't take the new values it pass the same value despite change why? I need help
The error is that the textbox loads in a routine in the Page's Startup event, with the routine placed outside the If IsNotPostback loop. So, the default value just reloads every time the page is refreshed, and thus appears to be 'unchangeable'.
Related
I'm using sqlite to save log and meet write performance issue.
string log = "INSERT INTO Log VALUES ('2019-12-12 13:43:06','Error','Client','This is log message')"
public int WriteLog(string log)
{
return ExecuteNoQuery(log);
}
public int ExecuteNoQuery(string command)
{
int nResult = -1;
try
{
using (SQLiteConnection dbConnection = new SQLiteConnection(ConnectString))
{
dbConnection.Open();
using (SQLiteCommand dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = command;
nResult = dbCommand.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
// Output error message
}
return nResult;
}
Search in google, transaction could improve the write performance significantly, but unfortunately I don't know when a log message will come, I could not combine the log message. Is there any other way to improve my log write performance?
I tried to add a timer to my code and commit transaction automatically. But I don't think it's a good way to speed up log write performance.
public class DatabaseManager : IDisposable
{
private static SQLiteTransaction transaction = null;
private SQLiteConnection dbConnection = null;
private static Timer transactionTimer;
private long checkInterval = 500;
private DatabaseManager(string connectionString)
{
dbConnection = new SQLiteConnection(connectionString);
dbConnection.Open();
StartTransactionTimer();
}
public void Dispose()
{
if(transaction != null)
{
transaction.Commit();
transaction = null;
}
dbConnection.Close();
dbConnection = null;
}
private void StartTransactionTimer()
{
transactionTimer = new Timer();
transactionTimer.Interval = checkInterval;
transactionTimer.Elapsed += TransactionTimer_Elapsed;
transactionTimer.AutoReset = false;
transactionTimer.Start();
}
private void TransactionTimer_Elapsed(object sender, ElapsedEventArgs e)
{
StartTransation();
transactionTimer.Enabled = true;
}
public void StartTransation()
{
try
{
if (dbConnection == null || dbConnection.State == ConnectionState.Closed)
{
return;
}
if (transaction != null)
{
transaction.Commit();
transaction = null;
}
transaction = dbConnection.BeginTransaction();
}
catch(Exception e)
{
LogError("Error occurs during commit transaction, error message: " + e.Message);
}
}
public int ExecuteNoQuery(string command)
{
int nResult = -1;
try
{
using (SQLiteCommand dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = command;
nResult = dbCommand.ExecuteNonQuery();
}
}
catch (Exception e)
{
LogError("Error occurs during execute sql no result query, error message: ", e.Message);
}
return nResult;
}
}
This started out as a comment, but it's evolving to an answer.
Get rid of the GC.Collect(); code line.
That's not your job to handle garbage collection - and you're probably degrading performance by using it.
No need to close the connection, you're disposing it in the next line anyway.
Why are you locking? Insert statements are usually thread safe - and this one doesn't seem to be an exception of that rule.
You are swallowing exceptions. That's a terrible habit.
Since you're only ever insert a single record, you don't need to return an int - you can simply return a bool (true for success, false for failure)
Why you don't use the entity framework to do the communications with the database?
For me is the easiest way. It's a Microsoft library so you can sure that the performance is very good.
I made some work with entity framework and sqlite db's and everything works very well.
Here an example of use:
var context = new MySqliteDatabase(new SQLiteConnection(#"DataSource=D:\\Mydb.db;cache=shared"));
var author = new Author {
FirstName = "William",
LastName = "Shakespeare",
Books = new List<Book>
{
new Book { Title = "Hamlet"},
new Book { Title = "Othello" },
new Book { Title = "MacBeth" }
}
};
context.Add(author);
context.SaveChanges();
The type of MySqliteDatabase can be created automatically using database first approach or with Code First approach. You have a lot of information and examples on the internet.
Here the link to the official documentation:
https://learn.microsoft.com/en-us/ef/ef6/
First time working with SQL Dependency... but after having gone over several examples I feel as I am doing everything correct. I've checked that the Broker is Enabled. I've further checked that my query is correct. I am not receiving any exceptions at all! All and all everything seems as it should work... but it is not, and I have no idea how to begin to troubleshoot it without any exceptions being thrown.
Any help would be VERY much appreciated!
Here is my class:
public class NotificationEvent
{
private delegate void RateChangeNotification(DataTable table);
private SqlDependency dependency;
string ConnectionString = #"ConnectionString";
string UserName = Environment.UserName;
public async void StartNotification()
{
SqlDependency.Start(this.ConnectionString, "UserNotificationsQueue");
SqlConnection connection = new SqlConnection(this.ConnectionString);
await connection.OpenAsync();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = string.Format("SELECT [NotificationID],[UserFrom],[UserTo],[DateTimeSent],[Notification] FROM [dbo].[PersonnellNotifications]", UserName);
command.Notification = null;
this.dependency = new SqlDependency(command, "Service=PostUserNotificationsQueue;", Int32.MaxValue);
dependency.OnChange += new OnChangeEventHandler(this.SqlDependencyOnChange);
await command.ExecuteReaderAsync();
}
private void SqlDependencyOnChange(object sender, SqlNotificationEventArgs eventArgs)
{
if (eventArgs.Info == SqlNotificationInfo.Invalid)
{
Console.WriteLine("The above notification query is not valid.");
}
else
{
Console.WriteLine("Notification Info: " + eventArgs.Info);
Console.WriteLine("Notification source: " + eventArgs.Source);
Console.WriteLine("Notification type: " + eventArgs.Type);
}
}
public void StopNotification()
{
SqlDependency.Stop(this.ConnectionString, "QueueName");
}
}
I am initializing this from another classes IniatializeComponent() as seen:
private void InitializeComponent()
{
// Initialize SQL Dependancy
ne.StartNotification();
}
I have just tested following in my Code and Its working good. I have simplified your code. Please see if this is working and you are getting a call in OnNotificationChange on Db Change.
public async void RegisterForNotification()
{
var connectionString = #"ConnectionString";
using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
var queryString = "Your Query String";
using (var oCommand = new SqlCommand(queryString, connection))
{
// Starting the listener infrastructure...
SqlDependency.Start(connectionString);
var oDependency = new SqlDependency(oCommand);
oDependency.OnChange += OnNotificationChange;
// NOTE: You have to execute the command, or the notification will never fire.
await oCommand.ExecuteReaderAsync();
}
}
}
private void OnNotificationChange(object sender, SqlNotificationEventArgs e)
{
Console.WriteLine("Notification Info: " + e.Info);
//Re-register the SqlDependency.
RegisterForNotification();
}
Are you setting SQLClientPermission? see:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-query-notifications
// Code requires directives to
// System.Security.Permissions and
// System.Data.SqlClient
private bool CanRequestNotifications()
{
SqlClientPermission permission =
new SqlClientPermission(
PermissionState.Unrestricted);
try
{
permission.Demand();
return true;
}
catch (System.Exception)
{
return false;
}
}
I have coded a service in C# which runs and updates a CRM solution. I am trying to get the service to re-establish a connection to the database if it has to drop for some reason. So far when I detach the database and then reattach it, the service stops by itself.. Another thing is that then I detach the database, there is no exception logged by my synch app - it just stops dead.
My partial class where I call my synch from:
namespace Vessel_Schedule_Synch
{
[DisplayName("CRM Vessel Synch")]
partial class startVessel : ServiceBase
{
System.Threading.Timer t;
VesselUpdater v;
protected override void OnStart(string[] args)
{
//System.Threading.Thread.Sleep(20000);
v = new VesselUpdater();
t = new System.Threading.Timer(new System.Threading.TimerCallback(t_TimerCallback), null, 0, 300000);
//InfoLogger.Info("Starting service " + this.ServiceName, true);
}
private void t_TimerCallback(object state)
{
t.Change(Timeout.Infinite, Timeout.Infinite);
lock (v)
{
InfoLogger.Info("Timer fired... updating vessels");
try
{
v.Process();
v.updateCRM();
}
catch (Exception e)
{
if (v == null)
{ throw e; }
else
{
InfoLogger.Exception(e);
}
}
finally
{
InfoLogger.Info("End of Timer Trigger... Restarting Timer.");
t.Change(30000, 30000);
}
}
}
protected override void OnStop()
{
InfoLogger.Info("Service Stopped " + this.ServiceName, true);
}
}
}
My synch class where I have tried to use a bool to test the connection:
namespace Vessel_Schedule_Synch
{
class VesselUpdater
{
private OrganizationServiceProxy _serviceProxy;
private IOrganizationService _service;
private Logger logger = LogManager.GetLogger("VesselUpdater");
public string ConnectionString { get; set; }
public string ServiceUrl { get; set; }
int i = 0;
private bool InitialiseCRMConnection;
public VesselUpdater()
{
InitialiseCRMConnection = true;
Console.WriteLine("Starting the service");
LogMessage("Starting service");
ServiceUrl = ConfigurationManager.AppSettings["CRMUrl"];
LogMessage(ConnectionString);
ConnectionString = ConfigurationManager.ConnectionStrings["iRoot"].ConnectionString;
LogMessage(ServiceUrl);
Console.WriteLine(ServiceUrl);
}
public void Process()
{
if (!InitialiseCRMConnection)
return;
LogMessage("Process Starting");
ClientCredentials UserCredentials = new ClientCredentials();
string UserName = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
UserCredentials.UserName.UserName = UserName;
UserCredentials.UserName.Password = Password;
ClientCredentials DivCredentials = null;
Uri HomeRealmURI = null;
Uri serviceurl = new Uri(ServiceUrl);
_serviceProxy = new OrganizationServiceProxy(serviceurl, HomeRealmURI, UserCredentials, DivCredentials);
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
_serviceProxy.EnableProxyTypes();
LogMessage("CRM Connection Initiated");
InitialiseCRMConnection = false;
}
public void updateCRM()
{
try
{
ProcessVesselSchedule("Insert");
ProcessVesselSchedule("Modification");
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
private void ProcessVesselSchedule(string Type)
{
if (InitialiseCRMConnection)
return;
try
{
LogMessage(string.Format("Processing Vessesl Schedules {0}", Type));
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("VesselScheduleInformation", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Type", Type);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
LogMessage("Processing Record");
LogMessage(dr["new_Name"].ToString());
string Name = dr["new_Name"].ToString() + " " + dr["new_VoyageNo"].ToString();
string Vesselname = dr["new_Name"].ToString();
int LineNo = (int)dr["Line Number"];
string NAVVesselScheduleCode = dr["new_NAVVesselScheduleCode"].ToString();
string CarrierService = dr["new_CarrierService"].ToString();
string ETA = dr["new_ETA"].ToString();
string ETD = dr["new_ETD"].ToString();
string VesselCode = dr["new_Vessel"].ToString();//Vessel Code
string VoyageNo = dr["new_VoyageNo"].ToString();
string TranshipmentVessel = dr["new_TranshipmentVessel"].ToString();
string TranshipmentVoyageNo = dr["new_TranshipmentVoyageNo"].ToString();
string Port = dr["new_Port"].ToString();
string PortOfDis = dr["new_DischargePort"].ToString();
string PortOfLoad = dr["new_LoadPort"].ToString();
//string StackStart = dr["new_StackStart"].ToString();
//string StackEnd = dr["new_StackEnd"].ToString();
bool Create = false;
LogMessage("Assigned all variables");
Console.WriteLine("Assigned all variables");
new_vesselschedule VesselS = FindVessleSchedule(NAVVesselScheduleCode, LineNo, out Create);
//if (DateTime.Parse(StackStart).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackstart"] = DateTime.Parse(StackStart).ToUniversalTime();
//}
//if (DateTime.Parse(StackEnd).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackend"] = DateTime.Parse(StackEnd).ToUniversalTime();
//}
VesselS.new_name = Name;
VesselS.new_navvesselschedulecode = NAVVesselScheduleCode;
VesselS.new_CarrierService = CarrierService;
if (DateTime.Parse(ETA).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETA = DateTime.Parse(ETA).ToUniversalTime();
}
if (DateTime.Parse(ETD).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETD = DateTime.Parse(ETD).ToUniversalTime();
}
VesselS.new_vesselcodeimport = VesselCode;
VesselS.new_vesselnameimport = Vesselname;
VesselS.new_VoyageNo = VoyageNo;
VesselS.new_TransshipmentVessel = TranshipmentVessel;
VesselS.new_TransshipmentVoyageNo = TranshipmentVoyageNo;
VesselS.new_dischargeportimport = PortOfDis;
VesselS.new_loadportimport = PortOfLoad;
if (Create)
{
LogMessage(string.Format("Created {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Create(VesselS);
}
else
{
LogMessage(string.Format("Updated {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Update(VesselS);
}
using (SqlCommand cmdUpdateMates = new SqlCommand())
{
SqlConnection con2 = new SqlConnection(ConnectionString);
con2.Open();
cmdUpdateMates.Connection = con2;
cmdUpdateMates.CommandText = "ProcessedVessSched";
cmdUpdateMates.CommandType = CommandType.StoredProcedure;
cmdUpdateMates.Parameters.AddWithValue("#VesselSched", NAVVesselScheduleCode);
cmdUpdateMates.Parameters.AddWithValue("#LineNo", LineNo);
cmdUpdateMates.ExecuteNonQuery();
i++;
Console.WriteLine("Created/Updated" + " " + i);
}
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
}
}
catch (SqlException e)
{
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
public void LogMessage(string Message)
{
LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", Message);
myEvent.LoggerName = logger.Name;
logger.Log(myEvent);
}
private new_vesselschedule FindVessleSchedule(string NAVVesselScheduleCode, int LineNo, out bool Create)
{
QueryExpression query = new QueryExpression(new_vesselschedule.EntityLogicalName);
query.ColumnSet.AllColumns = true;
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("new_navvesselschedulecode", ConditionOperator.Equal, NAVVesselScheduleCode);
query.Criteria.AddCondition("new_lineno", ConditionOperator.Equal, LineNo);
EntityCollection entitycollection = _serviceProxy.RetrieveMultiple(query);
if (entitycollection.Entities.Count == 0)
{
new_vesselschedule n = new new_vesselschedule();
n.new_navvesselschedulecode = NAVVesselScheduleCode;
n.new_lineno = LineNo;
Create = true;
return n;
}
Create = false;
return (new_vesselschedule)entitycollection.Entities[0];
}
}
}
Am I missing something here?
I found the issue in my code, I had forgotten to sent InitialiseCRMConnection = true; in my SQL Exception thus it could never go through the motions of reInitialising the connection as it would always return;
Fix:
catch (SqlException e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
good day to all I just need some help. I was wondering if my code is correct so please guide if it is not. I have a Digital Personal Biometric Model U.ar.U 4500 using DPFP .NET (C#) SDK I was able to save the serialize template to Database ms-sql and I was wondering if the way a serialize is correct. If it is correct how do I deserialize and compare the data to the machine template. here is my code.
public void EnrollmentControl_OnEnroll(Object Control, int Finger, DPFP.Template
Template, ref DPFP.Gui.EventHandlerStatus Status) {
if (Data.IsEventHandlerSucceeds) {
byte[] by = new byte[0];
foreach (DPFP.Template template in Data.Templates)
{
if (template != null)
{
by = new byte[template.Bytes.Length];
template.Serialize(ref by);
string PP;
string CR;
PP = iSQL.STORED_PROCEDURE_FNG_IMG; // <- Stored Procedure INSERT INTO Employee_Img
CR = "AB-0001-R12";
iEmp emp = new iEmp(PP); // <- Class that insert to MS SQL
int rt = emp.Insert_Finger(CR, template.Bytes); // <- return 1 if Successfully
if (rt == 1) { iCon.success_mgs(1, "Successfully Inserted", iSQL.EMPLOYEE_REGISTRN); } //<- Popup message
else { iCon.success_mgs(1, "Successfully Inserted", iSQL.EMPLOYEE_REGISTRN); }
}
}
Data.Templates[Finger - 1] = Template; // store a finger template
ExchangeData(true); // update other data
ListEvents.Items.Insert(0, String.Format("OnEnroll: finger {0}", Finger));
}else
Status = DPFP.Gui.EventHandlerStatus.Failure; // force a "failure" status
}
I have faced with this problem, then I have fixed it already by following steps:
Example:
pgAdmin:
Table Name:
-tbl_fptable
DB Fields:
fp_id (int)
fp_data (text)
Insert Data to Database;
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Enrollment);
// Check quality of the sample and add to enroller if it's good
if (features != null) try
{
MakeReport("The fingerprint feature set was created.");
Enroller.AddFeatures(features); // Add feature set to template.
}
finally {
UpdateStatus();
// Check if template has been created.
switch (Enroller.TemplateStatus)
{
case DPFP.Processing.Enrollment.Status.Ready:
// report success and stop capturing
byte[] serializedTemplate = null;
string str_temp = null;
DateTime cur_date = DateTime.Now;
Enroller.Template.Serialize(ref serializedTemplate);
//Enroller.Template.Serialize(ref str_temp);
if (serializedTemplate != null)
{
string result = System.Text.Encoding.UTF8.GetString(serializedTemplate);
Console.Write(result);
try
{
using (NpgsqlConnection conn = new NpgsqlConnection("Host=127.0.0.1;Port=5432;User Id=UserName;Password=*****;Database=finger_print_db;"))
{
conn.Open();
NpgsqlCommand dbcmd = conn.CreateCommand();
try
{
// Store TemplateSerialize as string data
dbcmd.CommandText= "INSERT INTO tbl_fptable( fp_data ) VALUES ( #serializedTemplate )";
dbcmd.Parameters.AddWithValue("#serializedTemplate ", serializedTemplate);
dbcmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
OnTemplate(Enroller.Template);
SetPrompt("Click Close, and then click Fingerprint Verification.");
Stop();
break;
case DPFP.Processing.Enrollment.Status.Failed: // report failure and restart capturing
Enroller.Clear();
Stop();
UpdateStatus();
OnTemplate(null);
Start();
break;
}
}
}
Get Data from Database to verified
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
if (features != null)
{
try
{
using (NpgsqlConnection conn = new NpgsqlConnection("Host=127.0.0.1;Port=5432;User Id=UserName;Password=*****;Database=finger_print_db;"))
{
conn.Open();
try
{
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM tbl_fptable ORDER BY enr_id DESC LIMIT 1", conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
long fpid = Convert.ToInt64(dr["id"]);
byte[] fpbyte = (byte[])dr["finger_data"];
Stream stream = new MemoryStream(fpbyte );
DPFP.Template tmpObj = new DPFP.Template(stream);
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
// Compare the feature set with our template
Verificator.Verify(features, tmpObj, ref result);
UpdateStatus(result.FARAchieved);
if (result.Verified)
MakeReport("The fingerprint was VERIFIED.");
else
MakeReport("The fingerprint was NOT VERIFIED.");
}
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I hope this example can solve this stuck.
public class VerificationForm : CaptureForm
{
public void Verify(DPFP.Template template)
{
Template = template;
ShowDialog();
}
protected override void Init()
{
base.Init();
base.Text = "Fingerprint Verification";
Verificator = new DPFP.Verification.Verification(); // Create a fingerprint template verificator
UpdateStatus(0);
}
bool found = false; string fname = "";
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
if (features != null)
{
// Compare the feature set with our template
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
string[] flist = Directory.GetFiles("c:/finger");
int mx = flist.Length;
int cnt = 0;
bool found = false;
DPFP.Template templates;
while (cnt < mx && !found)
{
// MessageBox.Show(flist[cnt]);
using (FileStream fs = File.OpenRead(flist[cnt]))
{
templates = new DPFP.Template(fs);
Verificator.Verify(features, templates, ref result);
UpdateStatus(result.FARAchieved);
}
if (result.Verified)
{
found = true;
FileInfo nfo = new FileInfo(flist[cnt]);
fname = nfo.Name;
break;
}
else
{
found = false;
cnt++;
}
}
if (found)
{
MakeReport("The fingerprint was VERIFIED. "+fname);
MessageBox.Show("Verified!!");
}
else
{
MakeReport("The fingerprint was NOT VERIFIED.");
MessageBox.Show("Not Verified!!");
}
}
}
private void UpdateStatus(int FAR)
{
// Show "False accept rate" value
SetStatus(String.Format("False Accept Rate (FAR) = {0}", FAR));
}
private DPFP.Template Template;
private DPFP.Verification.Verification Verificator;
private void InitializeComponent()
{
this.SuspendLayout();
//
// VerificationForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.ClientSize = new System.Drawing.Size(693, 373);
this.Name = "VerificationForm";
this.Load += new System.EventHandler(this.VerificationForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?
Example:
protected void btnSave_Click(object sender, EventArgs e)
{
int ixTest= SaveTest("123");
CreateTest(ixTest);
}
protected int SaveTest(int ixTestID)
{
SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
null,
ixTestID);
sp.Execute();
int ixTest= (int)sp.OutputValues[0];
return ixTest;
}
private long CreateTest(int ixTest)
{
long ixTestCustomer = CreateTestCustomer();
TestCustomer testCustomer= new TestCustomer();
try
{
testCustomer.TestCustomerId = ixTest;
testCustomer.InteractionId = ixTestCustomer ;
testCustomer.Save();
}
catch
{
Response.Redirect("pgCallSaveFailure.aspx");
}
m_saleDetail = new TestSaleDetail();
try
{
m_saleDetail.SaleId = sale.SaleId;
m_saleDetail.Save();
}
catch
{
Response.Redirect("pgCallSaveFailure.aspx");
}
return ixTestCustomer ;
}
I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?
Use the TransactionScope class
Code performs exact is given below. Hope you can get the idea.
public void SaveData()
{
SqlConnection connDB = new SqlConnection();
SqlCommand cmdExecuting = new SqlCommand();
try {
connDB = new SqlConnection(connection_string);
cmdExecuting.Connection = connDB;
connDB.Open();
cmdExecuting.Transaction = connDB.BeginTransaction();
int result = 0;
result = Method1(cmdExecuting);
if (result != 0) {
cmdExecuting.Transaction.Rollback();
return;
}
result = Method2(cmdExecuting);
if (result != 0) {
cmdExecuting.Transaction.Rollback();
return;
}
cmdExecuting.Transaction.Commit();
} catch (Exception ex) {
cmdExecuting.Transaction.Rollback();
} finally {
cmdExecuting.Dispose();
cmdExecuting = null;
connDB.Close();
connDB = null;
}
}
public int Method1(SqlCommand cmdExecuting)
{
cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 01";
cmdExecuting.CommandType = CommandType.StoredProcedure;
cmdExecuting.Parameters.Add("#para1", SqlDbType.Int);
cmdExecuting.Parameters("#para1").Value = value;
return cmdExecuting.ExecuteScalar();
}
public int Method2(SqlCommand cmdExecuting)
{
cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 02";
cmdExecuting.CommandType = CommandType.StoredProcedure;
cmdExecuting.Parameters.Add("#para1", SqlDbType.Int);
cmdExecuting.Parameters("#para1").Value = value;
return cmdExecuting.ExecuteScalar();
}