Digital Persona - Biometrics check bringing wrong data (bringing data from another user) - c#

I basically need to bring information from users using biometrics, for this I am using a biometric reader of the digital person (U.are.U 4500).
The problem is that sometimes it happens to come information from another user, in case I put my finger on the reader, it is read and instead of returning my data, it is returned from another user.
I've noticed one thing, I'm saving biometrics in byte format ([byte]). When I am going to register biometrics, my byte array usually consists of 1000 items. When I make the comparison, the bytes are usually returned from the database, but the byte array I will use to compare with the database is 300. It may sound like bullshit, but does it have any interference? Anyway, I will make the source available !! Thank you for your help.
About the small details of the bytes that I noticed:
Bytes in register:
bytes in check:
I tried to post the images here but I was blocked by stack overflow :)
Register Biometric:
memoryTemplate = new MemoryStream();
Template.Serialize(memoryTemplate);
memoryTemplate.Position = 0;
brReader = new BinaryReader(memoryTemplate);
serializedTemplate = brReader.ReadBytes((Int32)memoryTemplate.Length);
DALUsuario usuario = new DALUsuario();
//I execute the method to register biometrics
usuario.CadastrarBiometria(Apoio.stCodUsuario, Finger, serializedTemplate);
//usuario.CadastrarBiometria:
con = new SqlConnection();
apoio = new Apoio();
con = apoio.conexaoBD(con);
command = new StringBuilder();
fkMao = VerificarMao(fkDedo);
command.Append("INSERT INTO TBL_BIOMETRIA (FK_USUARIO, FK_DEDO, FK_MAO, BIOMETRIA) ");
command.Append("VALUES (#idUser, #fkDedo, #fkMao, #Biometria)");
cmd = new SqlCommand(command.ToString(), con);
cmd.Parameters.AddWithValue("#IdUser", idUsuario);
cmd.Parameters.AddWithValue("#fkDedo", fkDedo);
cmd.Parameters.AddWithValue("#fkMao", fkMao);
cmd.Parameters.AddWithValue("#Biometria", Template);
cmd.ExecuteNonQuery();
//Biometrics Check
private void VerificationControl1_OnComplete(object Control, DPFP.FeatureSet FeatureSet, ref DPFP.Gui.EventHandlerStatus EventHandlerStatus) {
DPFP.Verification.Verification ver = new DPFP.Verification.Verification();
DPFP.Verification.Verification.Result res = new DPFP.Verification.Verification.Result();
Usuario user = null;
DALUsuario dalUser = null;
// Compare feature set with all stored templates.
user = new Usuario();
dalUser = new DALUsuario();
// I execute the method that takes the user's biometry and compares it with the one of the database
user = dalUser.RetornaBiometria(FeatureSet);
}
//dalUser.RetornaBiometria:
while (reader.Read()) {
user.iCodUsuario = Convert.ToInt32(reader["FK_USUARIO"]);
user.Biometria = (byte[]) reader["BIOMETRIA"];
memoryStream = new MemoryStream(user.Biometria);
DPFP.Template tmpObj = new DPFP.Template();
tmpObj.DeSerialize(memoryStream);
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
// I MAKE COMPARISON OF THE USER'S BIOMETRY WITH THE BIOMETRIES REGISTERED IN THE DATABASE
ver.Verify(FeatureSet, tmpObj, ref res);
Data.IsFeatureSetMatched = res.Verified;
Data.FalseAcceptRate = res.FARAchieved;
if (res.Verified) {
break; // success
}
fpTemp = null;
}

Related

GstSharp raw video pausing after gst_pad_push() = not-linked

