C# read/write mifare nfc tag - c#

I've searched a lot but I'm not able to find some C# simple sdk that lets me write and read in a nfc mifare 1k classic tags.
Could you give me some help please?
Thanks a lot.

Just check my library for ACR122u readers. It also supports insert/discard events. It is so simple to use it. Basically you create a class and register two events to that class. Afterwards, call the Watch function. It watches the changes on your device.
//Initializing
NFCReader NFC = new NFCReader();
//Inserted Event
NFC.CardInserted += new NFCReader.CardEventHandler(...Some function);
//Ejected Event
NFC.CardEjected += new NFCReader.CardEventHandler(... Some function);
//Enabling Event Watching
NFC.Watch();
If any change occurs, it calls the related event. You handle what you want to do there.
public void Card_Inserted()
{
try
{
if (NFC.Connect())
{
//Do stuff like NFC.GetCardUID(); ...
}
else
{
//Give error message about connection...
}
}
catch (Exception ex)
{
//Something went wrong
}
}
public void Card_Ejected()
{
//Do stuff...
NFC.Disconnect();
}
See the related repo and links for more information.
Medium introduction tutorial:
https://medium.com/#hakbas/nfcreader-a-very-simple-nfc-library-for-c-that-supports-insert-and-discard-events-93db29f79b5
Github address:
https://github.com/h4kbas/NfcReader

Related

Proper way to set up and use custom event log in .NET service?

I found several topics on this already, but somehow they all managed to avoid the real problem solution/assumed the obvious.
(e.g. here, here, here, here, here)
I am checking for and creating new event log + source during installation, and specifying them to be used during operation, but still somehow "EventSourceName" events end up in Application Log.
Why is that?
Here are snippets out of my code:
Installer:
namespace Service_Name
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
if (!System.Diagnostics.EventLog.SourceExists("EventSourceName"))
{
System.Diagnostics.EventLog.CreateEventSource(
"EventSourceName", "EventLogName");
}
InitializeComponent();
}
private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
}
}
}
Service:
public Service_Name()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ServiceEventLog = new EventLog();
ServiceEventLog.Source = "EventSourceName"; // This is different from Service Name
ServiceEventLog.Log = "EventLogName"; // This is different from Service Name
..
ServiceEventLog.WriteEntry("Service Init");
Worker = new Thread(CodeWorker);
Worker.Start();
}
private void CodeWorker()
{
//.. operational code
while (true)
{
try
{
//.. operational code
ServiceEventLog.WriteEntry("<operational event data here>", (EventLogEntryType)4, 0);
}
catch (Exception Error)
{
ServiceEventLog.WriteEntry(string.Format("<error event data here>", (EventLogEntryType)1, 0);
throw;
}
//.. operational code
}
}
As it turns out, the code works perfectly as is, however there is important thing to remember when working with event log;
EventLog.CreateEventSource Method has an important footnote:
If a source has already been mapped to a log and you remap it to a new
log, you must restart the computer for the changes to take effect.
I had mapped the source prior, to another event log which was named the same as Service itself. Using same name as the service itself caused multiple other issues and I ended up fixing that by using another log name, but did not restart test system prior to doing tests on new code version.
But as Caius Jard pointed out below, parts of the code are redundant:
ServiceEventLog.Log = "EventLogName" does not need to be specified as Source is already registered to Log.
The documentation states "If you change the Log property after the Source property has been set, writing a log entry throws an exception.".
The sample code on MSDN just sets the Source property and then calls WriteEvent, it does not then set the Log beforehand or after setting Source
I recommend you remove the call to setting the Log property; I suspect your call to WriteEvent is crashing, and being in a try catch the call in the catch is also crashing. Perhaps it's not an ideal code structure to "try writing to this log and if it fails, try writing to this log" if it's the "writing to log" that is failing

C# Best Practice used for application multithreading log building cross-form instance

I'm building a UI which consists of one main Form with possible instances of additional forms and custom classes. What I'm still missing is a consistent way of logging errors. So what I do is I created try-catch blocks around all code that could generate errors, mainly the things that process incoming data. I'm receiving a constant data flow (JSON) from some site, so the built in threading functionality of the framework makes it a multi threading application. Again, the multi threading part is the built-in functionality, I'm not doing this myself actively, since I'm not that smart yet, from a C# point of view. ;)
For the logging part, I've got the code below from here. Even though I'm not so smart yet, I do think I actually understand what is going on there. My concern/question however, is this: how do I implement a Multi-Threading logging mechanism that writes errors to ONE log file cross-form cross-class.
Here is an example that you can use a reference:
// MyMainForm.cs
namespace MyNameSpace
{
public partial class MyMainForm : Form
{
FooClass MyClass = new FooClass(); //<< errors could occur here
Form f = new MyForm(); //<< errors could occur here
... //<< errors could occur here
}
}
// FooClass.cs
namespace MyNameSpace
{
public class FooClass
{
public string ErrorGeneratingMethod()
{
try...catch(Exception e) { /* Write to Log file */ }
}
}
}
// Don't really know where to put this...
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
public void WriteToFileThreadSafe(string text, string context)
{
string t = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
string path = Properties.Settings.Default.FQLogFileLocation;
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try
{
// Append text to the file
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("[" + t + "]["+ context + "]" + text);
sw.Close();
}
} catch (Exception e)
{
MessageBox.Show(e.Message); // Really Exceptional (should never happen)
}
finally
{
// Release lock
_readWriteLock.ExitWriteLock();
}
}
So basically what is important for me to know is where do I put WriteToFileThreadSafe() together with _readWriteLock?
And how do I safely use this function in multiple threads in multiple forms and classes?
Thanks a lot in advance for letting me learn from you guru's :)

