InnerException = {"Exception from HRESULT: 0x8004231C"} - c#

I am developing an application in Windows Phone Silverlight 8.1 in which I am trying to set a route between current location and a hardcoded destination using this link the code is:
private async void GetCoordinates()
{
Geolocator myGeolocator = new Geolocator();
myGeolocator.DesiredAccuracyInMeters = 50;
Geoposition myposition = null;
try
{
myposition = await myGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1),TimeSpan.FromSeconds(50));
Geocoordinate myGeocoordinate = myposition.Coordinate;
GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeocoordinate);
mycoordinates.Add(new GeoCoordinate(myGeoCoordinate.Latitude, myGeoCoordinate.Longitude));
locationmap.Center = myGeoCoordinate;
locationmap.ZoomLevel = 13;
Mygeocodequery = new GeocodeQuery();
Mygeocodequery.SearchTerm = "Seattle, WA";
Mygeocodequery.GeoCoordinate = new GeoCoordinate(myGeoCoordinate.Latitude, myGeoCoordinate.Longitude);
Mygeocodequery.QueryCompleted += Mygeocodequery_Querycompleted;
Mygeocodequery.QueryAsync();
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is disabled in phone settings or capabilities are not checked.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Mygeocodequery_Querycompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if(e.Error==null)
{
MyQuery = new RouteQuery();
mycoordinates.Add(e.Result[0].GeoCoordinate);
MyQuery.Waypoints = mycoordinates;
MyQuery.QueryCompleted += MyQuery_QueryCompleted;
MyQuery.QueryAsync();
Mygeocodequery.Dispose();
}
}
private void MyQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
try
{
**Route MyRoute = e.Result;**
MapRoute MyMapRoute = new MapRoute(MyRoute);
locationmap.AddRoute(MyMapRoute);
MyQuery.Dispose();
}
catch (TargetInvocationException ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
It sometimes works fine but sometimes I am getting this inner exception as TargetInvocationException Exception from HRESULT: 0x8004231C
On the line highlighted please let me know what should I do?

The Problem is only because I had skipped the step to write the following code in load event of map control
private void locationmap_Loaded(object sender, RoutedEventArgs e)
{
Microsoft.Phone.Maps.MapsSettings.ApplicationContext.ApplicationId = "yourapplicationID";
Microsoft.Phone.Maps.MapsSettings.ApplicationContext.AuthenticationToken = "yourauthenticationtoken";
}
if this code is added it works fine for all the locations.

Related

How can I print a pdf document from Xamarin.Forms UWP?

I have a Xamarin.Forms application that supports only UWP. I cannot find a way to print a pdf document. Whatever I have seen on the web, for some reason doesn't work for me. E.g. I tried
https://www.syncfusion.com/kb/8767/how-to-print-pdf-documents-in-xamarin-forms-platform
It lets me print, but the preview in the print dialog never shows up, and the progress indicator just keeps rotating forever.
I also tried http://zawayasoft.com/2018/03/13/uwp-print-pdf-files-silently-without-print-dialog/
This gives me errors that I cannot fix.
So I wonder if somebody can suggest something else that would actually work. Maybe something newer than what I have tried (I use VS 2017). Printing without the printing dialog would be preferable.
Thank you in advance.
I used a very dirty hack to do that!
What I had to do was to try to print the image version of the pdf (I did the conversion in backend) and then used the following DependencyInjection:
Inside my Print class in UWP project:
class Print : IPrint
{
void IPrint.Print(byte[] content)
{
Print_UWP printing = new Print_UWP();
printing.PrintUWpAsync(content);
}
}
and the class responsible for printing in uwp:
public class Print_UWP
{
PrintManager printmgr = PrintManager.GetForCurrentView();
PrintDocument PrintDoc = null;
PrintDocument printDoc;
PrintTask Task = null;
Windows.UI.Xaml.Controls.Image ViewToPrint = new Windows.UI.Xaml.Controls.Image();
public Print_UWP()
{
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
public async void PrintUWpAsync(byte[] imageData)
{
int i = 0;
while (i < 5)
{
try
{
BitmapImage biSource = new BitmapImage();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(imageData.AsBuffer());
stream.Seek(0);
await biSource.SetSourceAsync(stream);
}
ViewToPrint.Source = biSource;
if (PrintDoc != null)
{
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
printDoc.AddPages -= PrintDoc_AddPages;
}
this.printDoc = new PrintDocument();
try
{
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
printDoc.AddPages += PrintDoc_AddPages;
bool showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
// printmgr = null;
// printDoc = null;
// Task = null;
PrintDoc = null;
GC.Collect();
printmgr.PrintTaskRequested -= Printmgr_PrintTaskRequested;
break;
}
catch (Exception e)
{
i++;
}
}
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deff = args.Request.GetDeferral();
Task = args.Request.CreatePrintTask("Invoice", OnPrintTaskSourceRequested);
deff.Complete();
}
async void OnPrintTaskSourceRequested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
args.SetSource(printDoc.DocumentSource);
});
def.Complete();
}
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
private void PrintDoc_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = Task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void PrintDoc_GetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, ViewToPrint);
}
}
Please note that this is not a perfect solution and sometimes it crashes without actually being able to trace the exception (which is really strange) so I am sure there must be better answers even though it does the job.