I've been working on a small Microsoft Teams extension that takes an incoming Audio/Video feed from each participant and records the data into an mp4 file for each participant. In all the MS Teams documentation they focus on getting access to the raw data itself and gloss over any kind of persistence of it into a usable video container. The video comes in as an NV12 encoded byte array and the audio is wav format. I've been trying to use Gstreamer to take the raw video data, push it to a videoconvert then on to a filesink to try and save the data as an h264 encoded mp4. I've pulled together a mix and match of code examples and think I'm close but missing something in the process. My pipeline creates successfully but when pushing buffers into the appsrc I get the following in my console:
pausing after gst_pad_push() = not-linked
error: Internal data stream error.
error: streaming stopped, reason not-linked (-1)
The code I use to create my pipeline, pads and sinks etc is as follows:
private Gst.App.AppSrc CreatePipeline(Guid identifier, string identity, int width, int height, string directory)
{
Directory.CreateDirectory($"{directory}\\temporary\\{identifier}");
var pipeline = new Gst.Pipeline($"pipeline_{identity}");
var VideoQueue = Gst.ElementFactory.Make("queue", $"video_queue_{identity}");
var VideoConvert = Gst.ElementFactory.Make("videoconvert", $"video_convert_{identity}");
var VideoSink = Gst.ElementFactory.Make("autovideosink", $"video_sink_{identity}");
var AppQueue = Gst.ElementFactory.Make("queue", $"app_queue_{identity}");
var AppSink = new Gst.App.AppSink($"app_sink_{identity}");
var AppSource = new Gst.App.AppSrc($"app_src_{identity}");
var Tee = Gst.ElementFactory.Make("tee", $"tee_{identity}");
var FileSink = Gst.ElementFactory.Make("filesink", $"file_sink_{identity}");
AppSource.Caps = Gst.Caps.FromString($"video/x-raw,format=NV12,width={width},height={height},framerate={this.fixedFps}");
AppSource.IsLive = true;
AppSink.EmitSignals = true;
AppSink.Caps = Gst.Caps.FromString($"video/x-raw,format=NV12,width={width},height={height},framerate={this.fixedFps}");
AppSink.NewSample += NewSample;
Console.WriteLine("Setting Filesink location");
FileSink["location"] = $"{directory}\\temporary\\{identifier}\\{identity}.mp4";
pipeline.Add(AppSource, Tee, VideoQueue, VideoConvert, VideoSink, AppQueue, AppSink, FileSink);
var teeVideoPad = Tee.GetRequestPad("src_%u");
var queueVideoPad = VideoQueue.GetStaticPad("sink");
var teeAppPad = Tee.GetRequestPad("src_%u");
var queueAppPad = AppQueue.GetStaticPad("sink");
if ((teeVideoPad.Link(queueVideoPad) != Gst.PadLinkReturn.Ok) ||
(teeAppPad.Link(queueAppPad) != Gst.PadLinkReturn.Ok))
{
Console.WriteLine("Tee could not be linked.");
throw new Exception("Tee could not be linked.");
}
AppSource.PadAdded += new Gst.PadAddedHandler(this.OnVideoPadAdded);
var bus = pipeline.Bus;
bus.AddSignalWatch();
bus.Connect("message::error", HandleError);
pipeline.SetState(Gst.State.Playing);
return AppSource;
}
And this gets called every time a new participant joins the call. Then each time a new video frame is sent to the call from a participant the following code is executed:
private bool NV12toMP4(byte[] array, string identity, int width, int height, long timestamp, int length)
{
var buffer = new Gst.Buffer(null, (ulong)length, Gst.AllocationParams.Zero)
{
Pts = (ulong)timestamp,
Dts = (ulong)timestamp
};
buffer.Fill(0, array);
var ret = this.participantSources[identity].PushBuffer(buffer);
buffer.Dispose();
if (ret != Gst.FlowReturn.Ok)
{
return false;
}
return true;
}
I was expecting my PadAdded method to get called on the AppSrc when it first detects the type of input but this never gets triggered so I'm not sure where to look next on this.

How can Xamarin.Forms read json from WCF?

