Connect to EPSON ePOS t88V printer from .NET UWP - c#

I am trying to connect to an EPSON ePOS t88V printer from my .NET UWP application, using the drivers and SDK found here: https://download.epson-biz.com/modules/pos/index.php?page=prod&pcat=3&pid=36
I have deployed the official UWP sample app (https://download.epson-biz.com/modules/pos/index.php?page=single_soft&cid=5592&pcat=3&pid=36) to the POS, but the application wasn't able to discover the printer.
Then, I tried to build a minimal app, following the code snippets from the user manual:
using System;
...
using Epson.Epos.Epos2;
using Epson.Epos.Epos2.Printer;
namespace PrinterTest1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
Printer printer = null;
PrinterStatusInfo status = null;
public MainPage()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
printer = new Printer(Series.TM_T88, ModelLang.Ank);
printer.Received += Printer_Received;
printer.AddText("Deeeeerp.");
await printer.ConnectAsync("TCP:10.10.10.133", Printer.PARAM_DEFAULT); //this line throws an exception
await printer.BeginTransactionAsync();
await printer.SendDataAsync(Printer.PARAM_DEFAULT);
}
catch (Exception ex)
{
}
}
private void Printer_Received(Printer sender, ReceivedEventArgs args)
{
DoStuff();
}
private async void DoStuff()
{
try
{
status = printer.GetStatusAsync().GetResults();
if (status.Connection == Connection.True && status.Online == Online.True)
{
await printer.SendDataAsync(Printer.PARAM_DEFAULT);
}
}
catch (Exception ex)
{
}
}
}
}
but I am still not being able to connect to the printer. I am getting this exception:
{System.Exception: Exception from HRESULT: 0xA0048201 at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at PrinterTest1.MainPage.d__3.MoveNext()}

Take a look at the Universal Windows apps SDK
This allows you to connect to network printers.

See this code
Of course after installing the printer SDK
Printer printer = null;
try
{
printer = new Printer(Series.TM_T82, ModelLang.Ank);
printer.Received += Printer_Received;
printer.Buffer(order);
// Connect to printer through wifi
// Find printer from MAC address
await printer.ConnectAsync("TCP:64:EB:8C:2C:5B:4F", Printer.PARAM_DEFAULT);
await printer.BeginTransactionAsync();
// Send data to the printer
PrinterStatusInfo status = await printer.GetStatusAsync();
if (status.Connection == Connection.True && status.Online == Online.True)
{
await printer.SendDataAsync(Printer.PARAM_DEFAULT);
}
// Haven't figure out issue:
// If not delayed an ERR_PROCESSING is caught
await Task.Delay(1500);
//
await printer.EndTransactionAsync();
await printer.DisconnectAsync();
}
catch (Exception ex)
{
foreach (PropertyInfo prop in typeof(ErrorStatus).GetProperties())
{
if((int)prop.GetValue(null) == ex.HResult)
{
throw new Exception(prop.Name);
}
}
throw new Exception(ex.Message);
}
printer.ClearCommandBuffer();
printer.Received -= Printer_Received;
printer = null;
// Form a receipt from given order to the printer data buffer
public static void Buffer(this Printer printer, Order order)
{
// Receipt header
printer.AddTextAlign(Alignment.Center);
printer.AddTextSize(2, 1);
printer.AddText("MALAY PARLOUR\n");
printer.AddTextSize(Printer.PARAM_DEFAULT, Printer.PARAM_DEFAULT);
printer.AddText("234 PONSONBY RD, AUCKLAND\n");
printer.AddText("GST No: 106-338-302\n\n");
// Order time e.g. 01-01-2017 15:15
printer.AddText(String.Format("{0:dd}-{0:MM}-{0:yyyy} {0:HH}:{0:mm}\n", order.OrderDate));
// Print order details
foreach (OrderDetail od in order.OrderDetails)
{
printer.AddTextAlign(Alignment.Left);
// e.g. 2 * Seafood Laksa $16.50
printer.AddText(String.Format("{0,6} * {1,-22} {2,10:C2}\n",
od.Quantity,
od.Product.ProductName,
od.UnitPrice * od.Quantity));
// If item has remarks, add remarks in a new line
if (!String.IsNullOrEmpty(od.Remarks))
{
printer.AddText("\t" + od.Remarks + "\n");
}
printer.AddText("\n");
}
printer.AddTextAlign(Alignment.Right);
// If order has discount, print subtotal and discount
if (order.Discount != 0)
{
printer.AddText(String.Format("Subtotal: ${0:f2}\n", order.Subtotal));
printer.AddText(String.Format("Discount: {0:P2}\n", order.Discount));
}
// Print total. e.g. EftPos: $38.00
printer.AddTextSize(2, 1);
printer.AddText(String.Format("{0}: ${1:f2}\n\n", order.Payment, order.Total));
// Order footer
printer.AddTextAlign(Alignment.Center);
printer.AddTextSize(Printer.PARAM_DEFAULT, Printer.PARAM_DEFAULT);
printer.AddText("www.malayparlour.co.nz\n\n\n");
// Add a cut
printer.AddCut(Cut.Default);
}
private static void Printer_Received(Printer sender, ReceivedEventArgs args)
{
string callbackCode = Enum.GetName(typeof(CallbackCode), args.Code);
if (callbackCode.Contains("Error"))
{
throw new Exception(callbackCode);
}
}

