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();
}
Related
I am developing a project using c#.in my project i should get the camera stream .So i use onvif to get the stream but i faced a problem .some of my camera can't support onvif and they support RTSP,and i have to use rtsp in my project to :
Here is my onvif code to get the camera stream :
async void StartCameraAfterLogin()
{
//Dooooorbin
await ProcessConnect("http://172.16.0.52/onvif/device_service"
, Properties.Settings.Default.CameraUserName, Properties.Settings.Default.CameraPassword);
}
async Task ProcessConnect(string addr, string name, string pass)
{
//Release();
//ctrlInfo.Content = new ProgressControl();
var account = new System.Net.NetworkCredential(name, pass);
NvtSessionFactory factory = new NvtSessionFactory(account);
////This is syncronouse ui blokking call
//var session = factory.CreateSession(new Uri(addr);
try
{
var session = factory.CreateSession(new Uri(addr));
ss = session;
await FillInfoArea(session);
}
catch (Exception err)
{
Algoa.Utilities.Logger.ToDebug(err);
//ctrlInfo.Content = new ErrorControl(err);
}
}
string profie;
private async Task FillInfoArea(INvtSession session)
{
var profInfo = new ProfieInfoControl();
try
{
var streamData = await profInfo.Init(session);
//sp.Children.Add(profInfo);
profie = profInfo.valueToken.Text;
InitVideoControl(streamData.Item1, streamData.Item4, session.credentials);
//InitPtzControl(session, streamData.Item2, streamData.Item3);
}
catch (Exception err)
{
Algoa.Utilities.Logger.ToDebug(err);
}
//ctrlInfo.Content = sp;
}
private void InitVideoControl(string suri, System.Windows.Size size, System.Net.NetworkCredential networkCredential)
{
InitPlayer(suri, networkCredential, size);
}
public void InitPlayer(string videoUri, NetworkCredential account, System.Windows.Size sz = default(System.Windows.Size))
{
player = new HostedPlayer();
playerDisposable.Add(player);
if (sz != default(System.Windows.Size))
videoBuff = new VideoBuffer((int)sz.Width, (int)sz.Height);
else
{
videoBuff = new VideoBuffer(720, 576);
}
player.SetVideoBuffer(videoBuff);
MediaStreamInfo.Transport transp = MediaStreamInfo.Transport.Udp;
MediaStreamInfo mstrInfo = null;
if (account != null)
{
mstrInfo = new MediaStreamInfo(videoUri, transp, new UserNameToken(account.UserName, account.Password));//, transp, null);
}
else
{
mstrInfo = new MediaStreamInfo(videoUri, transp);
}
playerDisposable.Add(
player.Play(mstrInfo, this)
);
InitPlayback(videoBuff, true);
//{ // playing controls
// btnPause.Click += play;
// btnResume.Click += play;
//}
}
How can i convert my onvif url to rtsp url ?Is there any solution or i should change all part of my code?
I am new in camera stream coding .
I downloaded the OZEKI-SDK
private IIPCamera _camera;
private DrawingImageProvider _imageProvider = new DrawingImageProvider();
private MediaConnector _connector = new MediaConnector();
private VideoViewerWF _videoViewerWF1;
public Form1()
{
InitializeComponent();
// Create video viewer UI control
_videoViewerWF1 = new VideoViewerWF();
_videoViewerWF1.Name = "videoViewerWF1";
_videoViewerWF1.Size = panel1.Size;
panel1.Controls.Add(_videoViewerWF1);
// Bind the camera image to the UI control
_videoViewerWF1.SetImageProvider(_imageProvider);
}
// Connect camera video channel to image provider and start
private void connectBtn_Click(object sender, EventArgs e)
{
_camera = IPCameraFactory.GetCamera("rtsp://192.168.113.150:554/ufirststream", "root", "pass");
_connector.Connect(_camera.VideoChannel, _imageProvider);
_camera.Start();
_videoViewerWF1.Start();
}
As a another solution i finally used Accord.net library to capture rtsp stream.
I have been tasked with writing a custom application in C#.NET to move messages from one queue to another, while keeping all of the context and identity information the same as the original message.
I have tried to decipher the online docs, and have tried every combination of MQC.MQOO_PASS_ALL_CONTEXT and MQOO_SAVE_ALL_CONTEXT in opening queues, and MQC.MQPMO_PASS_ALL_CONTEXT in put calls, to no avail. I have tried setting the MQPutMessageOptions.ContextReference to both the source and the
destination queues, but I continue to get exceptions, either MQRC_CONTEXT_HANDLE_ERROR or MQRC_OPTIONS_ERROR, and I cannot find enough information in the online docs to determine the problem.
I am using runtime version v2.0.50727, Version 7.5.0.1 of the amqmdnet.dll. If anyone knows the correct open and/or put message option settings I need to use, I would appreciate the leg up. Thanks.
***** SECOND UPDATE *****
Here is a very simple gui program to test the classes, and I get the same results:
public partial class frmMain : Form
{
// Simple test - all data hard-coded
string sourceQStr = "PETE.TQ1";
string targetQStr = "PETE.TQ2";
string targetMsgIdStr = "414D5120514D4942584330352020202028ED0155202EB302";
string connName = "localhost";
string connPort = "1414";
MQQueueManager sourceManager;
MQQueueManager targetManager;
MQQueue sourceQueue;
MQQueue targetQueue;
MQMessage msg = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
MQPutMessageOptions pmo = new MQPutMessageOptions();
public frmMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void txtPassword_Validating(object sender, CancelEventArgs e)
{
if (txtPassword.Text.Trim() != string.Empty)
{
if (LoginUser())
btnTest.Focus();
else
txtUserId.Focus();
}
}
public void LogoutUser()
{
txtUserId.Text = "";
txtPassword.Text = "";
btnTest.Enabled = false;
}
public bool LoginUser()
{
bool OK = ValidateUserAndPassword();
if (OK)
{
btnTest.Enabled = true;
}
else LogoutUser();
return OK;
}
private bool ValidateUserAndPassword()
{
if ((txtUserId.Text.Trim() == string.Empty) || (txtPassword.Text.Trim() == string.Empty))
return false;
try
{
bool _passwordValid = false;
ContextOptions options = ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "UP"))
{
_passwordValid = pc.ValidateCredentials
(txtUserId.Text.Trim(), txtPassword.Text.Trim(), options);
}
if (!_passwordValid)
MessageBox.Show("Invalid username / password", "Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return _passwordValid;
}
catch (PrincipalServerDownException pex)
{
string msg = pex.Message.Insert(pex.Message.IndexOf("server"), "Authentication ");
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void btnTest_Click(object sender, EventArgs e)
{
try
{
SetupObjects();
sourceQueue.Get(msg, gmo);
targetQueue.Put(msg, pmo);
sourceManager.Commit();
targetManager.Commit();
MessageBox.Show("Test appears successful - verify with MQ Explorer","OK",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (Exception ex) // MQRC_CONTEXT_HANDLE_ERROR is always thrown
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
sourceManager.Backout();
targetManager.Backout();
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
/************************************** Utiility methods *****************************************/
private void SetupObjects()
{
// set up objects
string connectName = connName + "(" + connPort + ")";
int ConnOptions = MQC.MQCNO_HANDLE_SHARE_BLOCK;
sourceManager = new MQQueueManager("", ConnOptions, "CHANNEL1", connectName);
targetManager = new MQQueueManager("", ConnOptions, "CHANNEL1", connectName);
MQEnvironment.UserId = txtUserId.Text.Trim();
MQEnvironment.Password = txtPassword.Text.Trim();
int options =
MQC.MQOO_INPUT_SHARED + MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_SAVE_ALL_CONTEXT + MQC.MQOO_INQUIRE;
sourceQueue = sourceManager.AccessQueue
(sourceQStr, options, sourceManager.Name, null, txtUserId.Text.Trim());
options =
MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_PASS_ALL_CONTEXT + MQC.MQOO_INQUIRE;
targetQueue = targetManager.AccessQueue
(targetQStr, options, targetManager.Name, null, txtUserId.Text.Trim());
int i = 0;
try
{
i = sourceQueue.CurrentDepth;
}
catch (Exception ex)
{
MessageBox.Show("Exception: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
gmo.Options = MQC.MQGMO_COMPLETE_MSG + MQC.MQGMO_FAIL_IF_QUIESCING +
MQC.MQGMO_NO_WAIT + MQC.MQGMO_SYNCPOINT;
pmo.Options = MQC.MQPMO_PASS_ALL_CONTEXT +
MQC.MQPMO_SYNCPOINT + MQC.MQPMO_SYNC_RESPONSE;
pmo.ContextReference = sourceQueue;
msg.MessageId = StringToByteArray(targetMsgIdStr);
}
public byte[] StringToByteArray(String hex)
{
hex = hex.Trim();
int NumberChars = hex.Length;
if ((NumberChars % 2) != 0)
{
hex = "0" + hex;
NumberChars++;
}
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = StringToByte(hex.Substring(i, 2));
return bytes;
}
public byte StringToByte(string hexDigits)
{
if (hexDigits.Length != 2)
return 0;
int high = hexValue(hexDigits[0]);
int low = hexValue(hexDigits[1]);
return (byte)(((high << 4) & 240) | (low & 15));
}
public int hexValue(char c)
{
int retval = 0;
if (c > '9')
retval = ((int)c) - 55;
else
retval = ((int)c) - 48;
return retval;
}
}
The GUI simply prompts for a username and password (which are validated with an LDAP call) and then enables a "test" button which runs the btnTest_Click method. I still get the same exception (MQRC_CONTEXT_HANDLE_ERROR) even thought I have used all the open and get message options specified.
Adding to Morag's answer, here is snippet for moving messages with context. I am also using a SYNC_POINT to ensure the message is removed from source queue after the message is successfully put to the destination queue.
/// <summary>
/// Moves messages from one queue to another with context
/// </summary>
public void moveMessagesWithContext()
{
MQQueueManager qmSource = null;
MQQueueManager qmDestination = null;
MQQueue qSource = null;
MQQueue qDestination = null;
Hashtable htSource = null;
Hashtable htDestination = null;
try
{
htSource = new Hashtable();
htDestination = new Hashtable();
htSource.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
htSource.Add(MQC.HOST_NAME_PROPERTY, "localhost");
htSource.Add(MQC.PORT_PROPERTY, 2020);
htSource.Add(MQC.CHANNEL_PROPERTY, "A_QM_SVRCONN");
qmSource = new MQQueueManager("A_QM", htSource);
qSource = qmSource.AccessQueue("Q_SOURCE", MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SAVE_ALL_CONTEXT);
htDestination.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
htDestination.Add(MQC.HOST_NAME_PROPERTY, "localhost");
htDestination.Add(MQC.PORT_PROPERTY, 3030);
htDestination.Add(MQC.CHANNEL_PROPERTY, "B_QM_SVRCONN");
qmDestination = new MQQueueManager("B_QM", htDestination);
qDestination = qmDestination.AccessQueue("Q_DESTINATION", MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_PASS_ALL_CONTEXT);
MQMessage msgSource = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options |= MQC.MQGMO_SYNCPOINT;
qSource.Get(msgSource,gmo);
if (msgSource != null)
{
MQMessage msgDestination = new MQMessage();
MQPutMessageOptions pmo = new MQPutMessageOptions();
pmo.ContextReference = qSource;
qDestination.Put(msgSource, pmo);
qmSource.Commit();
}
}
catch (MQException mqEx)
{
qmSource.Backout();
Console.WriteLine(mqEx);
}
catch (Exception otherEx)
{
Console.WriteLine(otherEx);
}
}
The correct options to use to move messages whilst retaining all the context information within them are as follows.
When opening the queue to get messages from, use MQOO_SAVE_ALL_CONTEXT. The context will be saved at get time in the object handle that represents this opened queue.
When opening the queue to put messages to, use MQOO_PASS_ALL_CONTEXT. Then when putting the message, use MQPMO_PASS_ALL_CONTEXT and provide the object handle that contains the context.
Receiving return code MQRC_CONTEXT_HANDLE_ERROR means that you didn't use MQOO_SAVE_ALL_CONTEXT on the first open but then tried to use the object handle on the put. It could also mean that it's just not a correct reference to the first queue. In the MQ API it's an object handle (MQHOBJ) whereas in .Net it's the MQQueue (see MQPutMessageOptions .NET class).
Receiving return code MQRC_OPTIONS_ERROR means that you mixed and matched the options too much.
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'.
I have a windows service that is supposed to check for a record, email a report for that record, delete the record and then repeat for the table. It checks for the record, emails a report for the first record then shuts off. Any ideas??
Service code:
namespace ReportSender
{
public partial class EmailReportService : ServiceBase
{
private EmailReportApp _app = new EmailReportApp();
public Timer serviceTimer = new Timer();
public EmailReportService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//Set interval (from App Settings) and enable timer
serviceTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_OnElapsed);
//Use Conversion utility to determine next start date/time based on properties, use DateTime.Subtract() to find milliseconds difference between Now and the next start time
//serviceTimer.Interval = Date.AddInterval(Properties.Settings.Default.IntervalType, Properties.Settings.Default.Interval).Subtract(DateTime.Now).TotalMilliseconds;
serviceTimer.Interval = 600000;
serviceTimer.Enabled = true;
}
protected override void OnStop()
{
//Stop and disable timer
serviceTimer.Enabled = false;
}
private void ServiceTimer_OnElapsed(object source, ElapsedEventArgs e)
{
try
{
//Stop the timer to prevent overlapping runs
serviceTimer.Stop();
//Start service
//Run your app.Start() code
_app = new EmailReportApp();
_app.Start();
}
catch (Exception ex)
{
}
finally
{
//Re-start the timer
serviceTimer.Start();
}
}
}
}
Code the service is supposed to execute:
namespace ReportSender
{
class EmailReportApp
{
// Private fields
private Thread _thread;
private EventLog _log;
private void Execute()
{
try
{
// Check for a new record
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
dc.reportsSent1s.DeleteOnSubmit(item);
dc.SubmitChanges();
}
}
catch (ThreadAbortException ex)
{
_log.WriteEntry(ex.StackTrace.ToString());
}
}
public void Start()
{
if (!EventLog.SourceExists("EventLoggerSource"))
EventLog.CreateEventSource("EventLoggerSource", "Event Logger");
_log = new EventLog("EventLoggerSource");
_log.Source = "EventLoggerSource";
_thread = new Thread(new ThreadStart(Execute));
_thread.Start();
}
public void Stop()
{
if (_thread != null)
{
_thread.Abort();
_thread.Join();
}
}
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("234#acmetaxabstracts.com", "georr#gmail.com", "Report for BRT # " + matchedAdd, "Attached if the Tax Information Certificate for the aboved captioned BRT Number");
MailAddress copy = new MailAddress("a123s#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.**.***.**");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
}
catch (Exception ex)
{
}
}
}
}
The 'ServiceBase' is losing scope once the OnStart method is called. A 'ManualResetEvent' will keep the service open for you.
Use member:
ManualResetEvent stop = new ManualResetEvent(false);
Try this in your main Start():
do
{
try
{
_app = new EmailReportApp();
_app.Start();
}
catch(Exception e)
{
... handle error or log however you want
}
}
while(!stop.WaitOne(0, false))
in Stop(), make sure to do stop.Set()
I have successfully integrated IMAPI2 using Interop.cs into my application. I can burn CD/DVDs without any problem. However, the event handler for MsftDiscFormat2Data update does not work, so I can't get my progress bar moving.
Here is the code I found at codeproject website:
private void backgroundBurnWorker_DoWork(object sender, DoWorkEventArgs e)
{
MsftDiscRecorder2 discRecorder = null;
MsftDiscFormat2Data discFormatData = null;
try
{
//
// Create and initialize the IDiscRecorder2 object
//
discRecorder = new MsftDiscRecorder2();
var burnData = (BurnData)e.Argument;
discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId);
//
// Create and initialize the IDiscFormat2Data
//
discFormatData = new MsftDiscFormat2Data
{
Recorder = discRecorder,
ClientName = ClientName,
ForceMediaToBeClosed = _closeMedia
};
//
// Set the verification level
//
var burnVerification = (IBurnVerification)discFormatData;
burnVerification.BurnVerificationLevel = _verificationLevel;
//
// Check if media is blank, (for RW media)
//
object[] multisessionInterfaces = null;
if (!discFormatData.MediaHeuristicallyBlank)
{
multisessionInterfaces = discFormatData.MultisessionInterfaces;
}
//
// Create the file system
//
IStream fileSystem;
if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem))
{
e.Result = -1;
return;
}
//
// add the Update event handler
//
discFormatData.Update += discFormatData_Update;
//
// Write the data here
//
try
{
discFormatData.Write(fileSystem);
e.Result = 0;
}
catch (COMException ex)
{
e.Result = ex.ErrorCode;
MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
if (fileSystem != null)
{
Marshal.FinalReleaseComObject(fileSystem);
}
}
//
// remove the Update event handler
//
discFormatData.Update -= discFormatData_Update;
if (_ejectMedia)
{
discRecorder.EjectMedia();
}
}
catch (COMException exception)
{
//
// If anything happens during the format, show the message
//
MessageBox.Show(exception.Message);
e.Result = exception.ErrorCode;
}
finally
{
if (discRecorder != null)
{
Marshal.ReleaseComObject(discRecorder);
}
if (discFormatData != null)
{
Marshal.ReleaseComObject(discFormatData);
}
}
}
void discFormatData_Update([In, MarshalAs(UnmanagedType.IDispatch)] object sender, [In, MarshalAs(UnmanagedType.IDispatch)] object progress)
{
//
// Check if we've cancelled
//
if (backgroundBurnWorker.CancellationPending)
{
var format2Data = (IDiscFormat2Data)sender;
format2Data.CancelWrite();
return;
}
var eventArgs = (IDiscFormat2DataEventArgs)progress;
_burnData.task = BURN_MEDIA_TASK.BURN_MEDIA_TASK_WRITING;
// IDiscFormat2DataEventArgs Interface
_burnData.elapsedTime = eventArgs.ElapsedTime;
_burnData.remainingTime = eventArgs.RemainingTime;
_burnData.totalTime = eventArgs.TotalTime;
// IWriteEngine2EventArgs Interface
_burnData.currentAction = eventArgs.CurrentAction;
_burnData.startLba = eventArgs.StartLba;
_burnData.sectorCount = eventArgs.SectorCount;
_burnData.lastReadLba = eventArgs.LastReadLba;
_burnData.lastWrittenLba = eventArgs.LastWrittenLba;
_burnData.totalSystemBuffer = eventArgs.TotalSystemBuffer;
_burnData.usedSystemBuffer = eventArgs.UsedSystemBuffer;
_burnData.freeSystemBuffer = eventArgs.FreeSystemBuffer;
//
// Report back to the UI
//
backgroundBurnWorker.ReportProgress(0, _burnData);
}
Unfortunately, the update handler gets never called. I looked up everywhere on internet but could not find a solution. I saw some people with same problem but no one was able to answer.
The original code from Eric, http://www.codeproject.com/KB/miscctrl/imapi2.aspx?msg=2695517,
does work for some reason.
Can someone please help me?
I know, it's too late, but I've got the same problem with update callbacks.
Open Project->Properties->Application->Assembly Information and tick "Make Assembly COM-visible".