I'm trying to make an program that send a file to a mobile device encrypted, and the device will get it in another program and decrypt it.
So far I've done the bluetooth connection:
private void Connect()
{
using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog())
{
bldialog.ShowAuthenticated = true;
bldialog.ShowRemembered = true;
bldialog.ShowUnknown = true;
if (bldialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
if (bldialog.SelectedDevice == null)
{
System.Windows.Forms.MessageBox.Show("No device selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice;
BluetoothEndPoint remoteEndPoint = new BluetoothEndPoint(selecteddevice.DeviceAddress, BluetoothService.ObexFileTransfer);
client = new BluetoothClient();
client.Connect(remoteEndPoint);
session = new ObexClientSession(client.GetStream(), UInt16.MaxValue);
session.Connect(ObexConstant.Target.FolderBrowsing);
tbConnectionDet.Text = string.Format("Connected to: {0}", selecteddevice.DeviceName);
}
}
}
Also I'm sending the file this way:
private void UploadFiles(string[] files)
{
long size = 0;
List<string> filestoupload = new List<string>();
foreach (string filename in files)
{
if (File.Exists(filename))
{
FileInfo info = new FileInfo(filename);
filestoupload.Add(filename);
size += info.Length;
}
}
using (FileForm upform = new FileForm(new List<string>(filestoupload),
false, session, size, null))
{
upform.ExceptionMethod = ExceptionHandler;
upform.ShowDialog();
lsvExplorer.BeginUpdate();
for (int i = 0; i <= upform.FilesUploaded; i++)
{
ListViewItem temp = new ListViewItem(new string[]{ Path.GetFileName(filestoupload[i]),
FormatSize(new FileInfo(filestoupload[i]).Length, false)},
GetIconIndex(Path.GetExtension(filestoupload[i]), false));
temp.Tag = false;
lsvExplorer.Items.Add(temp);
}
lsvExplorer.EndUpdate();
}
}
I'm using 32feet and BrechamObex libraries .
I have the following questions :
I want to send a public key from my phone to my computer then encrypt a file and send it back to my phone. After I receive the file, I want to decrypt it so I will need another program in order to do this. How can I send information from one program to another using bluetooth?
Whenever I send a file, the phone gets it, but the size it always 0
Related
Hi i'm newbie in RFID reading. So firstly i downloaded pcsc sharp repository from github. Then i tried to read binary from common rfid tag, it works perfect but the next step was to read data from as i think emulated rfid tag. RFID tag controller is pn71501. From this tag using pcsc sharp i can't read any data excluding ATR and uid. I tried to read this tag using my iPhone and it read it. So what i'm doing wrong?
I also tried to use already done software but it couldn't read it also.
Here is what i get using NFC Tools:
PS Smart Card reader i used is ACS ACR1252
Here is my code:
using System;
using System.Text;
using System.Collections.Generic;
using PCSC;
using PCSC.Iso7816;
namespace Transmit {
public class Program {
public static void Main() {
using (var context = ContextFactory.Instance.Establish(SCardScope.System)) {
var readerNames = context.GetReaders();
if (NoReaderFound(readerNames)) {
Console.WriteLine("You need at least one reader in order to run this example.");
Console.ReadKey();
return;
}
var readerName = ChooseRfidReader(readerNames);
if (readerName == null) {
return;
}
String response = "";
using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) {
// for (byte i = 0x00; i < 0x47; i++) {
var apdu = new CommandApdu(IsoCase.Case3Extended, rfidReader.Protocol) {
CLA = 0xFF,
Instruction = (InstructionCode)0xB0,
P1 = 0x00,
P2 = 0x00,
Le = 0x10
};
using (rfidReader.Transaction(SCardReaderDisposition.Leave)) {
//Console.WriteLine("Retrieving the UID .... ");
var sendPci = SCardPCI.GetPci(rfidReader.Protocol);
var receivePci = new SCardPCI(); // IO returned protocol control information.
var receiveBuffer = new byte[256];
var command = apdu.ToArray();
var bytesReceived = rfidReader.Transmit(
sendPci, // Protocol Control Information (T0, T1 or Raw)
command, // command APDU
command.Length,
receivePci, // returning Protocol Control Information
receiveBuffer,
receiveBuffer.Length); // data buffer
var responseApdu =
new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case3Extended, rfidReader.Protocol);
Console.WriteLine(String.Format("SW1: {0:X2} SW2: {1:X2}", responseApdu.SW1, responseApdu.SW2));
//if(responseApdu.DataSize > 0) {
//response += BitConverter.ToString(responseApdu.GetData()).Replace('-', ' ');
response += responseApdu.DataSize;
// }
}
// }
}
/*String[] devidedResponse = response.Split(' ');
String stillResponse = "";
bool notStarted = true;
int skipBytes = 7;
int onByte = 0;
for(int i = 0; i < devidedResponse.Length; i++) {
if (devidedResponse[i] != "D1" && notStarted) {
continue;
} else if (onByte < skipBytes) {
notStarted = false;
onByte += 1;
continue;
} else if (devidedResponse[i] == "FE") {
break;
}
stillResponse += devidedResponse[i] + " ";
}
String res = stillResponse.Trim();
string asciiCharString = "";
var splitResult = res.Split(' ');
foreach (string hexChar in splitResult) {
var byteChar = int.Parse(hexChar, System.Globalization.NumberStyles.HexNumber);
asciiCharString += (char)byteChar;
}*/
Console.WriteLine(response);
}
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
private static string ChooseRfidReader(IList<string> readerNames) {
// Show available readers.
Console.WriteLine("Available readers: ");
for (var i = 0; i < readerNames.Count; i++) {
Console.WriteLine($"[{i}] {readerNames[i]}");
}
// Ask the user which one to choose.
Console.Write("Which reader is an RFID reader? ");
var line = Console.ReadLine();
if (int.TryParse(line, out var choice) && choice >= 0 && (choice <= readerNames.Count)) {
return readerNames[choice];
}
Console.WriteLine("An invalid number has been entered.");
Console.ReadKey();
return null;
}
private static bool NoReaderFound(ICollection<string> readerNames) =>
readerNames == null || readerNames.Count < 1;
}
}
I know. I looked it up earlier. Can you read the card with the file explorer?
A hardware device like a UART can be read at three different levels
Read/Write UART directly by finding hardware I/O address
Read/Write through driver. In c# Use Open Serial Port. The driver gets the hardware I/O
Read/Write through an application. The application does 1 and/or 2 above.
You have a working application (number 3) and I do not know if it is using method 1 or 2.
With the card reader I'm trying to make your programming as simple as possible. The easiest method is 3 if you have an API. Next easiest is method 2 which you should be able to use if you installed the vendor driver. You should see device in device manager.
To unlock the card (encryption) you also need to install the certificate than came with card. The file explorer should be able to read/write card.
I've a Bluetooth thermal printer and i am trying to send a print command using Xamarin.
I've tried the following code
BluetoothSocket socket = null;
BufferedReader inReader = null;
BufferedWriter outReader = null;
BluetoothDevice device = (from bd in BluetoothAdapter.DefaultAdapter?.BondedDevices
where bd?.Name == deviceName
select bd).FirstOrDefault();
//BluetoothDevice hxm = BluetoothAdapter.DefaultAdapter.GetRemoteDevice (bt_printer);
UUID applicationUUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
socket = device.CreateRfcommSocketToServiceRecord(applicationUUID);
socket.Connect();
inReader = new BufferedReader(new InputStreamReader(socket.InputStream));
outReader = new BufferedWriter(new OutputStreamWriter(socket.OutputStream));
outReader.Write("hhhh");
outReader.Flush();
Thread.Sleep(5 * 1000);
var s = inReader.Ready();
inReader.Skip(0);
//close all
inReader.Close();
socket.Close();
outReader.Close();
The screen on the printer shows 'Working' and then back to ready and nothing gets printed out.
As you see i am trying to print the text 'hhhh' do i have to append anything extra for the message.
The printer is an RD-G80 Radall thermal printer.
Hope you can help I've been trying for a week now.
Thanks
I used something like the code below to send the cod to a Zebra
Mobile Printer on a application that i worked some time ago.
Its important to point that u have to know the right code pattern to send to the printer. Usually they have a documentation about it.
In the> application, i send the product code to our backend-end and it
retrieves and build the code pattern that i needed to send from my
mobile application to the printer.
Code below. hope this helps you:
**
private enum msgRet
{
conectionERROR,
sendERROR,
sucess
}
public int Print(string codToSend, string Print)
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
BluetoothSocket btSocket = null;
UUID MY_UUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device = null;
Stream outStream = null;
int ret = -1;
try
{
MessagingCenter.Send(this, "Print");
var MacAdress = mBluetoothAdapter.BondedDevices.ToList().Find(x => x.Name == Print).Address;
if(string.IsNullOrEmpty(MacAdress))
return ret = (int)msgRet.sendERROR;
if (!mBluetoothAdapter.IsEnabled)
{
BluetoothAdapter mBluetoothAdapter =
BluetoothAdapter.DefaultAdapter;
if(!mBluetoothAdapter.IsEnabled)
{
mBluetoothAdapter.Enable();
}
}
device = mBluetoothAdapter.GetRemoteDevice(MacAdress);
btSocket = device.CreateInsecureRfcommSocketToServiceRecord(MY_UUID);
if (!btSocket.IsConnected)
{
btSocket.Connect();
}
if (btSocket.IsConnected)
{
Thread.Sleep(200);
try
{
byte[] msgBuffer = Encoding.ASCII.GetBytes(codToSend);
outStream = btSocket.OutputStream;
outStream.Write(msgBuffer, 0, msgBuffer.Length);
}
catch (Exception e)
{
Debug.WriteLine("sendERROR" + e.Message);
ret = (int)msgRet.sendERROR;
}
}
} catch (Exception ex) {
Debug.WriteLine("conectionERROR:" + ex.Message);
ret = (int)msgRet.conectionERROR;
}
finally
{
if (outStream != null) { outStream.Close(); outStream.Dispose();}
mBluetoothAdapter.Dispose();
if (btSocket!=null) { btSocket.Close(); btSocket.Dispose(); }
}
if (ret == -1) { ret = (int)msgRet.sucess; }
return ret;
}
I have been developing a game in Unity3D in C#. So I have set the game to upload the game save file
to Parse every 2 minutes. When I run the code in Unity it works fine, it saves the game save file locally, and every 2 minutes it uploads it to Parse, it also points to the user who's playing the game. Although when I run the game on a mobile device the file does not upload, I have been refreshing my parse data object in the last half an hour and I still haven't got anything.
Here is the code:
void Start ()
{
if (ParseUser.CurrentUser != null)
{
gapTest = true;
}
}
void Update ()
{
if(gapTest)
{
StartCoroutine(UploadFile());
}
if (uploadSaveFile)
{
OnZipComplete();
uploadSaveFile = false;
}
else if (createNewSaveFile)
{
CreateNewSaveFile();
createNewSaveFile = false;
}
}
IEnumerator UploadFile()
{
gapTest = false;
yield return new WaitForSeconds (120.0F);
if(ParseUser.CurrentUser != null)
{
OnZipComplete();
}
gapTest = true;
}
void OnZipComplete()
{
var query = ParseObject.GetQuery("GameSave").WhereEqualTo("UserObjectId", ParseUser.CurrentUser);
if (existingGameSave == null)
{
query.FindAsync().ContinueWith(t =>
{
IEnumerable<ParseObject> results = t.Result;
int resultCount = 0;
foreach (var result in results)
{
if (resultCount > 0)
{
Debug.LogError("Found more than one save file for user!");
}
else
{
resultCount++;
existingGameSave = result;
uploadSaveFile = true;
}
}
if (resultCount == 0)
{
createNewSaveFile = true;
}
});
}
else
{
UpdateExistingSaveFile();
}
}
private void CreateNewSaveFile()
{
//upload the file to parse
zipPath = Application.persistentDataPath + "/SaveGame.zip";
byte[] data = System.Text.Encoding.UTF8.GetBytes(zipPath);
ParseFile GameSave = new ParseFile("GameSave.zip", data);
var gameSave = new ParseObject("GameSave");
gameSave["UserObjectId"] = ParseUser.CurrentUser;
gameSave["GameSaveFile"] = GameSave;
Task saveTask = gameSave.SaveAsync();
Debug.Log("New Game save file has been uploaded");
}
void UpdateExistingSaveFile()
{
//upload the file to parse
UserIdFile = Application.persistentDataPath + "/UserId.txt";
zipPath = Application.persistentDataPath + "/SaveGame.zip";
byte[] data = System.Text.Encoding.UTF8.GetBytes(zipPath);
ParseFile GameSave = new ParseFile("GameSave.zip", data);
existingGameSave["GameSaveFile"] = GameSave;
Task saveTask = existingGameSave.SaveAsync();
Debug.Log("Existing Game save file has been uploaded");
}
This might be a problem related to permission on android device.
Go to Build Setting > Player Setting > Other Settings, and check "Write Access", by default, it is internal Only which means that the path is for development purpose only.
Try Setting the Write Access as External(SD Card) or add WRITE_ EXTERNAL_STORAGE permission into AndroidManifest.xml. And check Android/file/com.your.appid/files of your sd card if your data is actually getting written on device.
If data is getting written, then it will sure get uploaded on parse.com.
I want ask if the folder exist, if no create it.I try the foloowing but when I became to the bold row below in the code I get error:NO Command received in Invalid state.
using (ImapClient ic = new ImapClient(imapAddr, myEmailID, myPasswd, ImapClient.AuthMethods.Login, portNo, secureConn))
{
bool headersOnly = false;
ic.SelectMailbox("INBOX");
Lazy<MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unseen(), headersOnly);
foreach (Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;
AE.Net.Mail.Imap.Mailbox IsExistFolder = ic.Examine("INBOX/zipi4");
if (IsExistFolder == null)
{
ic.CreateMailbox("INBOX/zipi4");
}
string s = "INBOX/zipi2";
**ic.MoveMessage(m.Uid, s);**
ic.Expunge();
TextWriter writer1 = File.CreateText("Y:\\perl4.txt");
m.Save(writer1);
}
}
I have created a Web Email Application, How do I view and save attached files?
I am using OpenPop, a third Party dll, I can send emails with attachments and read emails with no attachments.
This works fine:
Pop3Client pop3Client = (Pop3Client)Session["Pop3Client"]; // Creating newPopClient
int messageNumber = int.Parse(Request.QueryString["MessageNumber"]);
Message message = pop3Client.GetMessage(messageNumber);
MessagePart messagePart = message.MessagePart.MessageParts[1];
lblFrom.Text = message.Headers.From.Address; // Writeing message.
lblSubject.Text = message.Headers.Subject;
lblBody.Text=messagePart.BodyEncoding.GetString(messagePart.Body);
This second portion of code displays the contents of the attachment, but that's only useful if its a text file. I need to be able to save the attachment. Also the bottom section of code I have here over writes the body of my message, so if I receive an attachment I can't view my message body.
if (messagePart.IsAttachment == true) {
foreach (MessagePart attachment in message.FindAllAttachments()) {
if (attachment.FileName.Equals("blabla.pdf")) { // Save the raw bytes to a file
File.WriteAllBytes(attachment.FileName, attachment.Body); //overwrites MessagePart.Body with attachment
}
}
}
If anyone is still looking for answer this worked fine for me.
var client = new Pop3Client();
try
{
client.Connect("MailServerName", Port_Number, UseSSL); //UseSSL true or false
client.Authenticate("UserID", "password");
var messageCount = client.GetMessageCount();
var Messages = new List<Message>(messageCount);
for (int i = 0;i < messageCount; i++)
{
Message getMessage = client.GetMessage(i + 1);
Messages.Add(getMessage);
}
foreach (Message msg in Messages)
{
foreach (var attachment in msg.FindAllAttachments())
{
string filePath = Path.Combine(#"C:\Attachment", attachment.FileName);
if(attachment.FileName.Equals("blabla.pdf"))
{
FileStream Stream = new FileStream(filePath, FileMode.Create);
BinaryWriter BinaryStream = new BinaryWriter(Stream);
BinaryStream.Write(attachment.Body);
BinaryStream.Close();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("", ex.Message);
}
finally
{
if (client.Connected)
client.Dispose();
}
for future readers there is easier way with newer releases of Pop3
using( OpenPop.Pop3.Pop3Client client = new Pop3Client())
{
client.Connect("in.mail.Your.Mailserver.com", 110, false);
client.Authenticate("usernamePop3", "passwordPop3", AuthenticationMethod.UsernameAndPassword);
if (client.Connected)
{
int messageCount = client.GetMessageCount();
List<Message> allMessages = new List<Message>(messageCount);
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
foreach (Message msg in allMessages)
{
var att = msg.FindAllAttachments();
foreach (var ado in att)
{
ado.Save(new System.IO.FileInfo(System.IO.Path.Combine("c:\\xlsx", ado.FileName)));
}
}
}
}
The OpenPop.Mime.Message class has ToMailMessage() method that converts OpenPop's Message to System.Net.Mail.MailMessage, which has an Attachments property. Try extracting attachments from there.
I wrote this quite a long time ago, but have a look at this block of code that I used for saving XML attachments within email messages sat on a POP server:
OpenPOP.POP3.POPClient client = new POPClient("pop.yourserver.co.uk", 110, "your#email.co.uk", "password_goes_here", AuthenticationMethod.USERPASS);
if (client.Connected) {
int msgCount = client.GetMessageCount();
/* Cycle through messages */
for (int x = 0; x < msgCount; x++)
{
OpenPOP.MIMEParser.Message msg = client.GetMessage(x, false);
if (msg != null) {
for (int y = 0; y < msg.AttachmentCount; y++)
{
Attachment attachment = (Attachment)msg.Attachments[y];
if (string.Compare(attachment.ContentType, "text/xml") == 0)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string xml = attachment.DecodeAsText();
doc.LoadXml(xml);
doc.Save(#"C:\POP3Temp\test.xml");
}
}
}
}
}
List<Message> lstMessages = FetchAllMessages("pop.mail-server.com", 995, true,"Your Email ID", "Your Password");
The above line of code gets the list of all the messages from your email using corresponding pop mail-server.
For example, to get the attachment of latest (or first) email in the list, you can write following piece of code.
List<MessagePart> lstAttachments = lstMessages[0].FindAllAttachments(); //Gets all the attachments associated with latest (or first) email from the list.
for (int attachment = 0; attachment < lstAttachments.Count; attachment++)
{
FileInfo file = new FileInfo("Some File Name");
lstAttachments[attachment].Save(file);
}
private KeyValuePair<byte[], FileInfo> parse(MessagePart part)
{
var _steam = new MemoryStream();
part.Save(_steam);
//...
var _info = new FileInfo(part.FileName);
return new KeyValuePair<byte[], FileInfo>(_steam.ToArray(), _info);
}
//... How to use
var _attachments = message
.FindAllAttachments()
.Select(a => parse(a))
;
Just in case someone wants the code for VB.NET:
For Each emailAttachment In client.GetMessage(count).FindAllAttachments
AttachmentName = emailAttachment.FileName
'----// Write the file to the folder in the following format: <UniqueID> followed by two underscores followed by the <AttachmentName>
Dim strmFile As New FileStream(Path.Combine("C:\Test\Attachments", EmailUniqueID & "__" & AttachmentName), FileMode.Create)
Dim BinaryStream = New BinaryWriter(strmFile)
BinaryStream.Write(emailAttachment.Body)
BinaryStream.Close()
Next