Please check required device capabilities are enabled on Package.appxmanifest.
Required capabilities depend on how to connect to your printer (almost "Internet (Client & Server)" or "Bluetooth").
https://learn.microsoft.com/ja-jp/windows/uwp/devices-sensors/enable-device-capabilities

Related

Convert VLC video stream to bitmap for xzing to decode using C#

I need to convert a VLC video stream (working) in my WPF app to a bmp for Xzing to be able to decode,
I can decode using a usb or the onboard webcam.
But how to get the 2 together??
Been searching all over and have tried some solutions but nothing seems to work, might be me as i'm pretty new to C#
Thanks
I tried this piece of code:
public static void Get_Frame(Vlc.DotNet.Forms.VlcControl vlc)
{
try
{
if (File.Exists(Temp_Frame_Filename))
{
File.Delete(Temp_Frame_Filename);
}
vlc.TakeSnapshot(Temp_Frame_Filename, width: (uint)vlc.Size.Width, (uint)vlc.Size.Height);
}
catch
{
MessageBox.Show("No Code");
}
}
I cant get it to work because I don't know how to call it,
I want to call it from a dispatch timer but I get errors.
Sorry for not answering questions correctly, will get the hang of this forum.
Try get the whole function in:
/// <summary>
/// Draw the video box into an image
/// </summary>
/// <param name="vlc"></param>
/// <returns></returns>
public static void Get_Frame(Vlc.DotNet.Forms.VlcControl vlc)
{
try
{
if (File.Exists(Temp_Frame_Filename))
{
File.Delete(Temp_Frame_Filename);
}
vlc.TakeSnapshot(Temp_Frame_Filename, width: (uint)vlc.Size.Width, (uint)vlc.Size.Height);
}
catch
{
MessageBox.Show("No Code");
}
}
I tried doing this:
void Codetimer_Tick(object sender, EventArgs e)
{
ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
Result result = Reader.Decode(Temp_Frame_Filename);
if (result != null) TxtScannedResult.Text = result.ToString();
}
Get an error cannot convert from string to system.drawingbitmap.
Thanks
I think I went down the wrong path with that attempt,
I somehow need to convert a VLCVideo stream to bitmap for Xzing
any ideas please
I made a little test with Vlc.DotNet.Wpf 3.0.0 and ZXing.Net 0.16.5.
I'm not sure why you are speaking about a WPF app but then you are using the Vlc.DotNet.Forms namespace. I used the Vlc.DotNet.Wpf.VlcControl.
Here is the proof of concept code (perhaps there is a better solution for threading and locking, but it works):
First, I added the VlcControl to my WPF form:
<Wpf:VlcControl Name="vlcControl" HorizontalAlignment="Left" Height="380" Margin="87,10,0,0" VerticalAlignment="Top" Width="367" Loaded="VlcControl_Loaded"/>
And here is the code behind:
private int isWorking;
private System.Threading.Timer decodingTimer;
private ZXing.IBarcodeReader<BitmapSource> reader = new ZXing.Presentation.BarcodeReader();
private void VlcControl_Loaded(object sender, RoutedEventArgs e)
{
((VlcControl)sender).SourceProvider.CreatePlayer(new DirectoryInfo(#"C:\Program Files\VideoLAN\VLC"));
((VlcControl)sender).SourceProvider.MediaPlayer.SetMedia(new FileInfo(#"How Barcodes Work - YouTube.mp4"));
((VlcControl)sender).SourceProvider.MediaPlayer.Play();
decodingTimer = new System.Threading.Timer(DoDecoding, null, 500, 500);
}
private void DoDecoding(object state)
{
if (Interlocked.Increment(ref isWorking) == 1)
{
this.Dispatcher.BeginInvoke((Action) (() =>
{
try
{
var bitmap = vlcControl.SourceProvider.VideoSource as InteropBitmap;
if (bitmap != null)
{
var result = reader.Decode(bitmap);
if (result != null)
{
MessageBox.Show(result.Text);
}
}
}
catch (Exception )
{
// add handling here
}
finally
{
Interlocked.Decrement(ref isWorking);
}
}));
}
else
{
Interlocked.Decrement(ref isWorking);
}
}
Thank you so much for your help, I tried your solution and it works perfectly.
I have implemented in my solution and am getting the following error:
Object reference not set to an instance of an object.
Any ides why?
Here are some code snippets:
public partial class MainWindow : Window
private ZXing.IBarcodeReader<BitmapSource> reader = new ZXing.Presentation.BarcodeReader();
private System.Threading.Timer decodingTimer;
and
private void DoDecoding(object state)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
try
{
InteropBitmap bitmap = videoSin.SourceProvider.VideoSource as InteropBitmap;
if (bitmap != null)
{
var result = reader.Decode(bitmap);
if (result != null)
{
MessageBox.Show(result.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
));
}
The Video stream works and I only get the error when I present a barcode to the camara.
Thanks

ELM327 returns?

Iam developing a WPF application to interact with ELM327. The communication medium between myApp and ELM327 is USB protocol. ELM327 is connected to vehicle through OBD port. My app able to establish USB communication successfully. Whatever command Iam sending from my App, Iam getting ? as reply. I set baud rate as 9600. For example, I sent ATZ, iam getting ? as reply. I sent 010D, I got ?. I tried with the app comes along with ELM327, that app can successfully able to extract data.
MyApp USB communication connect code:
public SerialPort sport;
private void Button_Click(object sender, RoutedEventArgs e)
{
int baudValue=0;
if (cbBaud.Text == null)
MessageBox.Show("select a baud rate");
else
{
if (cbBaud.Text != null)
{
baudValue = int.Parse(cbBaud.Text);
}
serialConnect(baudValue);
}
}
public void serialConnect(int baudRate)
{
try
{
if (tbCOM.Text != null)
{
sport = new System.IO.Ports.SerialPort(tbCOM.Text,
baudRate);
if (!sport.IsOpen)
{
sport.Open();
sport.DataReceived += new SerialDataReceivedEventHandler(serialDataReceived);
elIndicator.Fill = Brushes.Green;
}
else
{
MessageBox.Show("Connection already Opened");
}
}
}
catch(Exception EX)
{
MessageBox.Show("Connection Error");
}
}
MyApp data sent code:
private void BtSent_Click(object sender, RoutedEventArgs e)
{
try
{
sport.WriteLine(tbSend.Text);
}
catch(Exception EX)
{
MessageBox.Show("Write Error");
}
}
MyApp data receive code:
private void serialDataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
recData.Text = "\n";
recData.Text = System.Environment.NewLine + sport.ReadExisting();
}));
}
Is there any initialization code amI have to sent ?

How can I download (from URL) an apk with a button in xamarin Android?

I used WebClient to download a file in my apk. But I got this error:
Unhandled Exception:
System.Net.WebException: An exception occurred during a WebClient request.
And this is the code that I tried:
{
using (WebClient client = new WebClient())
{
client.DownloadFile(
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
}
Since you are only referring to a WebException, it may have to do with one of these cases:
The URI formed by combining BaseAddress and address is invalid.
The file or destination folder does not exist. Make sure your path to
the destination folder already exists and that you have permissions to access it.
An error occurred while
downloading data.
If you provide us more information about the exception we may be able to reduce the error to one of these cases. To get the InnerException you can do something like this:
{
using (WebClient client = new WebClient ())
{
try
{
client.DownloadFile (
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
catch (Exception ex)
{
while (ex != null)
{
Console.WriteLine (ex.Message);
ex = ex.InnerException;
}
}
}
}
You have to ask permissions on run time even you have mentioned them in your manifest file if you are running Android api level 23 or greater.
Have a look at this blog would help about how to ask a run time permission:requesting-runtime-permissions-in-android
Also, this is the official sample of how to check RuntimePermissions
Refer: xamarin-system-unauthorizedaccessexception-access-to-the-path-is-denied
Update:
To ask run time permissions, you can use this plugin:Plugin.Permissions, install it to your project.
And then, call CheckMyPermissionAsync(); before you download the file:
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
CheckMyPermissionAsync();
}
In the method CheckMyPermissionAsync(), check your Storage permission and then download file:
public async void CheckMyPermissionAsync()
{
var permissionsStartList = new List<Permission>()
{
Permission.Storage
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
//Check the persimmison again
var storeagePermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (storeagePermission == PermissionStatus.Granted)
{
//Download file here
DownloadFile("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg", "XF_Downloads");
}
else {
Console.WriteLine("No permissions");
}
}
You can check the result in the completed event:
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("success");
}
else
{
if (OnFileDownloaded != null) { }
Console.WriteLine("fail");
}
}
Note: pay attention to your filePath,make sure your path is correct, I use:
string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
I updated my sample here: runtime-permission-xamarin.android

Why value does not fall within the expected range when setting Value Changed for Gatt Characteristic

I would like to keep on reading characteristic/set value changed event handlers for characteristics from my BLE 4.0 device, by using the ValueChanged callback in Universal Windows Platform C# in Visual Studio 2017.
I followed some tutorial from these sites: Damian Blog's Windows Universal with BLE, Bluetooth Gatt's Git Hub, Bluetooth Generic Attribute Profile - Heart Rate Service and Dr. Jukka's mobile Blog on BLE. All of them are using ValueChanged and I have tried to follow what they did.
Unfortunately, instead of ValueChanged being triggered, I receive the following error when using the ValueChanged callback.
System.ArgumentException: 'Value does not fall within the expected range.'
This line of code is producing the error:
characteristic.ValueChanged += Oncharacteristic_ValueChanged;
Here is more details of my source code:
NOTE: I am using COM 7 for my dongler and my program could discover the BLE's device name, and could discover the Uuid of the services and characteristics.
public List<string> serviceList = new List<string>();
public List<string> characteristicList = new List<string>();
public BluetoothLEDevice myDevice { get; set; }
public MainPage()
{
this.InitializeComponent();
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
// Find the com port
string selector = SerialDevice.GetDeviceSelector("COM7");
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
if (devices.Count > 0)
{
var dialog = new MessageDialog("Com Device found");
await dialog.ShowAsync();
DeviceInformation deviceInfo = devices[0];
SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
serialDevice.BaudRate = 9600;
serialDevice.DataBits = 8;
serialDevice.StopBits = SerialStopBitCount.One;
serialDevice.Parity = SerialParity.None;
}
else
{
MessageDialog popup = new MessageDialog("Sorry, no device found.");
await popup.ShowAsync();
}
// After com port is found, search for device
foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()))
{
BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id);
// Display BLE device name
var dialogBleDeviceName = new MessageDialog("BLE Device Name " + bleDevice.Name);
await dialogBleDeviceName.ShowAsync();
myDevice = bleDevice;
}
// Check device connection
myDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
foreach (var service in myDevice.GattServices)
{
serviceList.Add(service.Uuid.ToString());
// Verify if service is discovered by displaying a popup
MessageDialog serviceUuidPopUp = new MessageDialog("Adding Service Uuid to list " + service.Uuid.ToString() );
await serviceUuidPopUp.ShowAsync();
foreach (var characteristic in service.GetAllCharacteristics())
{
var characteristicUuid = characteristic.Uuid.ToString().ToLowerInvariant();
characteristicList.Add(characteristicUuid);
// Verify if characteristic is discovered by displaying a popup
MessageDialog charUuidPopUp = new MessageDialog("Adding characteristic Uuid to list " + characteristicUuid);
await charUuidPopUp.ShowAsync();
// set value changed event handlers for characteristics
characteristic.ValueChanged += Oncharacteristic_ValueChanged;
}
}
}
private void OnConnectionStatusChanged(BluetoothLEDevice sender, object args)
{
if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected)
{
System.Diagnostics.Debug.WriteLine("Connected");
}
else
{
System.Diagnostics.Debug.WriteLine("Disconnected");
}
}
private void Oncharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
byte[] data = new byte[args.CharacteristicValue.Length];
DataReader.FromBuffer(
args.CharacteristicValue).ReadBytes(data);
string text = Encoding.UTF8.GetString(data, 0, data.Length);
}
UPDATE 1
I tried to check Characteristic Properties before set value changed event handlers for my characteristics by following the answer given by rudi belt on SO.
if (characteristic.CharacteristicProperties == (GattCharacteristicProperties.Read | GattCharacteristicProperties.Notify))
{
characteristic.ValueChanged += Oncharacteristic_ValueChanged;
}
Unfortunately, this IF statement is not executed.
UPDATE 2
I have tried to remove ALL the codes inside Oncharacteristic_ValueChanged method. But it still gives me the same error
System.ArgumentException: 'Value does not fall within the expected range.'
I have been spending a lot of time trying to solve this problem. I will be very happy if anyone can help me on this. Thank you!
Reading your efforts in the former question I can provide a working example, but first some explanation.
myDevice.ConnectionStatusChanged is not needed, it is only used to notice a connection is lost or connected. You have to connect to your device first and handle things in the connection method.
After you have succeeded in connecting you have to get the service that contains the characteristic you want to use for read, write, notify or indicate.
When you have selected the service You can get the characteristics of that service.
Select the characteristic by Uuid, or in my example with CharacteristicProperties.HasFlag.
This flag in my example is Notify.
In the code comments you find extra info.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
namespace App1
{
public sealed partial class MainPage : Page
{
GattDeviceServicesResult serviceResult = null;
private BluetoothLEDevice myDevice;
private GattCharacteristic selectedCharacteristic;
public MainPage()
{
this.InitializeComponent();
ConnectDevice();
}
private async void ConnectDevice()
{
//This works only if your device is already paired!
foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()))
{
BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id);
// Display BLE device name
var dialogBleDeviceName = new MessageDialog("BLE Device Name " + bleDevice.Name);
await dialogBleDeviceName.ShowAsync();
myDevice = bleDevice;
}
if (myDevice != null)
{
int servicesCount = 3;//Fill in the amount of services from your device!!!!!
int tryCount = 0;
bool connected = false;
while (!connected)//This is to make sure all services are found.
{
tryCount++;
serviceResult = await myDevice.GetGattServicesAsync();
if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount)
{
connected = true;
Debug.WriteLine("Connected in " + tryCount + " tries");
}
if (tryCount > 5)//make this larger if faild
{
Debug.WriteLine("Failed to connect to device ");
return;
}
}
if (connected)
{
for (int i = 0; i < serviceResult.Services.Count; i++)
{
var service = serviceResult.Services[i];
//This must be the service that contains the Gatt-Characteristic you want to read from or write to !!!!!!!.
string myServiceUuid = "0000ffe0-0000-1000-8000-00805f9b34fb";
if (service.Uuid.ToString() == myServiceUuid)
{
Get_Characteriisics(service);
break;
}
}
}
}
}
private async void Get_Characteriisics(GattDeviceService myService)
{
var CharResult = await myService.GetCharacteristicsAsync();
if (CharResult.Status == GattCommunicationStatus.Success)
{
foreach (GattCharacteristic c in CharResult.Characteristics)
{
if (c.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
{
selectedCharacteristic = c;
break;
}
}
try
{
// Write the ClientCharacteristicConfigurationDescriptor in order for server to send notifications.
var result = await selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (result == GattCommunicationStatus.Success)
{
var dialogNotifications = new MessageDialog("Successfully registered for notifications");
await dialogNotifications.ShowAsync();
selectedCharacteristic.ValueChanged += SelectedCharacteristic_ValueChanged;
}
else
{
var dialogNotifications = new MessageDialog($"Error registering for notifications: {result}");
await dialogNotifications.ShowAsync();
}
}
catch (Exception ex)
{
// This usually happens when not all characteristics are found
// or selected characteristic has no Notify.
var dialogNotifications = new MessageDialog(ex.Message);
await dialogNotifications.ShowAsync();
await Task.Delay(100);
Get_Characteriisics(myService); //try again
//!!! Add a max try counter to prevent infinite loop!!!!!!!
}
}
else
{
var dialogNotifications = new MessageDialog("Restricted service. Can't read characteristics");
await dialogNotifications.ShowAsync();
}
}
private void SelectedCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
}
}
}
If you have problems with this code feel free to ask in comments.

