bluetooth file transfer in c# - c#-4.0

I am writing a bluetooth file transfer from my PC to Samsung galaxy using 32Feet.net
Following is the code,i am getting like:
Internal server error final
On my mobile set i saw file transfer but incomplete and message "remote device disconnected"
I tried to send file directly from my pc and it succeeded but using C# it did not work.
I tried 32Feet.net and some other blogs but could not get through.I read i should do pairing but dont know how to do it.
Please help me out of this.
private void sendFile()
{
SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
// dialog.ShowAuthenticated = true;
dialog.ShowRemembered = true;
dialog.ShowUnknown = true;
OpenFileDialog ofd = new OpenFileDialog();
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
System.Uri uri = new Uri("obex://" + dialog.SelectedDevice.DeviceAddress + "/" + ofd.FileName);
ObexWebRequest request = new ObexWebRequest(uri);
request.ReadFile(ofd.FileName);
ObexWebResponse response = (ObexWebResponse)request.GetResponse();
MessageBox.Show(response.StatusCode.ToString());
response.Close();
Cursor.Current = Cursors.Default;
}
else
{
MessageBox.Show("File Not Selected");
}
}
else
{
MessageBox.Show("Device Not Selected");
}
}

Pairing is something you do with Bluetooth devices before you transfer files between them. The devices have to know who they are talking to and trust each other.
On Windows XP
http://support.microsoft.com/kb/883259
On Windows Vista, 7, or 8 go to the start menu and start typing "Bluetooth". The entries that pop up should lead you the right direction.

Related

How to Connect IoT device to the remote monitoring preconfigured solution (Windows)? How to implement and specify the behaviour of IoT hub device?

https://learn.microsoft.com/en-us/azure/iot-suite/iot-suite-connecting-devices#create-a-c-sample-solution-on-windows
Add the following functions that execute when the device receives the SetTemperature and SetHumidity commands from IoT Hub:
EXECUTE_COMMAND_RESULT SetTemperature(Thermostat* thermostat, int temperature)
{
(void)printf("Received temperature %d\r\n", temperature);
thermostat->Temperature = temperature;
return EXECUTE_COMMAND_SUCCESS;
}
EXECUTE_COMMAND_RESULT SetHumidity(Thermostat* thermostat, int humidity)
{
(void)printf("Received humidity %d\r\n", humidity);
thermostat->Humidity = humidity;
return EXECUTE_COMMAND_SUCCESS;
}
Add the following function that sends a message to IoT Hub:
static void sendMessage(IOTHUB_CLIENT_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size)
{
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
if (messageHandle == NULL)
{
printf("unable to create a new IoTHubMessage\r\n");
}
else
{
if (IoTHubClient_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK)
{
printf("failed to hand over the message to IoTHubClient");
}
else
{
printf("IoTHubClient accepted the message for delivery\r\n");
}
IoTHubMessage_Destroy(messageHandle);
}
free((void*)buffer);
}
More in given link
The article you're referring to here shows you how to build and run this sample code on a Windows desktop machine using Visual Studio. There are two other equivalent articles that show you how to run the same code on a Linux machine or an mbed device.
If you want to follow an in-depth tutorial on how to use another hardware device such as a Raspberry Pi or Intel Edison with Azure IoT Hub, then take a look at the collection of IoT Hub tutorials in the Get started folder here.

Unauthorized access while copying files onto USB via OTG Xamarin Android