Android Activity destroyed when calling ZXing barcode scanner. How to recover?

First of all, I'm using, Xamarin with MvvmCross.
In my ViewModel, I'm using the ZXing MobileBarcodeScanner class to scan a barcode when the user clicks a button:
var scanner = new MobileBarcodeScanner();
var result = await scanner.Scan();
if (result != null)
{
CodigoProduto = result.Text;
InternalPesquisarProduto();
}
After the scan, I run the InternalPesquisarProduto void, that search for data on a remote server, based of course, on the barcode that was read. This method, also display some loading message while the data is fetched:
Ui.DisplayLoading("Searching...", "Searching data");
// Code that fetches the data
Ui.DismissLoading();
The Ui is a property on my ViewModel defined like this:
protected IUiInteractor Ui { get; set; }
I receive it by dependency injection. Here is the relevant code from the implementation being used in this scenario:
public class AndroidUiInteractor : IUiInteractor
{
private IMvxAndroidCurrentTopActivity _mvxCurrentTopActivity;
public AndroidUiInteractor(IMvxAndroidCurrentTopActivity mvxCurrentTopActivity)
{
_mvxCurrentTopActivity = mvxCurrentTopActivity;
}
public void DisplayLoading(string title, string message)
{
_mvxCurrentTopActivity.Activity.RunOnUiThread(() =>
{
_progressDlg = new ProgressDialog(_mvxCurrentTopActivity.Activity);
// Configuring the title and the message
_progressDlg.Show();
});
}
}
The problem is that when the scanner.Scan is called, my caller activity is destroyed, so when I call the Ui.DisplayLoading, the _mvxCurrentTopActivity.Activity is null.
What is most weird about this case, is that I have two Samsungs with Android 5.0 API 21 that I use in my tests, and this problem only happens in one of them, on the other, the activity is not destroyed when calling the scanner.Scan.
Note: I'm sorry for anything wrong in the code, but because of company policies, I can only access the internet by Terminal Service, and the Ctrl + V is disabled on it.
It turns out the problem was in the device. After reseting it's configurations it worked properly.
This might not be a definitive solution for everyone that faces that problem, but in my scenario it could be done.

C# - Skype Auto Accept Contact Request

So I'm currently working on a Skype bot thing, I wish it could automatically accept contact request so I don't have to do them manually, any idea how?
And while I was researching, I found this
ichat.AcceptAdd();
Any idea what does that do?
I don't know if I understood what you want to accomplish..
Do you want to accept contact requests automatically? Really? Do you like being target for hackers, spammers, etc? :)
Anyway, if that's what you want to do, you can subscribe to the UserAuthorizationRequestReceived event:
var events = (_ISkypeEvents_Event) _skype;
events.UserAuthorizationRequestReceived += UserAuthorizationRequestReceived;
try
{
_skype.Attach(8);
}
catch(COMException ce)
{
RaiseErrorEvent("Unable to attach to skype.", ce);
}
private void UserAuthorizationRequestReceived(SKYPE4COMLib.User puser)
{
if (do some user check here?? )
{
puser.IsAuthorized = true;
}
}
Hope this helps.

Detect Office Communicator Audio Call

