Send Print Command from Xamarin.Android to bluetooth printer - xamarin

So I am pretty new to Xamarin.Android, I have managed to connect to my Bluetooth printer device using the code below, so now I want to send a print command to the printer but I have not been able to for several weeks now. Searched the internet but I have not been able to find a solution. Any assistance will be greatly appreciated
Button btnConnect;
TextView txtView;
Button btnPrint;
BluetoothSocket socket;
BluetoothAdapter adapter;
BluetoothDevice bluetoothDevice;
private byte[] buffer;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.BrianPeek);
FindViews();
HandleEvents();
buffer = new byte[1024];
}
private void HandleEvents()
{
btnConnect.Click += BtnConnect_Click;
btnPrint.Click += Print_Click;
}
private void Print_Click(object sender, EventArgs e)
{
// Variables
string ipAddress = "192.168.1.100";
int portNumber = 9100;
List<string> myText = new List<string>() { "Line1", "Line2" };
// Try to find the platform specific services
// var printer = DependencyService.Get<DSInterfaces.IPrinter>();
var printer = new Printer();
if (printer == null) {
// Do not proceed if no services found for the platform
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Printer");
alert.SetMessage("Error");
alert.Show();
}
try
{
// Call themethod, declare by the IPrinter interface
printer.Print(ipAddress, portNumber, myText);
}
catch (Exception ex)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Printer");
alert.SetMessage("Failed to print redemption slip\nReason "+ex.Message);
alert.Show();
// Exception here could mean difficulties in connecting to the printer etc
//await DisplayAlert("Error", $"Failed to print redemption slip\nReason: {ex.Message}", "OK");
}
}
private async void BtnConnect_Click(object sender, EventArgs e)
{
adapter = BluetoothAdapter.DefaultAdapter;
if(adapter == null) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("No Bluetooth Adapter Found");
alert.Show();
}
if (!adapter.IsEnabled) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("Bluetooth Adapter is not set!");
alert.Show();
}
bluetoothDevice = (from bd in adapter.BondedDevices
where bd.Name == "MTP-II"
select bd).FirstOrDefault();
if (bluetoothDevice != null) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("Bluetooth device " + bluetoothDevice.Name );
alert.Show();
//Connect Bluetooth Device
socket = bluetoothDevice.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
await socket.ConnectAsync();
//after connection, communication occurs through input and output stream
// Read data from the device
await socket.InputStream.ReadAsync(buffer, 0, buffer.Length);
// Write data to the device
await socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("The device is not found");
alert.Show();
}
}
private void FindViews()
{
btnConnect = FindViewById<Button>(Resource.Id.btnConnectBlue);
txtView = FindViewById<TextView>(Resource.Id.txtText);
btnPrint = FindViewById<Button>(Resource.Id.btnConnectPrint);
}

Related

ZKEmkeeper: Events not triggering on Windows Service

I'm stucked for a while trying to use zkemkeeper sdk to use on a Windows Service that uses a InBios(Controller) for fingerprint.
i first connect to the device and then i add the event OnAttTransactionEx, someone can point me what i'm doing wrong.
Here is the code snippet
`
protected override void OnStart(string[] args)
{
Thread TT = new Thread(new ThreadStart(WorkedThread));
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
this.isServiceStarted = true;
TT.Start();
}
private void WorkedThread()
{
WriteToFile("Worker Thread Started.");
ZKemClient objZkeeper = new ZKemClient(filepath);
this.isDeviceConnected = objZkeeper.Connect_Net("19x.x.x.24x", 4370);
if (this.isDeviceConnected)
{
WriteToFile("Device connected.");
WriteToFile("While loop execution starting.");
while (true)
{
WriteToFile(filepath, "While loop execution started.");
}
}
else
{
WriteToFile("Failed to connect to Device.");
}
}
// ZMClient class
public bool Connect_Net(string IPAdd, int Port)
{
bool bResult = false;
try
{
// Actual SDK class
CZKEM objCZKEM = new CZKEM();
if (objCZKEM.Connect_Net(IPAdd, Port))
{
if (objCZKEM.RegEvent(1, 32767))
{
// [ Register your events here ]
objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
}
bResult = true;
}
}
catch (Exception ex)
{
WriteToFile("Connect_Net() Exception->" + ex.Message);
}
return bResult;
}
`
After playing a lot with threading, found a solution.
For windows service - Add reference to System.Windows.Forms
Thread TT1 = new Thread(() =>
{
this.objCZKEM = new CZKEM();
Application.Run();
});
TT1.IsBackground = true;
TT1.SetApartmentState(ApartmentState.STA);
TT1.Start();
Simply continue with current thread
if (this.objCZKEM.Connect_Net(IP, 4370))
{
this.WriteToFile("ZKEM device connected");
if (this.objCZKEM.RegEvent(1, 32767))
{
this.WriteToFile("ZKEM device events registration started");
// [ Register your events here ]
this.objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
this.WriteToFile("Done with ZKEM device events registration.");
}
You should not able to receive finger events from device.

what is the best way to find out the reason that Application crashed on startup?

i am now having the problem: when I start debuging, the app crashes directly and the debug process stops. I can not see any log or error message. I don't know what can I do in this situation?
I tried to add -v -v -v -v to adtional mtouch argument. but did not see anything print out while the app just stoped the debuging.
Is there a way to solve such problem?
best regards
Lin
You should try to catch unhandled exception like this
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
...
#region Error handling
private void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", e.Exception);
LogUnhandledException(newExc);
}
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", e.ExceptionObject as Exception);
LogUnhandledException(newExc);
}
internal static void LogUnhandledException(Exception exception)
{
try
{
const string errorFileName = "Fatal.log";
var libraryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Resources); // iOS: Environment.SpecialFolder.Resources
var errorFilePath = Path.Combine(libraryPath, errorFileName);
var errorMessage = string.Format("Time: {0}\r\nError: Unhandled Exception\r\n{1}",
DateTime.Now, exception.ToString());
File.WriteAllText(errorFilePath, errorMessage);
}
catch
{
// just suppress any error logging exceptions
}
}
// If there is an unhandled exception, the exception information is diplayed
// on screen the next time the app is started (only in debug configuration)
[Conditional("DEBUG")]
private static void DisplayCrashReport()
{
const string errorFilename = "Fatal.log";
var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Resources);
var errorFilePath = Path.Combine(libraryPath, errorFilename);
if (!File.Exists(errorFilePath))
{
return;
}
var errorText = File.ReadAllText(errorFilePath);
var alertView = new UIAlertView("Crash Report", errorText, null, "Close", "Clear") { UserInteractionEnabled = true };
alertView.Clicked += (sender, args) =>
{
if (args.ButtonIndex != 0)
{
File.Delete(errorFilePath);
}
};
alertView.Show();
}
#endregion
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
global::Xamarin.Forms.Forms.Init();
global::XamForms.Controls.iOS.Calendar.Init();
global::ZXing.Net.Mobile.Forms.iOS.Platform.Init();
Firebase.Core.App.Configure();
Messaging.SharedInstance.Delegate = this;
DependencyService.Register<IJumpinNotificationService, JumpinNotificationService>();
DependencyService.Register<IJumpinPublicKeyValidateService, JumpinPublicKeyValidateService>();
LoadApplication(new App());
InstanceId.Notifications.ObserveTokenRefresh(TokenRefreshNotification);
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10 or later
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
Console.WriteLine(granted);
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
//Messaging.SharedInstance.RemoteMessageDelegate = this;
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {
// Handle approval
});
UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {
var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
});
return base.FinishedLaunching(app, options);
}