I am writing a code to paste files onto the USB Sandisk pen drive connected to my android KitKat device using an OTG cable.
I am using the following code snippet.
Using the following code I get a popup asking permission and on allowing it the mUsbManager.HasPermission(device); returns true, but while i copy the file I get an Unauthorized access exception.
I have set the WRITE_EXTERNAL_STORAGE permission.
//Code Snippet
UsbManager manager = (UsbManager)_mainActivity.GetSystemService(Context.UsbService);
var deviceList = manager.DeviceList;
IEnumerable deviceIterator = deviceList.Values.AsEnumerable();
if (deviceIterator.Count() > 0)
{
var device = deviceIterator.ElementAt(0);
ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
var mPermissionIntent = PendingIntent.GetBroadcast(_mainActivity.ApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
UsbManager mUsbManager = (UsbManager)_mainActivity.GetSystemService(Context.UsbService);
mUsbManager.RequestPermission(device, mPermissionIntent);
bool perm = mUsbManager.HasPermission(device);
if (perm)
{
string FileNameSource = "/storage/emulated/0/FileNotPresent.txt";
string FileNameDestination = "/storage/2A85-5687/FileNotPresent.txt";
File.Copy(FileNameSource, FileNameDestination);
}
}
Second question how can i get the path for the connected USB that as of now i have hard coded into the FileNameDestination variable.
A sample code snippet will really be helpful. Thanks.

Notification Hub with localized messages

i just came up with a new problem but the same context azure. now i am trying to implement Multilinqual(localized) push notifications so i am following this localized push notification so this link inculde lot of work of making categories i just wanted to omit them so i am trying to use direct code for subscribing the toast notification on the basis of tag given in Bachend clien app that generate toast notification...here is Backend client app code..
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://samplenotificationhub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=", "samplenotificationhub");
var notification = new Dictionary<string, string>() {
{"News_English", "World News in English!"},
{"News_French", "World News in French!"},
{"News_Mandarin", "World News in Mandarin!"}};
await hub.SendTemplateNotificationAsync(notification, "World");
first i tried it on my previously working sample app that can receive Push notification on the basis of tags also so i just tried to update its code to get template based toaste notification but unfortunately i am not getting anything..here is the code..
private void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("mychannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("mychannel");
CurrentChannel.Open();
CurrentChannel.BindToShellToast();
CurrentChannel.BindToShellTile();
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
var tags = new HashSet<string>();
tags.Add("World");
var hub = new NotificationHub("samplenotificationhub", "Endpoint=sb://samplenotificationhub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=");
var template = String.Format(#"<toast><visual><binding template=""ToastText01""><text id=""1"">$(News_English)</text></binding></visual></toast>");
await hub.RegisterTemplateAsync(args.ChannelUri.ToString(),template,"hello", tags);
// await hub.RegisterNativeAsync(args.ChannelUri.ToString(),tags);
});
}
so if you know anything about it..please guide me any kind of help or suggetion is appreciated..
Hello Friends I again able to solve my problem so the mistake i am doing here is i am following the link blindly as it is for Windows store apps and i wanted to implemented the same for windows phone 8 so what i am doing wrong is using the same Tamplate that is used in windows store apps for windows phone 8 too. so what i understand is this if wanted to target the multiple platforms from a notification hub then your client app that send the toast notification has the same notification for all but all your platform will handle it differently Like for windows 8 the tamplate i am using will work but windows phone this template will work.
string toast = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>Hello Windows phone</wp:Text1>" +
"</wp:Toast> " +
"</wp:Notification>";
so different platform will have different platform.hope it help somebody else too.

How to get information/data from platformRequest() in J2ME?