What im trying to do is a functionality that will advice users that make
audio calls in office communicator over a wireless connection to use a
wired connection instead.
i have been looking around but have not been able to find the info im searching for
Im looking for a way to detect if Office Communicator is in an Audio call.
is there an easy way to do this?
I don't think you'll be able to get exactly what you need with Communicator, but you can get close. (you could probably get even closer, or all the way there, if you were to upgrade to Lync).
You'll need to use the Automation API - documentation here, download here.
First thing to try is catching the users status changes:
MessengerClass _communicator;
public Form1()
{
InitializeComponent();
_communicator = new MessengerClass();
_communicator.OnMyStatusChange += new DMessengerEvents_OnMyStatusChangeEventHandler(_communicator_OnMyStatusChange);
}
void _communicator_OnMyStatusChange(int hr, MISTATUS mMyStatus)
{
AddText(string.Format("My Status changed to '{0}'", mMyStatus));
}
You're looking for a status of MISTATUS_ON_THE_PHONE
The downside of this is that certain statuses will override the MISTATUS_ON_THE_PHONE status. e.g. if the user is set to "Online", and then makes or receives a call, the status will change to MISTATUS_ON_THE_PHONE. But if their status is set to "Do not Disturb" and they make or receive a call, the status will NOT change to MISTATUS_ON_THE_PHONE.
You can maybe work around this a bit by examining the call as it is created. Catching a new conversation window being created is fairly straightforward:
_communicator = new MessengerClass();
_communicator.OnIMWindowCreated += new DMessengerEvents_OnIMWindowCreatedEventHandler(_communicator_OnIMWindowCreated);
Problem is, this will fire for IM and AV conversations, and also for incoming conversations as well as outgoing. There is no way to directly detect whether the call is an outgoing audio call.
You can also catch the "Contact Added" event, this will give you some info about which recipients get added to the conversation, and when. It's possible that the order in which this happens will give you some info as to whether its outgoing or incoming, and you could look for "tel:" uri's being added to tell you if the call is to a phone (although this won't help for communicator to communicator calls)
_communicator.OnIMWindowContactAdded += new DMessengerEvents_OnIMWindowContactAddedEventHandler(_communicator_OnIMWindowContactAdded);
The best thing to do is to have a play around with the events, and see what happens under which circumstances. This code should get you up and running with that.
MessengerClass _communicator;
public Form1()
{
InitializeComponent();
_communicator = new MessengerClass();
_communicator.OnIMWindowCreated += new DMessengerEvents_OnIMWindowCreatedEventHandler(_communicator_OnIMWindowCreated);
_communicator.OnIMWindowDestroyed += new DMessengerEvents_OnIMWindowDestroyedEventHandler(_communicator_OnIMWindowDestroyed);
_communicator.OnIMWindowContactAdded += new DMessengerEvents_OnIMWindowContactAddedEventHandler(_communicator_OnIMWindowContactAdded);
_communicator.OnIMWindowContactRemoved += new DMessengerEvents_OnIMWindowContactRemovedEventHandler(_communicator_OnIMWindowContactRemoved);
_communicator.OnMyStatusChange += new DMessengerEvents_OnMyStatusChangeEventHandler(_communicator_OnMyStatusChange);
}
void _communicator_OnMyStatusChange(int hr, MISTATUS mMyStatus)
{
AddText(string.Format("My Status changed to '{0}'", mMyStatus));
}
void _communicator_OnIMWindowContactRemoved(object pContact, object pIMWindow)
{
AddText(string.Format("{0} - Participant removed - '{1}'", ((IMessengerConversationWndAdvanced)pIMWindow).HWND, ((IMessengerContactAdvanced)pContact).SigninName));
}
void _communicator_OnIMWindowContactAdded(object pContact, object pIMWindow)
{
AddText(string.Format("{0} - Participant added - '{1}'", ((IMessengerConversationWndAdvanced)pIMWindow).HWND, ((IMessengerContactAdvanced)pContact).SigninName));
}
void _communicator_OnIMWindowDestroyed(object pIMWindow)
{
AddText(string.Format("{0} Conversation Closed, duration = {1}", ((IMessengerConversationWndAdvanced)pIMWindow).HWND, (DateTime.Now - _start).ToString()));
}
void _communicator_OnIMWindowCreated(object pIMWindow)
{
try
{
AddText(string.Format("{0} Conversation Created", ((IMessengerConversationWndAdvanced)pIMWindow).HWND));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private delegate void AddTextDelegate(string text);
private void AddText(string text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new AddTextDelegate(AddText), text);
return;
}
textBox1.Text += text + "\r\n";
}
By the way, don't forget to accept this as the answer using the "tick", if you feel that it helped :)

Categories

Resources