How do we get the SmtpServer NetworkCredentials while using a mail service in Xamarin Forms?

I am implementing a simple Forgot password, feature in my Xamarin Forms app. When the player provides an email in the text field, will check if the email exists in the database, if yes, will get the password associated with that email and send the password to that email.
In the following smtp step SmtpServer.Credentials = new System.Net.NetworkCredential("email", "password");from where do we get the credentials to provide in Network credentials as email / password ?
namespace soccerapp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ForgotPassword : ContentPage
{
private SQLiteConnection conn;
string emailText;
public ForgotPassword()
{
InitializeComponent();
conn = DependencyService.Get<Isqlite>().GetConnection();
}
public void btnSend_Clicked(object sender, EventArgs e)
{
emailText = txtEmail.Text;
int count = (from x in conn.Table<PlayerDetails>().Where(x => x.Email == emailText) select x).Count();
if (count != 0)
{
var detail = conn.Table<PlayerDetails>().First(x => x.Email == emailText);
var playerPassword = detail.Password;
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("admin#somesite.nz");
mail.To.Add(emailText);
mail.Subject = "Hello";
mail.Body = "Your soccer password: "+playerPassword;
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("some_email#gmail.com", "password");
SmtpServer.Send(mail);
}
catch (Exception ex)
{
DisplayAlert("Faild", ex.Message, "OK");
}
}
}
}
}

How to use or implement Broadcast Receiver in Xamarin.Form

How to use Broadcast Reciever in Xamarin.Form reference to this forum http://forums.xamarin.com/discussion/7070/how-to-prevent-sms-going-to-inbox
the class
public class SmsReceiver : BroadcastReceiver
{
public static readonly string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
public override void OnReceive(Context context, Intent intent)
{
InvokeAbortBroadcast();
try
{
if (intent.Action != IntentAction) return;
var bundle = intent.Extras;
if (bundle == null) return;
var pdus = bundle.Get("pdus");
var castedPdus = JNIEnv.GetArray<Java.Lang.Object>(pdus.Handle);
var msgs = new SmsMessage[castedPdus.Length];
var sb = new StringBuilder();
String sender = null;
for (var i = 0; i < msgs.Length; i++)
{
var bytes = new byte[JNIEnv.GetArrayLength(castedPdus[i].Handle)];
JNIEnv.CopyArray(castedPdus[i].Handle, bytes);
msgs[i] = SmsMessage.CreateFromPdu(bytes);
if (sender == null) sender = msgs[i].OriginatingAddress;
sb.Append(string.Format("SMS From: {0}{1}Body: {2}{1}", msgs[i].OriginatingAddress,
System.Environment.NewLine, msgs[i].MessageBody));
}
if (sender != null && sender.EndsWith("09068100820"))
{
// Process our sms...
// SMS.updateMessageBox("\nFrom: " + msg.getOriginatingAddress() + "\n" +
//"Message: " + msg.getMessageBody() + "\n");
/*((SMS) context).delete();*/
Toast.MakeText(context, "IsOrderedBroadcast :" + IsOrderedBroadcast.ToString() + "\n" + sb.ToString(), ToastLength.Long).Show();
}
else
{
ClearAbortBroadcast();
}
}
catch (Exception ex)
{
Toast.MakeText(context, ex.Message, ToastLength.Long).Show();
}
}
}
How to implement this class in Xamarin.Form and get the incoming SMS, Thanks in advance and Good Day :D
From Android 4.4, You can't do any kind of operation on SMS except just reading it if your app isn't the default SMS app.
If your app is default sms app and you want to block sender or whatever then put your SmsReceiver in Android Project and register it in Application class.
I don't think you need to do anything in Forms Project.

Issue while Playing, the recorded audio in WP7

Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.

Resources