I want to implement a behavior similar to Whatsapp, where when the user can upload an image. I tried opening the images in my app, but if the image is too large, I will have an out of memory error.
To solve this, I'm opening forwarding the images to be open in the phone's native image viewer using the platformRequest() method.
However, I want to know how is it Whatsapp modifies the phone's native image viewer to add a "Select" button, with which the user selects the image he wants to upload. How is that information sent back to the J2ME application and how is the image resized?
Edit:
I tried this in two different ways, both of which gave me the OOME.
At first, I tried the more direct method:
FileConnection fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
if (!fc.exists()) {
throw new IOException("File does not exists");
}
InputStream fis = fc.openInputStream();
Image im = Image.createImage(fis);
fis.close();
When that didn't work, I tried a more "manual" approach, but that gave me an error as well.
FileConnection fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
if (!fc.exists()) {
throw new IOException("File does not exists");
}
InputStream fis = fc.openInputStream();
ByteArrayOutputStream file = new ByteArrayOutputStream();
int c;
byte[] data = new byte[1024];
while ((c = fis.read(data)) != -1) {
file.write(data, 0, c);
}
byte[] fileData = null;
fileData = file.toByteArray();
fis.close();
fc.close();
file.close();
Image im = Image.createImage(fileData, 0, fileData.length);
When I call the createImage method, the out of memory error occurs in both cases.
This varies with the devices. An E72 gives me the error with 3MB images, while a newer device will give me the error with images larger than 10MBs.
MIDP 2 (JSR 118) does not have API for that, you need to find another way to handle big images.
As for WhatsApp, it looks like they do not rely on MIDP in supporting this functionality. If you check the Wikipedia page you'll note that they don't claim general Java ME as supported platform, but instead, list narrower platforms like Symbian, S40, Blackberry etc.
This most likely means that they implement "problematic features" like one you're asking about using platform-specific API of particular target devices, having essentially separate projects / releases for every platform listed.
If this feature is really necessary in your application, you likely will have to do something like this.
In this case, consider also encapsulating problematic features in a way to make it easier to switch just part of your source code when building it for different platforms. For example, Class.forName(String) can be used to load platform specific implementation depending on target platform.
//...
Image getImage(String resourceName) {
// ImageUtil is an interface with method getImage
ImageUtil imageUtil = (ImageUtil) Class.forName(
// get platform-specific implementation, eg
// "mypackage.platformspecific.s40.S40ImageUtil"
// "mypackage.platformspecific.bb.BBImageUtil"
// "mypackage.platformspecific.symbian.SymbialImageUtil"
"mypackage.platformspecific.s40.S40ImageUtil");
return imageUtil.getImage(resourceName);
}
//...

Java Me video player realize error with http - MediaException

I'm using the below code (references from, http://www.java-tips.org/java-me-tips/midp/playing-video-on-j2me-devices.html). It fails at 'realize()', with the javax.microedition.media.MediaException, "Unable to create native player". What is the problem here?
I tried this using both Eclipse and Netbeans. Am I missing some "internet" permissions or using any incorrect encoding, the video is an external 'mpg' test-resource and does work fine when downloaded through a desktop browser.
public void run()
{
String url = "http://www.fileformat.info/format/mpeg/sample/05e7e78068f44f0ea748855ef33c9f4a/MELT.MPG";
//Append the GUI to a form
Form form = new Form("Video on java mobile!");
Display display = Display.getDisplay(this);
display.setCurrent(form);
try
{
HttpConnection conn = (HttpConnection)Connector.open(url,
Connector.READ_WRITE);
InputStream is = conn.openInputStream();
Player p = Manager.createPlayer(is,"video/mpeg");
//I tried the below, but that didn't work either
//Player p = Manager.createPlayer(url);
p.realize();
//Get the video controller
VideoControl video = (VideoControl) p.getControl("VideoControl");
if(video != null)
{
//Get a GUI to display the video
Item videoItem = (Item)video.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null);
form.append(videoItem);
}
//Start the video
p.prefetch();
p.start();
}
catch(Exception e)
{
form.append(url + " Error:" + e.getMessage());
}
}
I've just started with Java, Eclipse, Netbeans. Since, there similar samples found everywhere, I believe I'm missing something very basic. Can someone please help?
The problem here was the video file. Although my source video seemed "mpeg", it wasn't acceptable to the emulator. After searching through a bit, I found a converter and I manually converted some sample mp4 to "mpeg". It finally worked with the same emulator, after I tried to download and play these manually converted files.
One piece of advise if you are new J2ME/JavaME apps (like me), keep playing with the input data sources/formats and the emulators. Switching emulators or the input data-formats is an easy way to identify the not-so-evident problems.

Resources