I am trying to drag an image from WPF application to UWP application but getting this error
"invalid formatetc structure (exception from hresult: 0x80040064 (dv_e_formatetc)) in GetStorageItemsAsync method"
public async void OnFileDrop(object sender, DragEventArgs e)
{
List<StorageFile> dropFiles = new List<StorageFile>();
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
var isShow2GBMessage = false;
var isShowEXEerrorMessage = false;
if (items.Count > 0)
{
foreach (var appFile in items.OfType<StorageFile>())
{
BasicProperties filesize = await appFile.GetBasicPropertiesAsync();
var fileSize = filesize.Size;
CheckAndAddFiles(dropFiles, ref isShow2GBMessage, ref isShowEXEerrorMessage, appFile, fileSize);
}
}
UploadFiles(dropFiles);
}
}
When I drag the image it is getting copied into a folder but how do I get the path address using DragEventArgs?
Related
Hello, would any of you send a working code to download a photo from a given http address on android Xamarin c #?
First, I need to create a new folder for my application files.
My goal is to download the file from the internet to my Android folder (saving this file with its original name is best).
The next step is to display the image from that folder in "ImageView". It is also important that there are permissions in android and I do not fully understand it.
Could any of you send it to me or help me understand it and explain the topic?
*Actually i have this code:
string address = "https://i.stack.imgur.com/X3V3w.png";
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
webClient.DownloadFile(address, Path.Combine(pathDire, "MyNewImage1.png"));
//System.Net.WebException: 'An exception occurred during a WebClient request.'
}
Loading image from url and display in imageview.
private void Btn1_Click(object sender, System.EventArgs e)
{
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
SavePicture("ImageName.jpg", imageBytes, "imagesFolder");
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
download image and save it in local storage.
private void SavePicture(string name, byte[] data, string location = "temp")
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
documentsPath = System.IO.Path.Combine(documentsPath, "Orders", location);
Directory.CreateDirectory(documentsPath);
string filePath = System.IO.Path.Combine(documentsPath, name);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
int length = data.Length;
fs.Write(data, 0, length);
}
}
you need to add permission WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in AndroidMainfeast.xml, then you also need to Runtime Permission Checks in Android 6.0.
private void checkpermission()
{
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the writeexternalstorage.
}
else
{
// writeexternalstorage permission is not granted. If necessary display rationale & request.
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the ReadExternalStorage.
}
else
{
// ReadExternalStorage permission is not granted. If necessary display rationale & request.
}
}
I"m using the xamarin.plugin.filepicker nuget in a Xamarin Forms project. The picker does not show the user's camera roll or local image gallery on iOS
It only shows 'Icloud Drive' and 'Recently Deleted' folder locations instead. I need to show the camera roll location if possible
private async void PickImage_Clicked(object sender, EventArgs args)
{
string[] fileTypes = null;
if (Device.RuntimePlatform == Device.Android)
{
fileTypes = new string[] { "image/png", "image/jpeg" };
}
if (Device.RuntimePlatform == Device.iOS)
{
fileTypes = new string[] { "public.image" }; // same as iOS constant UTType.Image
}
if (Device.RuntimePlatform == Device.UWP)
{
fileTypes = new string[] { ".jpg", ".png" };
}
if (Device.RuntimePlatform == Device.WPF)
{
fileTypes = new string[] { "JPEG files (*.jpg)|*.jpg", "PNG files (*.png)|*.png" };
}
await PickAndShowFile(fileTypes);
}
private async Task PickAndShowFile(string[] fileTypes)
{
try
{
var pickedFile = await CrossFilePicker.Current.PickFile(fileTypes);
if (pickedFile != null)
{
FileNameLabel.Text = pickedFile.FileName;
FilePathLabel.Text = pickedFile.FilePath;
if (pickedFile.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase)
|| pickedFile.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
FileImagePreview.Source = ImageSource.FromStream(() => pickedFile.GetStream());
chosenImageBytes = GetImageStreamAsBytes(pickedFile.GetStream());
FileImagePreview.IsVisible = true;
}
else
{
FileImagePreview.IsVisible = false;
}
}
}
catch (Exception ex)
{
FileNameLabel.Text = ex.ToString();
FilePathLabel.Text = string.Empty;
FileImagePreview.IsVisible = false;
}
}
You should use Xamarin Media Plugin for that purpose.
I have an application that creates a .vcf file after you input data. it stores storage provided by the phone, I want to click on a list view item and get the vcf file and share it via Email, SMS, WhatsApp, Skype etc how do I implement this in IOS and Android.
Thank you
I have got the answer of creating .vcf file which is given below. and for share that file follow this link : https://github.com/adamped/ShareDialog
private void Share_Clicked(object sender, EventArgs e)
{
try
{
var _btn = sender as Button;
var record = _btn.BindingContext as Contact;
int tempcontactID = record.ContactID;
if (record.CardFrontImage == null)
{
record.CardImage = record.CardBackImage;
}
else
{
record.CardImage = record.CardFrontImage;
}
string baseimage = Convert.ToBase64String(record.CardImage);
var vcf = new StringBuilder(); //vcf code start
vcf.AppendLine("BEGIN:VCARD");
vcf.AppendLine("VERSION:3.0");
vcf.AppendLine($"N:{record.ContactName};{string.Empty}; ;;");
vcf.AppendLine($"FN:{record.ContactName}");
vcf.AppendLine($"ORG:{record.CompanyName}");
vcf.AppendLine($"TITLE:{record.Designation}");
vcf.AppendLine($"PHOTO;ENCODING=BASE64;TYPE=PNG:{baseimage}");
vcf.AppendLine($"TEL;TYPE=work,voice;VALUE=uri:tel:{record.PhoneNumber}");
vcf.AppendLine("END:VCARD");
string fileName = Path.Combine("/storage/emulated/0/Android/data/com.Gamma.GammaNetworkingApp/files/", record.ContactID + record.ContactName + ".vcf");
using (var writer = new StreamWriter(fileName))
{
writer.Write(vcf.ToString());
}
string text = File.ReadAllText(fileName);
bool doesExist = File.Exists(fileName);
if (doesExist == true)
{
var share = DependencyService.Get<IShare>();
share.Show("Contact share", record.ContactName, fileName);
}
}
catch (Exception ex)
{
string test = ex.ToString();
Navigation.PushAsync(new HomePage());
}
}
I want to get a user's position, and therefore I'm using James Montemagno's Geolocator Plugin for Xamarin. The author uses this code in the code-behind.cs file; I extracted it to a static class:
public static class GeoService
{
public static Position savedPosition;
public static async Task<Position> GetPosition()
{
var lastknown = await ExecuteLastKnownPosition();
if(lastknown == null)
{
var current = await ExecuteGPSPosition();
if(current != null)
{
return current;
}
else
{
return null;
}
}
return lastknown;
}
private static async Task<Position> ExecuteLastKnownPosition()
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
return null;
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
//Progress Ring einfügen
var position = await locator.GetLastKnownLocationAsync();
if (position == null)
{
//Benachrichtigung über null lastknownLocation
//Aufrufen der CurrentPosition Methode
return null;
}
savedPosition = position;
return position;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
await Application.Current.MainPage.DisplayAlert("Uh oh", "Something went wrong, but don't worry we captured for analysis! Thanks.", "OK");
return null;
}
finally
{
//Freigabe der Buttons und Bools
}
}
private static async Task<Position> ExecuteGPSPosition()
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
return null;
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100;
//WarteText/Symbol
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(15));
if (position == null)
{
//Warnung, dass kein GPS vorhanden ist
return null;
}
savedPosition = position;
return position;
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Uh oh", "Something went wrong, but don't worry we captured for analysis! Thanks.", "OK");
return null;
}
finally
{
//Zurücksetzen von Buttons und Lademodus beenden
}
}
public static async Task<Address> ExecuteTrackingAdress(Position currentPosition)
{
try
{
//if (savedPosition == null)
// return null;
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
return null;
string mapkey = "Ajbb9XXXXXXatUzUg1w9BSXXXXXVUAEuF4P-TSXJpnvl5OpXXXXXXXXX";
var locator = CrossGeolocator.Current;
var addresses = await locator.GetAddressesForPositionAsync(currentPosition, mapkey);
var address = addresses.FirstOrDefault();
if (address == null)
{
Debug.WriteLine("Keine Adresse vorhanden");
}
return address;
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Uh oh", "Something went wrong, but don't worry we captured for analysis! Thanks.", "OK");
return null;
}
finally
{
}
}
}
Now I got a ContentPage, and when I go to that page (PushModalAsync) the constructor in the view model calls the GetPosition() method. There's a permission Task and whenever the Task is running, UWP offers me to prompt the location permission.
Unfortunately, from this point on the app is freezing. I can't choose Yes/No, and there's no way of interaction.
I tried to call the methods async, with Task.WhenAll() and so on, but it freezes every time.
This was the last code I wrote in my view model
private async void ExecuteGetPosition()
{
IsBusy = true;
await Task.Yield();
var positiontask = GeoService.GetPosition();
var addresstask = GeoService.ExecuteTrackingAdress(positiontask.Result);
await Task.WhenAll(positiontask, addresstask);
CurrentPosition = positiontask.Result;
CurrentAddress = addresstask.Result;
OnPropertyChanged("CurrentAddressView");
IsBusy = false;
}
I'm assuming that the XAML ContentPage isn't already loaded correctly, and so the prompting-window slips "behind" the MainWindow or something.
Please could you give me an idea for a workaround to handle this?
Edit:
Adding these lines to my App.xaml.cs OnStart()-Method brought the solution. Windows is now calling for permission OnStart, Android asks for permission on gps-request...crazy:
var permission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
Are you running on iOS? If so, look at the simulator's console log to see if there is a privacy error. I am guessing it has to do with the privacy declarations required to be in the info.plist when requesting location permissions.
Check out all of the required privacy declarations listed here.
They include (check out the link for info on when to add each one):
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access location when in the background.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access location when open and in the background.</string>
I am creating an outlook plugin that opens a SharePoint Calendar event for editing. The SharePoint Calendar is added to outlook as an overlay.
When clicking on the series event and editing a series everything works fine. But when I select just this one (occurrence). I am unable to get any of the properties for the AppointmentItem object.
I have tried both the ReadComplete and the Open events and still get an exception:
Exception from HRESULT: 0x80040108" and I am unable to access the
Parent. It appears all of the properties are null except Class = 26
and MessageClass = "IPM.Appointment"
private void Application_ItemLoad(object item)
{
_item = item;
try
{
if (!(item is AppointmentItem) || !_exp.CurrentFolder.Name.Contains("Test - Conference Room ")) return;
_warnUser = true;
_apptItem = (AppointmentItem) item;
_apptItem.ReadComplete += test;
_apptItem.Open += McAI_Open;
}
catch (Exception ex)
{
var expMessage = ex.Message;
MessageBox.Show(expMessage);
}
}
private static void ThisAddIn_Shutdown(object sender, EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
private void McAI_Open(ref bool cancel)
{
_warnUser = false;
var conferenceRoom = _exp.CurrentFolder.Name;
conferenceRoom = conferenceRoom.Replace("Test - ", "");
if (!(_item is AppointmentItem)){return;}
try
{
var g = _apptItem.IsRecurring;
if (_apptItem != null && _exp.CurrentFolder.Name.Contains("Test") && _apptItem.Location != null)
{
var location = _apptItem.Location;
var result = location.Substring(location.LastIndexOf(':') + 1);
cancel = true;
var sharePointItemId = int.Parse(result);
var frm = new FrmCalendarSelection(
"<SharePointURL>" + conferenceRoom,
sharePointItemId);
frm.Show();
frm.Closed += Frm_Closed;
}
else if (_apptItem != null && _exp.CurrentFolder.Name.Contains("Test") && _apptItem.Location == null)
{
cancel = true;
var frm = new FrmCalendarSelection(
"<SharePointURL>" + conferenceRoom);
frm.Show();
frm.Closed += Frm_Closed;
}
}
catch (Exception e)
{
throw e;
}
}