I'm trying to create my first Xamarin.Forms mobile app with a map and pins, so please bear with me.
I'm trying to add pins to the map. I use this code to add one pin:
map = new Map {
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
map.MoveToRegion (MapSpan.FromCenterAndRadius (
new Position (36.9628066,-122.0194722), Distance.FromMiles (3)));
var position = new Position(36.9628066,-122.0194722);
var pin = new Pin {
Type = PinType.Place,
Position = position,
Label = "Santa Cruz",
Address = "custom detail info"
};
map.Pins.Add(pin);
Now, instead of adding just one pin, I'd like to add several pins from a tsql table.
So I created a WCF service that returns a list of coordinates. One returns a json and the other returns a datatable:
public DataTable ToEraseGetCoordinates()
{
string sqlQuery = "select lat,lon from MyStores";
string connString = GetConnString();
SqlDatabase sqlDatabase = new SqlDatabase(connString);
DataSet result = sqlDatabase.ExecuteDataSet(CommandType.Text, sqlQuery);
return result.Tables[0];
}
public System.IO.Stream ToEraseGetCoordinatesJson()
{
string sqlQuery = "select lat,lon from MyStores";
string connString = GetConnString();
SqlDatabase sqlDatabase = new SqlDatabase(connString);
DataSet result = sqlDatabase.ExecuteDataSet(CommandType.Text, sqlQuery);
return ConvertToJson(result.Tables[0]);
}
I invoke the WCF like so: http://80.102.51.381:101/Service1.svc/ToEraseGetCoordinates (for an xml representation of the datatable)
For the JSON: http://80.102.51.381:101/Service1.svc/ToEraseGetCoordinatesJson, which returns this:
{"lat":25.7616,"lon":-80.1917},{"lat": 28.5383,"lon":-81.3792}
My question is: what do I next so that my Xamarin.Form reads this?
Regardless of the return type, I don't know how Xamarin will consume the WCF and draw the pins.
This earthquake map sample does basically what you want (it's a bit old, sadly).
Basically you want to download your Json (eg in this class)
// your http://80.102.51.381:101/Service1.svc/ToEraseGetCoordinatesJson would go here
var response = await client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt");
var earthquakesJson = response.Content.ReadAsStringAsync().Result;
then you need to convert the Json - but you said you've already done that
var rootobject = JsonConvert.DeserializeObject<Rootobject>(earthquakesJson);
lastly just create and add the pins to the map
var earthquakes = await webSvc.GetEarthquakesAsync();
Xamarin.Forms.Device.BeginInvokeOnMainThread( () => {
Debug.WriteLine("found " + earthquakeString.Length + " earthquakes");
label.Text = earthquakeString.Length + " earthquakes";
foreach (var earthquake in earthquakes)
{
var p = new Pin();
p.Position = new Position(earthquake.lat, earthquake.lng);
p.Label = "Magnitude: " + earthquake.magnitude;
m.Pins.Add(p);
}
});
Originally the pins weren't able to be databound, which is why it loops through to add them. Not sure if the ability to databind pings has been added to Xamarin.Forms since.
You'll probably want to keep track of the lat/longs so you can calculate a new region to set the maps view, to default to showing all the pins you added...
See the Maps docs and maps custom renderers for more info.

Rally C#: Is it possible to create a new user story along with an attachment? (Avoiding to query for the user-story reference)

Please be patient I have already gone through the example from: How to Add an Attachment to a User Story using Rally REST .NET
However the sample code requires a query to identify the newest user story reference. The sample illustrates how to add an attachment to an existing user story. I would like to accomplish: Creating a new user story along with an attachment.
Here is my method.
public void createUsWithAttachment(string workspace, string project,
string userStoryName, string userStoryDescription){
//Authenticate with Rally
this.EnsureRallyIsAuthenticated();
//UserStory Setup
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate[RallyField.workSpace] = workspace;
toCreate[RallyField.project] = project;
toCreate[RallyField.name] = userStoryName;
toCreate[RallyField.description] = userStoryDescription;
//get the image reference - assume that this is where the image lives after being downloaded from Outlook
String imageFilePath = "C:\\Users\\secret\\...";
String imageFileName = "file.png";
String fullImageFile = imageFilePath + imageFileName;
Image myImage = Image.FromFile(fullImageFile);
// Convert Image to Base64 format
string imageBase64String = imageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Png);
// Length calculated from Base64String converted back
var imageNumberBytes = Convert.FromBase64String(imageBase64String).Length;
// DynamicJSONObject for AttachmentContent
DynamicJsonObject myAttachmentContent = new DynamicJsonObject();
myAttachmentContent["Content"] = imageBase64String;
try
{
//create user story
CreateResult createUserStory = _api.Create(RallyField.hierarchicalRequirement, toCreate);
//create attachment
CreateResult myAttachmentContentCreateResult = _api.Create("AttachmentContent", myAttachmentContent);
String myAttachmentContentRef = myAttachmentContentCreateResult.Reference;
Console.WriteLine("Created: " + myAttachmentContentRef);
// DynamicJSONObject for Attachment Container
DynamicJsonObject myAttachment = new DynamicJsonObject();
//Note the below commented line
/*myAttachment["Artifact"] = ;*/
myAttachment["Content"] = myAttachmentContentRef;
myAttachment["Name"] = "AttachmentFromREST.png";
myAttachment["Description"] = "Attachment Desc";
myAttachment["ContentType"] = "image/png";
myAttachment["Size"] = imageNumberBytes;
//create attachment
CreateResult myAttachmentCreateResult = _api.Create("Attachment", myAttachment);
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
}
In the above commented line I need to get a reference to the created user story which I can do, but that would require another method to fetch the user story which I have.
However I am wondering if this can be accomplished a different way similar to how we can create a user story with the dynamicJsonObject staging.
I was thinking something like this would work, but I am having a tough time.
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate[RallyField.workSpace] = workspace;
toCreate[RallyField.project] = project;
toCreate[RallyField.name] = userStoryName;
toCreate[RallyField.description] = userStoryDescription;
toCreate["Content"] = imageToBase64;
CreateResult createUserStory = _api.Create(RallyField.hierarchicalRequirement, toCreate);
My above assumption is not going as planned and I was wondering if there is a way to create a new user story with an attachment, without having to query for the userstory reference as neatly illustrated in the example from the link provided.
Thanks and credit to the author from the example in the link.
You should already have what you need to associate it from the create result:
myAttachment["Artifact"] = createUserStory.Reference;

How to update an existing exchange rate

Using the ExchangeRateServiceClient every time I try to use client.create for currency a currency code pair I get an exception
Cannot create a record in Exchange rate currency pair (ExchangeRateCurrencyPair). From currency: USD, EUR. The record already exists.
System.Exception {System.ServiceModel.FaultException}
I am brand new to the AX API...I am using C#
AXDev09.ExchangeRateServiceCreateRequest request =
new AXDev09.ExchangeRateServiceCreateRequest();
AXDev09.ExchangeRateServiceClient client = new AXDev09.ExchangeRateServiceClient();
request.CallContext = new AXDev09.CallContext();
request.CallContext.Language = "en-us";
request.CallContext.Company = "T51";
request.CallContext.MessageId = Guid.NewGuid().ToString();
AXDev09.AxdEntity_CurrencyPair[] myPair = new AXDev09.AxdEntity_CurrencyPair[1];
myPair[0] = new AXDev09.AxdEntity_CurrencyPair();
myPair[0].ToCurrencyCode = "EUR";
myPair[0].FromCurrencyCode = "USD";
AXDev09.AxdEntity_ExchangeRate[] myExchange = new AXDev09.AxdEntity_ExchangeRate[1];
myExchange[0] = new AXDev09.AxdEntity_ExchangeRate();
myExchange[0].ExchangeRate = Convert.ToDecimal("0.708");
myExchange[0].ExchangeRateSpecified = true;
myPair[0].ExchangeRate = myExchange;
myPair[0].ExchangeRateDisplayFactor = AXDev09.AxdEnum_ExchangeRateDisplayFactor.One;
myPair[0].ExchangeRateType = "Average";
AxdType_DateTime myFromDate = new AxdType_DateTime();
myFromDate.localDateTime = DateTime.Now.ToUniversalTime();
myFromDate.timezone = AxdEnum_Timezone.GMTMINUS0600CENTRALTIME;
myFromDate.Value = myFromDate.localDateTime;
AxdType_DateTime myToDate = new AxdType_DateTime();
myToDate.localDateTime = DateTime.Now.ToUniversalTime();
myToDate.timezone = AxdEnum_Timezone.GMTMINUS0600CENTRALTIME;
myToDate.Value = myToDate.localDateTime;
request.LedgerExchangeRate = new AXDev09.AxdLedgerExchangeRate();
request.LedgerExchangeRate.CurrencyPair = myPair;
request.LedgerExchangeRate.ValidFromDateTime = myFromDate;
request.LedgerExchangeRate.ValidToDateTime = myToDate;
client.Open();
client.create(request.CallContext, request.LedgerExchangeRate);
client.Close();
The ExchangeRateServiceClient does appear to be a standard API.
The standards web service is called LedgerExchangeRateService.
If you provide two currencies, then try to reverse them.
if the error message is to be believed, seems like the issue is when it tries to create the ExchangeRateCurrencyPair
there is a no-duplicates index on:
fromCurrency
toCurrency
ExchangeRateType
"I am trying to add a new currency rate...with a new set from from-to but I keep getting "The record already exists" error eventhough I'm setting new FROM-TO dates."
it seems to be objecting to ExchangeRateCurrencyPair(not to the date effective bits) maybe try selecting the pair instead of attempting to create it every time--or maybe try debugging through a successful new pair to see if a tweak may be needed in the standard service

Payment not being created

My payments are not showing up in QuickBooks.
I can successfully create and update Customers. I can also successfully create and update Invoices. I cannot create Payments. But here's the thing, when I execute the Update command on my Payment object I do get a proper Id and Domain (NG) passed back. I've checked the Sync log file (IntuitSyncManagerLogger.log) after running a Sync but it has no error messages. Everything looks ok, there just is no payment associated with the invoice in QuickBooks.
I believe I'm setting all of the required fields but I'm not sure about two of them.
1) The PaymentLine has a field named TxnId. I'm setting it to be the Id and Domain of the InvoiceHeader, but am not sure if this is correct.
2) There is another required field (per the documentation) but I'm leaving it blank as I don't know what to populate it with. It's the DiscountAccountId field. I don't want a discount associated with the invoice.
Here is my code...
SqlConnection connection = new SqlConnection(m_connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("dbo.Intuit_GetPayment", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#glmvSyncId", SqlDbType.Int).Value = glmvSyncId;
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Intuit.Ipp.Data.Qbd.PaymentHeader paymentHeader = new Intuit.Ipp.Data.Qbd.PaymentHeader();
paymentHeader.ARAccountId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QB,
Value = "37"
};
paymentHeader.ARAccountName = "Accounts Receivable";
paymentHeader.DepositToAccountId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QB,
Value = "35"
};
paymentHeader.DepositToAccountName = "Undeposited Funds";
paymentHeader.CustomerId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = (rdr["cust_iddomain"].ToString() == "QB" ? Intuit.Ipp.Data.Qbd.idDomainEnum.QB : Intuit.Ipp.Data.Qbd.idDomainEnum.NG),
Value = rdr["cust_idvalue"].ToString()
}; // cust_iddomain and cust_idvalue are from the Customer
paymentHeader.DocNumber = rdr["invoicekey"].ToString();
paymentHeader.TxnDate = DateTime.Now;
List<Intuit.Ipp.Data.Qbd.PaymentLine> listLine = new List<Intuit.Ipp.Data.Qbd.PaymentLine>();
var paymentLine = new Intuit.Ipp.Data.Qbd.PaymentLine();
paymentLine.Amount = Convert.ToDecimal(rdr["amount"]);
paymentLine.TxnId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = (rdr["invc_iddomain"].ToString() == "QB" ? Intuit.Ipp.Data.Qbd.idDomainEnum.QB : Intuit.Ipp.Data.Qbd.idDomainEnum.NG),
Value = rdr["invc_idvalue"].ToString()
}; // invc_iddomain and invc_idvalue are from the InvoiceHeader
listLine.Add(paymentLine);
Intuit.Ipp.Data.Qbd.Payment syncPayment = new Intuit.Ipp.Data.Qbd.Payment();
syncPayment.Header = paymentHeader;
syncPayment.Line = listLine.ToArray();
connection.Close();
Intuit.Ipp.Data.Qbd.Payment resultPayment = new Intuit.Ipp.Data.Qbd.Payment();
resultPayment = commonService.Add(syncPayment);
I suspect the problem is with TxnId.
All I'm doing is creating a Customer, then creating an Invoice for the Customer, then creating a Payment for the Invoice. Am I missing a object someplace?
Any and all help is greatly appreciated.
The Payment is likely going into an error state after sync. You can check by executing a PaymentQuery and setting ErroredObjectsOnly=true.
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0100_Calling_Data_Services/0015_Retrieving_Objects#Objects_in_Error_State
If the entity is in error state, you can query for the specific reason using the Status API:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0600_Object_Reference/SyncStatus
SyncStatusRequest syncStatusRequest = new SyncStatusRequest();
syncStatusRequest.ErroredObjectsOnly = true;
syncStatusRequest.NgIdSet = new NgIdSet[] { new NgIdSet { NgId = <<EnterYourNgIdHere>>, NgObjectType = objectName.Payment } };
SyncStatusResponse[] response = dataServices.GetSyncStatus(syncStatusRequest);
If the payment is in error state, you can delete the entity from the cloud since it was never synced with QuickBooks:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0100_Calling_Data_Services/Deleting_an_Object
If a successful sync did occur with the entity at least once, but then an Update pushed it into error state, you will need to do a Revert:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0100_Calling_Data_Services/Reverting_an_Object
You can also try doing an Update directly on the entity in error state once you know the reason from the Status API, but it is not documented so it may not work.
Adding the following lines of code seems to have fixed the problem. The Payment is now being recorded in QuickBooks.
paymentHeader.TotalAmt = Convert.ToDecimal(rdr["amount"]);
paymentHeader.TotalAmtSpecified = true;

Categories