Problems uploading a ZK Face String Template to a device - c#

Device Model: SpeedFace-H5L
SDK Im using: StandAlone SDK-Ver6.3.1.34
Conected via TCP/IP
When i use GetUserFaceStr I get all the templates but when I try to do SetUserFaceStr the operation fails and returns a -103 Error Code, In the documentacion it says that this error means "-103 device send back error of face version error"
The Fp version code is
axCZKEM1.GetSysOption(GetMachineNumber(), "ZKFaceVersion", out strTemp);
Throws me a 58 Face Algorith
This is the code for getting and setting faces
public int sta_SetAllUserFaceInfo(ListBox lblOutputInfo, ProgressBar prgSta, ListView lvUserInfo)
{
if (GetConnectState() == false)
{
lblOutputInfo.Items.Add("*Please connect first!");
return -1024;
}
if (lvUserInfo.Items.Count == 0)
{
lblOutputInfo.Items.Add("*There is no data can upload!");
return -1023;
}
string sEnrollNumber = "";
string sEnabled = "";
bool bEnabled = false;
string sName = "";
string sPassword = "";
int iPrivilege = 0;
string sTmpData = "";
int iLength = 0;
int iFaceIndex = 50;
int num = 0;
axCZKEM1.EnableDevice(iMachineNumber, false);
for (int i = 0; i < lvUserInfo.Items.Count; i++)
{
sEnrollNumber = lvUserInfo.Items[i].SubItems[0].Text;
sEnabled = lvUserInfo.Items[i].SubItems[1].Text;
if (sEnabled == "true")
{
bEnabled = true;
}
else
{
bEnabled = false;
}
sName = lvUserInfo.Items[i].SubItems[2].Text;
sPassword = lvUserInfo.Items[i].SubItems[3].Text;
iPrivilege = Convert.ToInt32(lvUserInfo.Items[i].SubItems[4].Text);
iLength = Convert.ToInt32(lvUserInfo.Items[i].SubItems[5].Text);
sTmpData = lvUserInfo.Items[i].SubItems[6].Text;
if (axCZKEM1.SSR_SetUserInfo(iMachineNumber, sEnrollNumber, sName, sPassword, iPrivilege, bEnabled))//upload user information to the device
{
if(axCZKEM1.SetUserFaceStr(iMachineNumber, sEnrollNumber, iFaceIndex, sTmpData, iLength)) //upload face templates information to the device
{
num++;
prgSta.Value = num % 100;
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
lblOutputInfo.Items.Add("*Operation failed,ErrorCode=!" + idwErrorCode.ToString());
axCZKEM1.EnableDevice(iMachineNumber, true);
}
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
lblOutputInfo.Items.Add("*Operation failed,ErrorCode=!" + idwErrorCode.ToString());
axCZKEM1.EnableDevice(iMachineNumber, true);
return -1022;
}
}
prgSta.Value = 100;
axCZKEM1.RefreshData(iMachineNumber);//the data in the device should be refreshed
axCZKEM1.EnableDevice(iMachineNumber, true);
lblOutputInfo.Items.Add("Upload face successfully");
return 1;
}

It is a ZKteco error in SDK not compatible with device firmware. I faced same issue. It also happens with SpeedFace V4L

Related

How to enable/Disabe an USB device specific with C#