How to solve the issue in using Location services with Async in windows phone?

In my windows phone application I'm getting the using current location using the following code
private void GetCoordinate()
{
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold = 2
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
MessageBox.Show("Current position not available!!");
break;
case GeoPositionStatus.NoData:
MessageBox.Show("Current position not available!!");
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
try
{
var pos = e.Position.Location;
StaticData.currentCoordinate = new GeoCoordinate(pos.Latitude, pos.Longitude);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As shown above I am calling the GetCoordinate method in the page load event of the application page. By using that GPS coordinate values I was enabling or disabling some controls on the page. But here, the issue is page load code executing first and then we are getting the Gps coordinate values..
I need the GPS Coordinate values in pageload. please suggest
You shall start the watcher in the page load, and once the GeoCoordinateWatcher collects the GeoCoordinate value it triggers PositionChanged event where in you shall code for enabling disabling the controls.
So now your code would look like this
private void GetCoordinate()
{
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold = 2
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
try
{
var pos = e.Position.Location;
if(position==required one)
{
//enable disable here
}
StaticData.currentCoordinate = new GeoCoordinate(pos.Latitude, pos.Longitude);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

WP7 Skydrive API - creating folder doesnt work

I try this tutorial to create new folder on skydrive from my WP7 app.
Here is my code:
private void MSAccountLoginToggleSwitch_Checked_1(object sender, RoutedEventArgs e)
{
try
{
LiveAuthClient auth = new LiveAuthClient("** my id **");
auth.LoginAsync(new string[] { "wl.skydrive_update", "wl.calendars_update" });
auth.LoginCompleted += auth_LoginCompleted;
}
catch (LiveAuthException exception)
{
MessageBox.Show("Error signing in: " + exception.Message);
}
}
private void auth_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
mySession = e.Session;
}
else
{
MSAccountLoginToggleSwitch.IsChecked = false;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
try
{
var folderData = new Dictionary<string, object>();
folderData.Add("some test", "A brand new folder was created");
LiveConnectClient liveClient = new LiveConnectClient(mySession);
liveClient.PostAsync("me/skydrive", folderData);
}
catch (LiveConnectException exception)
{
MessageBox.Show("Error creating folder: " + exception.Message);
}
finally
{
MessageBox.Show("uploded");
}
}
it show me messagebox "uploaded", but when I look on my skydrive that file was not created.
It doesnt show any error message, what Im doing worng?
This line liveClient.PostAsync("me/skydrive", folderData); gives you a Task which you do not wait, you just show MessageBox.Show("uploded"); at the end. I don't think that async / await are supported in WP7, so you will need to handle Task with ContinueWith method:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var folderData = new Dictionary<string, object>();
folderData.Add("some test", "A brand new folder was created");
LiveConnectClient liveClient = new LiveConnectClient(mySession);
liveClient.PostAsync("me/skydrive", folderData)
.ContinueWith((t) =>
{
if (t.IsFauled)
{
MessageBox.Show("Error creating folder: " + t.Exception.Message);
}
else
{
MessageBox.Show("uploded");
}
}
, TaskScheduler.FromCurrentSynchronizationContext());
}
UPDATED: Code above will work only on WP8, but on WP7 PostAsync is not a method with Task, so to get PostAsync result you need to subscribe to PostCompleted event.
I found problem I have mistake in line:
folderData.Add("some test", "A brand new folder was created");
correct version is:
folderData.Add("name", "some test");
var folderData = new Dictionary<string,object>();
folderData.Add("myfolder ","simple folder ");
client.PostAsync("me/skydrive","{'name': 'myfolder' }");
client.PostCompleted += new EventHandler<LiveOperationCompletedEventArgs> (client_PostCompleted);
void client_PostCompleted(object sender, LiveOperationCompletedEventArgs e)
{
var a = e.RawResult;
}

I want to merge two .png images

I want to merge two .png images. but when I ga to save them there occurred an error called a generic error occurred in gdi+. I want to continue my project as soon as possible. please help me. Thanks
private void MergeImages(string ImageBack,string ImageFore)
{
try
{
System.Drawing.Graphics myGraphic = null;
Image imgB;// =new Image.FromFile(ImageBack);
imgB = Image.FromFile(ImageBack);
//FileInfo fileInfoBack = new FileInfo(ImageBack);
Image imgF;// =new Image.FromFile(ImageBack);
imgF = Image.FromFile(ImageFore);
//Bitmap tempBitmap = new Bitmap(imgB.Width, imgB.Height,imgB.PixelFormat );
// tempBitmap.Save("a"+fileInfoBack.Extension);
Image m;
m = Image.FromFile(ImageBack);
// m = Image.FromFile("a" + fileInfoBack.Extension);
myGraphic = System.Drawing.Graphics.FromImage(m);
myGraphic.DrawImageUnscaled(imgB,0,0);
myGraphic.DrawImageUnscaled(imgF,posX,posY);
myGraphic.Save();
m.Save(ImageBack.Replace(".jpg",".jpeg"),System.Drawing.Imaging.ImageFormat.Jpeg);
//m.Save(ImageBack, System.Drawing.Imaging.ImageFormat.Png);
// m.Save("d.png", System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnFileProtector_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
txtFileProtector.Text=openFileDialog1.FileName;
}
}
private void btnFilesToProtect_Click(object sender, System.EventArgs e)
{
listFilesToProtect.Items.Clear();
if (openFileDialog2.ShowDialog()==DialogResult.OK)
{
if (openFileDialog2.FileNames.Length>0)
{
for(int i=0;i<openFileDialog2.FileNames.Length;i++)
{
listFilesToProtect.Items.Add(openFileDialog2.FileNames[i]);
}
}
}
}
private void btnLoad2_Click(object sender, System.EventArgs e)
{
posX = int.Parse(textBox1.Text);
posY = int.Parse(textBox2.Text);
// heightBackImage = int.Parse(textBox3.Text);
// widthBackImage = int.Parse(textBox4.Text);
if (listFilesToProtect.Items.Count>0)
{
foreach(object it in listFilesToProtect.Items)
{
MergeImages(it.ToString(), txtFileProtector.Text);
}
}
}
You didn't show us at which line this exception is thrown, So I am going to guess here. This error usually occurs when the path of the image that you are trying to load/save is not correct, so check the path for both ImageBack and ImageFore.
Also make sure that the file you are trying to load/save to is not open by another process including your application.
It is worth to mentioned here that you should dispose the images/graphics when you finish from using them, for instance by use using. like
using(Image imgB = Image.FromFile(ImageBack))
{
//the code that is using the imgB here
}

Backgroundworker thread throws nullreferenceexception

I am loading the images using the BackgroundThread. I am receving "nullreferenceexception unhandled by user code" after loading all the images into the Listview. What could be the issue? Please let me know.
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
int progress = 0;
string pname;
Image myImage;
max_length = files.Length;
for (int k = 0; k < files.Length; k++)
{
ProgressInfo info = new ProgressInfo();
pname = System.IO.Path.GetFullPath(files[k]);
myImage = Image.FromFile(pname);
info.Image = myImage;
info.ImageIndex = k;
backgroundWorker1.ReportProgress(progress, info);
myImage = null;
}
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
//Get image.
ProgressInfo img = e.UserState as ProgressInfo;
//Set image to ListView here.
ImgListView.Images.Add(getThumbnaiImage(ImgListView.ImageSize.Width, img.Image));
fname = System.IO.Path.GetFileName(files[img.ImageIndex]);
ListViewItem lvwItem = new ListViewItem(fname, img.ImageIndex);
lvwItem.Tag = files[img.ImageIndex];
lstThumbNailView.Items.AddRange(new ListViewItem[] { lvwItem });
percent = (int)((float)100 * (float)i / (float)files.Length);
this.progressBar1.Value = (int)percent;
this.label1.Text = "Loading images...";
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
Judging from your comments, you're seeing the error because not all exceptions have an InnerException. If InnerException is null, you will see this problem.
There are several issues at work here though. First, here is the proper try/catch method:
try
{
// Code here
}
catch (Exception ex)
{
// Handle your exception
throw; // Rethrow the same exception, preserving the stack trace (optional)
}
Second, you are likely abusing the purpose of ReportProgress. You should attempt to do all your logic in your backgroundWorker_DoWork, and send the percentage (between 0 and 100) to ReportProgress to update any progress bars.
You may have used the ReportProgress in the way you did to fix a multi-threaded issue. To add items to a ListBox across threads, wrap your code in an anonymous method using the BeginInvoke function
Example:
// Note: I haven't error checked this, and this is only a rough idea of what
// you're trying to do. I'm not even sure of the overall goal here.
this.lstThumbnailView.Invoke((Action)delegate
{
ListViewItem lvwItem = new ListViewItem(name, img.ImageIndex);
ivwItem.Tag = files[img.ImageIndex];
lstThumbNailView.Items.Add(lvwItem);
});
Thanks for the quick response. Here are the changes I made. It seems to be working fine.
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
ProgressInfo img = e.UserState as ProgressInfo;
LoadImages(img);
this.progressBar1.Value = img.Percent;
this.label1.Text = "Loading images...";
}
catch (Exception ex)
{
throw ex;
}
}
private void LoadImages(ProgressInfo img)
{
ImgListView.Images.Add(getThumbnaiImage(ImgListView.ImageSize.Width, img.Image));
this.lstThumbNailView.Invoke((Action)delegate
{
fname = System.IO.Path.GetFileName(files[img.ImageIndex]);
ListViewItem lvwItem = new ListViewItem(fname, img.ImageIndex);
lvwItem.Tag = files[img.ImageIndex];
lstThumbNailView.Items.Add(lvwItem);
});
}

Categories