SharpPcap Exception during Capture

I've been trying to build a packet sniffer using SharpPcap and PacketDotNet.
This is my code so far:
public static void SniffConnection()
{
var packets = new List<RawCapture>();
var devices = CaptureDeviceList.Instance;
PcapDevice device = null;
foreach (var dev in devices)
{
if (((LibPcapLiveDevice)dev).Interface.FriendlyName.Equals("Wi-Fi 3"))
{
device = (LibPcapLiveDevice)dev;
break;
}
}
try
{
//Open the device for capturing
device.Open(DeviceMode.Promiscuous);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return;
}
//Register our handler function to the 'packet arrival' event
device.OnPacketArrival += (sender, packets_storage) => PacketArrivalHandler(sender, ref packets);
Console.WriteLine("sniffing...");
try
{
device.Capture();
}
catch (System.AccessViolationException e)
{
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine(e);
}
device.Close();
Console.ReadLine();
}
public static void PacketArrivalHandler(object sender, ref List<RawCapture> packets)
{
var dev = (WinPcapDevice)sender;
RawCapture p = dev.GetNextPacket();
if (p != null)
{
var raw_packet = Packet.ParsePacket(p.LinkLayerType, p.Data); // split the packet into layers to check the data in layers is valid
var tcpPacket = (TcpPacket)raw_packet.Extract(typeof(TcpPacket));
var ipPacket = (IpPacket)raw_packet.Extract(typeof(IpPacket));
packets.Add(p);
}
}
After a few packets are captured, the Capture function throws an exception, usually something about memory. (Access Violation, Out of Memory, Overflow)
Any idea what's causing this and how to solve this?
(when Out of Memory or Overflow exceptions are thrown, it says it's something in SharpPcap.LibPcap.PcapDevice.MarshalRawPacket function, but when the Access Violation is thrown, it says it's happenning in a dll thats not even related to my code directly)

Categories