I try to enable/disable a specific USB device with C#.
I am a very confused because i found a lot informations, and they all contradict each other.
My first question is, the "setupapi.dll" just works in 32 bit plataform?
Anyway, my program return false when calling:
bool rstl2 = DeviceHelper.SetupDiCallClassInstaller(DeviceHelper.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
My source code:
public bool HW_Set_State( bool bEnable)
{
try
{
Guid myGUID = new Guid("{745a17a0-74d3-11d0-b6fe-00a0c90f57da}");
IntPtr hDevInfo = DeviceHelper.SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, DeviceHelper.DIGCF_ALLCLASSES | DeviceHelper.DIGCF_PRESENT);
try
{
if (hDevInfo.ToInt32() == DeviceHelper.INVALID_HANDLE_VALUE)
return false;
} catch { }
if (hDevInfo.ToInt64() == DeviceHelper.INVALID_HANDLE_VALUE)
return false;
DeviceHelper.SP_DEVINFO_DATA DeviceInfoData;
DeviceInfoData = new DeviceHelper.SP_DEVINFO_DATA();
DeviceInfoData.cbSize = 28;
DeviceInfoData.devInst = 0;
DeviceInfoData.classGuid = myGUID;
DeviceInfoData.reserved = 0;
UInt32 i;
StringBuilder DeviceName = new StringBuilder("");
DeviceName.Capacity = DeviceHelper.MAX_DEV_LEN;
for (i = 0; DeviceHelper.SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData); i++)
{
if(DeviceHelper.SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, DeviceHelper.SPDRP_DEVICEDESC, 0, DeviceName, DeviceHelper.MAX_DEV_LEN, IntPtr.Zero)){
if (DeviceName.ToString().Contains("USB Input Device"))
{
if (DeviceInfoData.classGuid.ToString().Contains("745a17a0-74d3-11d0-b6fe-00a0c90f57da"))
{
ChangeDeviceState(hDevInfo, DeviceInfoData, bEnable);
}
}
}
}
DeviceHelper.SetupDiDestroyDeviceInfoList(hDevInfo);
}
catch (Exception ex)
{
return false;
}
return true;
}
}
private bool ChangeDeviceState(IntPtr hDevInfo, DeviceHelper.SP_DEVINFO_DATA devInfoData, bool bEnable)
{
try
{
int szOfPcp;
IntPtr ptrToPcp;
int szDevInfoData;
IntPtr ptrToDevInfoData;
DeviceHelper.SP_PROPCHANGE_PARAMS pcp = new DeviceHelper.SP_PROPCHANGE_PARAMS();
if (bEnable)
{
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(DeviceHelper.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DeviceHelper.DIF_PROPERTYCHANGE;
pcp.StateChange = DeviceHelper.DICS_ENABLE;
pcp.Scope = DeviceHelper.DICS_FLAG_GLOBAL;
pcp.HwProfile = 0;
szOfPcp = Marshal.SizeOf(pcp);
ptrToPcp = Marshal.AllocHGlobal(szOfPcp);
Marshal.StructureToPtr(pcp, ptrToPcp, true);
szDevInfoData = Marshal.SizeOf(devInfoData);
ptrToDevInfoData = Marshal.AllocHGlobal(szDevInfoData);
if (DeviceHelper.SetupDiSetClassInstallParams(hDevInfo, ptrToDevInfoData, ptrToPcp, Marshal.SizeOf(typeof(DeviceHelper.SP_PROPCHANGE_PARAMS))))
{
DeviceHelper.SetupDiCallClassInstaller(DeviceHelper.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
}
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(DeviceHelper.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DeviceHelper.DIF_PROPERTYCHANGE;
pcp.StateChange = DeviceHelper.DICS_ENABLE;
pcp.Scope = DeviceHelper.DICS_FLAG_CONFIGSPECIFIC;
pcp.HwProfile = 0;
}
else
{
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(DeviceHelper.SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DeviceHelper.DIF_PROPERTYCHANGE;
pcp.StateChange = DeviceHelper.DICS_DISABLE;
pcp.Scope = DeviceHelper.DICS_FLAG_CONFIGSPECIFIC;
pcp.HwProfile = 0;
}
szOfPcp = Marshal.SizeOf(pcp);
ptrToPcp = Marshal.AllocHGlobal(szOfPcp);
Marshal.StructureToPtr(pcp, ptrToPcp, true);
szDevInfoData = Marshal.SizeOf(devInfoData);
ptrToDevInfoData = Marshal.AllocHGlobal(szDevInfoData);
Marshal.StructureToPtr(devInfoData, ptrToDevInfoData, true);
bool rslt1 = DeviceHelper.SetupDiSetClassInstallParams(hDevInfo, ptrToDevInfoData, ptrToPcp, Marshal.SizeOf(typeof(DeviceHelper.SP_PROPCHANGE_PARAMS)));
bool rstl2 = DeviceHelper.SetupDiCallClassInstaller(DeviceHelper.DIF_PROPERTYCHANGE, hDevInfo, ptrToDevInfoData);
if ((!rslt1) || (!rstl2))
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
return false;
}
}
If I wrote something wrong, I'm sorry. Im from Brazil :)
If you also prefer using WMI you can do it like this:
*Install Management NuGet
using System.Management;
*Add string with your device name/guid/deviceid.etc
public string DeviceName = "YourDeviceName";
*For Enable
ManagementObjectSearcher myDevices = new ManagementObjectSearcher("root\\CIMV2", #"SELECT * FROM Win32_PnPEntity where Name Like " + '"' + DeviceName + '"');
foreach (ManagementObject item in myDevices.Get())
{
ManagementBaseObject UWFEnable = item.InvokeMethod("Enable", null, null);
}
*For Disable
ManagementObjectSearcher myDevices = new ManagementObjectSearcher("root\\CIMV2", #"SELECT * FROM Win32_PnPEntity where Name Like " + '"' + DeviceName + '"');
foreach (ManagementObject item in smyDevices.Get())
{
ManagementBaseObject inParams = item.InvokeMethod("Disable", null, null);
}
#Edit:
You can also use devcon.exe from the Microsoft website.
I was able to achieve this by making use of the DevCon utility provided by Microsoft. The DevCon utility can be invoked by command line or with Process.Start(...).
I followed the example for disabling a device based on the device instance ID. Note that the ID argument begins with the "#" character. When I initially ran the command, I didn't notice this and it didn't enable/disable my device.
https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/devcon-examples?source=recommendations#example-31-disable-devices-by-device-instance-id
devcon disable "#USB\VID_045E&PID_0039\5&29F428A4&0&2"

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

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

How to implement "apply credit" to existing invoices if credits are available for that customer via .Net C# code by using Interop.QBFC13Lib.dll?

I got stuck when trying to implement the "apply credit" functionality of Quickbooks to existing invoices if credit is available for that customer. I am able to do it via Quickbooks Desktop UI but not getting the way to implement it via a .Net integrated app, written in C#. Can any one please guide on this.
Code which I am using to implement "apply credit" to Quickbooks via C# code.
I am getting the error: "QuickBooks found an error when parsing the provided XML text stream." with below code.
public void ApplyCreditsOnPrePayInvoices()
{
// open connection and begin session before data fetch - intentionally skipped this code
IMsgSetRequest msgset = null;
ICreditMemoQuery creditMemoQuery = null;
string sCustomerName = string.Empty;
if (this.GetConnectedToQB()) //this is the method call to login to quickbooks desktop
{
try
{
// during data fetch
msgset = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
creditMemoQuery = msgset.AppendCreditMemoQueryRq();
creditMemoQuery.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(new DateTime(2012, 3, 31), false);
IMsgSetResponse msgRes = m_sessionManager.DoRequests(msgset);
IResponseList responseList = msgRes.ResponseList;
if (responseList.Count > 0)
{
IResponse response = responseList.GetAt(0);
ICreditMemoRetList creditMemoList = response.Detail as ICreditMemoRetList;
if (creditMemoList == null)
{
return;
}
for (int i = 0; i <= creditMemoList.Count - 1; i++)
{
ICreditMemoRet qbCreditMemo = creditMemoList.GetAt(i);
if (this.GetQBCustomerListId(qbCreditMemo.CustomerRef.FullName.GetValue()) != string.Empty)
{
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IInvoiceAdd invoiceAddRq = m_requestMsgSet.AppendInvoiceAddRq();
invoiceAddRq.CustomerRef.FullName.SetValue(qbCreditMemo.CustomerRef.FullName.GetValue());
ISetCredit SetCredit1 = invoiceAddRq.SetCreditList.Append();
SetCredit1.CreditTxnID.SetValue(qbCreditMemo.TxnID.GetValue());
SetCredit1.AppliedAmount.SetValue(qbCreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseSetInvoice = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseSetInvoice);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["InvoiceAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse == "Status OK")
{
Console.WriteLine("Credit no.:" + qbCreditMemo.TxnID.GetValue() + " Customer:" + qbCreditMemo.CustomerRef.FullName.GetValue() + " Total:" + qbCreditMemo.TotalAmount.GetValue());
}
}
}
}
}
catch (Exception ex)
{
string ss = ex.Message;
//handle exception here
}
finally
{
if (msgset != null)
{
Marshal.FinalReleaseComObject(msgset);
}
if (creditMemoQuery != null)
{
Marshal.FinalReleaseComObject(creditMemoQuery);
}
}
}
// end session and close connection after data fetch - intentionally skipped this code
}
Thanks in advance!!
I got solution by using below function:-
public void ApplyCreditsOnPrePayInvoices(string sMonth, string sYear)
{
IMsgSetRequest IMsgSetRequestToQB = null;
ICreditMemoQuery ICreditMemoQueryToQB = null;
string sInvoiceTxnId = string.Empty;
string sInvoiceNumber = string.Empty;
if (this.GetConnectedToQB())
{
try
{
IMsgSetRequestToQB = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
ICreditMemoQueryToQB = IMsgSetRequestToQB.AppendCreditMemoQueryRq();
ICreditMemoQueryToQB.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTimecl.GetValue("1." + sMonth + sYear), true);
IMsgSetResponse IMsgSetResponseFromQB = m_sessionManager.DoRequests(IMsgSetRequestToQB);
IResponseList ICreditListMemoAvailable = IMsgSetResponseFromQB.ResponseList;
if (ICreditListMemoAvailable.Count > 0)
{
string sCustomerListIdQB = string.Empty;
string sCustomerAccountNumber = string.Empty;
string sQBImportPrepayAccounts = Path.Combine(Environment.CurrentDirectory, sMonth + sYear, "Step11_QBImport_PrepayAccounts.csv");
DataTable dtQBImportPrepayAccounts = Utilcl.GetDataTableFromCSVFile(sQBImportPrepayAccounts);
IResponse ICreditMemoAvailable = ICreditListMemoAvailable.GetAt(0);
ICreditMemoRetList iCreditMemoList = ICreditMemoAvailable.Detail as ICreditMemoRetList;
if (iCreditMemoList != null)
{
for (int iCtr = 0; iCtr <= iCreditMemoList.Count - 1; iCtr++)
{
ICreditMemoRet ICreditMemo = iCreditMemoList.GetAt(iCtr);
DataRow[] drInvoiceNos = dtQBImportPrepayAccounts.Select("RefNumber = '" + ICreditMemo.RefNumber.GetValue() + "'");
if (drInvoiceNos.Length > 0)
{
sInvoiceNumber = Stringcl.GetValue(drInvoiceNos[0]["RefNumber"]);
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IReceivePaymentAdd IReceivePayment = m_requestMsgSet.AppendReceivePaymentAddRq();
sInvoiceTxnId = this.GetQBInvoiceTxnIDList(ICreditMemo.CustomerRef.FullName.GetValue()); //To get the Transaction ID of Invoice
IReceivePayment.CustomerRef.FullName.SetValue(Stringcl.GetValue(ICreditMemo.CustomerRef.FullName.GetValue()));
IAppliedToTxnAdd IAppliedToTxnAddress = IReceivePayment.ORApplyPayment.AppliedToTxnAddList.Append();
IAppliedToTxnAddress.TxnID.SetValue(sInvoiceTxnId);
ISetCredit ISetCreditToInvoice = IAppliedToTxnAddress.SetCreditList.Append();
ISetCreditToInvoice.CreditTxnID.SetValue(ICreditMemo.TxnID.GetValue());
ISetCreditToInvoice.AppliedAmount.SetValue(ICreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseApplyCredit = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseApplyCredit);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["ReceivePaymentAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse != "Status OK")
{
Utilcl.LogMessage("QB Credit Memo Query Response: " + sQueryResponse);
}
}
}
}
}
}
catch (Exception ex)
{
Utilcl.LogMessage(ex);
}
finally
{
if (IMsgSetRequestToQB != null)
{
Marshal.FinalReleaseComObject(IMsgSetRequestToQB);
}
if (ICreditMemoQueryToQB != null)
{
Marshal.FinalReleaseComObject(ICreditMemoQueryToQB);
}
}
}
}

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

Add link to rich text box that starts a process (RDP)

I'm trying to add a clickable link to a rich text box that says something like "Start RDP" so when a user clicks on it, it will start windows remote desktop and use put the machine name in the box for you. Here is my code so far, It searchs Active Directory for a computer name that the user enters, pings the machine and if it is online, show its status in another textbox.
private void btnAd_Click(object sender, EventArgs e)
{
var adsb = new StringBuilder();
var mssb = new StringBuilder();
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://dc=Domain.org";
try
{
string wildcard = "*";
string adser = wildcard + txtAd.Text + wildcard;
DirectorySearcher ser = new DirectorySearcher();
ser.SizeLimit = System.Int32.MaxValue;
ser.PageSize = System.Int32.MaxValue;
ser.Filter = "(&(ObjectCategory=computer)(name=" + adser + "))"; //Only allows Computers to be returned in results.
SearchResultCollection results = ser.FindAll();
if (String.IsNullOrEmpty(txtcomputers.Text)) //if the textbox is empty, write ad search results to textbox
{
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName,..
adsb.AppendLine(temp[0].Substring(10));//returns everything after LDAP://CN= until end of temp[0].
if (Ping(temp[0].Substring(10)))
{
mssb.AppendLine(temp[0].Substring(10) + "....Online");
}
else
{
mssb.AppendLine(temp[0].Substring(10) + "....Offline");
}
}
rtbComputerstatus.Text = mssb.ToString();
txtcomputers.Text = adsb.ToString();
}
else //Add items to textbox if there are already items present.
{
txtcomputers.AppendText(Environment.NewLine);
rtbComputerstatus.AppendText(Environment.NewLine);
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(',');
adsb.AppendLine(temp[0].Substring(10));
txtcomputers.AppendText(adsb.ToString());
if (Ping(temp[0].Substring(10)))
{
mssb.AppendLine(temp[0].Substring(10) + "....Online......");
}
else
{
mssb.AppendLine(temp[0].Substring(10) + "....Offline");
}
rtbComputerstatus.AppendText(mssb.ToString());
}
}
//trims spaces
this.txtcomputers.Text = this.txtcomputers.Text.Trim();
txtcomputers.CharacterCasing = CharacterCasing.Upper;
//color items
HighlightPhrase(rtbComputerstatus, "Online",Color.Green);
HighlightPhrase(rtbComputerstatus, "Offline", Color.Red);
HighlightPhrase(rtbComputerstatus, "RDP", Color.Blue);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
de.Dispose();//Clean up resources
}
}
// color method
static void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
//ping method
public static bool Ping(string hostName)
{
bool result = false;
try
{
Ping pingSender = new Ping(); PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(hostName, timeout, buffer, options); if (reply.Status == IPStatus.Success)
{
result = true;
}
else
{
result = false;
}
}
catch
{
result = false;
}
return result;
}
Any suggestions ? I've tried a few different things but can't seem to get it working.
Thanks !
There is an article published on Codeproject, describing the solution that you are looking for: link
Hope this will help. Rgds, AB

Categories

Resources