Problem with SaveFileDialog in Silverlight 3 - silverlight-3.0

i have weird exception by SaveFileDialog in Silverlight 3. I don't really have a idea where the problem is.
I create instance of SaveFileDialog in Loaded event of user control. After Download button is clicked and dialogResult is true asynchronous file download is started. After file download is completed, method OpenFile() is called. This works fine once, but second time I get exception:
Exception message:
"No file was selected"
Details:
{System.InvalidOperationException: No file was selected.
at System.Windows.Controls.SaveFileDialog.OpenFile()
at Spaces.Client.Views.Dialogs.FileDialog.BL_DownloadFileCompleted(Object sender, EventArguments`1 e)
at Spaces.Client.BL.Interface.DownloadFileCompletedEventHandler.Invoke(Object sender, EventArguments`1 e)
at Spaces.Client.BL.WebService.SpacesService._spacesService_DownloadFileCompleted(Object sender, DownloadFileCompletedEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Spaces.Client.BL.SpacesServiceReference.ServiceClient.OnDownloadFileCompleted(Object state)}
Stack:
at System.Windows.Controls.SaveFileDialog.OpenFile()
at Spaces.Client.Views.Dialogs.FileDialog.BL_DownloadFileCompleted(Object sender, EventArguments`1 e)
at Spaces.Client.BL.Interface.DownloadFileCompletedEventHandler.Invoke(Object sender, EventArguments`1 e)
at Spaces.Client.BL.WebService.SpacesService._spacesService_DownloadFileCompleted(Object sender, DownloadFileCompletedEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Spaces.Client.BL.SpacesServiceReference.ServiceClient.OnDownloadFileCompleted(Object state)
Here code snippet:
private void _userControlFileDialog_Loaded(object sender, RoutedEventArgs e)
{
_comboBoxVersions.ItemsSource = _file.Versions;
if (_comboBoxVersions.Items.Count > 0)
_comboBoxVersions.SelectedIndex = 0;
String extension = "*." + _file.Extension;
_sfd = new SaveFileDialog();
_sfd.DefaultExt = _file.Extension;
_sfd.Filter = extension + "|" + extension;
}
private void _hyperlinkButtonDownload_Click(object sender, RoutedEventArgs e)
{
string path = ((FileVersion)_comboBoxVersions.SelectedItem).Url;
bool? dialogResult = _sfd.ShowDialog();
if (dialogResult == true)
{
AppContext.BL.DownloadFileCompleted += new Spaces.Client.BL.Interface.DownloadFileCompletedEventHandler(BL_DownloadFileCompleted);
AppContext.BL.DownloadFileAsync(AppContext.AuthenticatedUser, path);
}
}
void BL_DownloadFileCompleted(object sender, Spaces.Client.BL.Interface.EventArguments<byte[]> e)
{
byte [] data = e._result;
using (Stream fileStream = (Stream)_sfd.OpenFile())
{
fileStream.Write(data, 0, data.Length);
fileStream.Flush();
fileStream.Close();
}
}
Have anybody idea what is wrong?
Regards
Anton Kalcik

There was problem with multiple event handlers. On each click is event handler attached and never detached. Event handler stays attached also after UserControl is closed. So it is on developer to detach event handler on properly way.
Regards
AKa

Related

WebView2 download event is not firing - Windows forms application

I create windows forms application using WebView2 control, in there I add DownloadStarting event for select the downloading path to the user but unfortunately DownloadStarting event not firing.
private async void InitBrowser()
{
var environment = await CoreWebView2Environment.CreateAsync(null, #"C:\Temp", null);
webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
await webView.EnsureCoreWebView2Async(environment);
webView.NavigationCompleted += WebView_NavigationCompleted;
webView.Source = new Uri("myurl");
}
private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
}
private void CoreWebView2_DownloadStarting1(object sender, CoreWebView2DownloadStartingEventArgs e)
{
downloadOperation = e.DownloadOperation;
e.Handled = true;
e.ResultFilePath = Savefile();
}

Xamarin.Android , OnBackPressed() method handling

I have main_activity and dashboard_activity, on dashboard_activity I added fragment using code in OnBackPressed() method
public override void OnBackPressed()
{
//base.OnBackPressed();
FragmentTransaction transaction =FragmentManager.BeginTransaction();
Dialog dialog = new Dialog();
dialog.Show(transaction,"dialog_fragment");
}
My fragment code is here
class Dialog:DialogFragment
{
private Button btnExitapp;
private Button btnLogOut;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
var view = inflater.Inflate(Resource.Layout.dialog, container,false);
btnExitapp=view.FindViewById<Button>(Resource.Id.btnExitapp);
btnExitapp.Click += BtnExitapp_Click;
btnLogOut = view.FindViewById<Button>(Resource.Id.btnLogOut);
btnLogOut.Click += BtnLogOut_Click;
return view;
}
private void BtnLogOut1_Click(object sender, EventArgs e)
{
}
private void BtnExitapp1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
}
Note:My code for btnExitapp work fine only once after deployment and if I reopen the app in emulator and press btnExit it close app and reopen with Dashboard_Activity instead of closing app.
Please guide me to achieve
that when BtnLogout pressed, should go back to Main_Activity as it work on backpress button and when BtnExitapp pressed should close the app
At first, if you want to go back to the previous activity in your dialogframent, you can try to call the base.OnBackPressed(); in the private void BtnLogOut1_Click(object sender, EventArgs e). In addition, maybe you need to call it twice, from dialog to dashborad activity and then the main activity.
Then if you want to exit the app, you can use the following code:
private void BtnExitapp1_Click(object sender, EventArgs e)
{
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}

Need to print UWP MapControl with route results

I have a MapControl working just creating my route. Now, I just need to figure out a way to print it out. Using the UWP printing sample, I get a black box where the control should be. The map and route are being built, just not rendered correctly in the print preview. I thought I saw a MapControl.Print... but I think that was in the Bing.Maps stuff. Any pointers would be appreciated. Thanks.
Using the UWP printing sample, I get a black box where the control should be.
It seems the MapControl can not be printed.
As a workround, we can use RenderTargetBitmap to get the image from the MapControl. That we can print the image.
Using a RenderTargetBitmap, you can accomplish scenarios such as applying image effects to a visual that originally came from a XAML UI composition, generating thumbnail images of child pages for a navigation system, or enabling the user to save parts of the UI as an image source and then share that image with other apps.
Because RenderTargetBitmap is a subclass of ImageSource, it can be used as the image source for Image elements or an ImageBrush brush.
For more info,see RenderTargetBitmap.
For example:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(MyMap);
MyImage.Source = renderTargetBitmap;
The printing code:
public sealed partial class MainPage : Page
{
private PrintManager printmgr = PrintManager.GetForCurrentView();
private PrintDocument printDoc = null;
private PrintTask task = null;
public MainPage()
{
this.InitializeComponent();
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
task = args.Request.CreatePrintTask("Print", OnPrintTaskSourceRequrested);
task.Completed += PrintTask_Completed;
deferral.Complete();
}
private void PrintTask_Completed(PrintTask sender, PrintTaskCompletedEventArgs args)
{
//the PrintTask is completed
}
private async void OnPrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
args.SetSource(printDoc?.DocumentSource);
});
def.Complete();
}
private async void appbar_Printer_Click(object sender, RoutedEventArgs e)
{
if (printDoc != null)
{
printDoc.GetPreviewPage -= OnGetPreviewPage;
printDoc.Paginate -= PrintDic_Paginate;
printDoc.AddPages -= PrintDic_AddPages;
}
this.printDoc = new PrintDocument();
printDoc.GetPreviewPage += OnGetPreviewPage;
printDoc.Paginate += PrintDic_Paginate;
printDoc.AddPages += PrintDic_AddPages;
bool showPrint = await PrintManager.ShowPrintUIAsync();
}
private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(this);
printDoc.AddPagesComplete();
}
private void PrintDic_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, this);
}
}

Umbraco unpublish Event not working for the current node

I am developing Umbraco 7 MVC application and my requirement is to add Item inside Umbraco. Item name should be unique. For that used the below code but I am getting the error "Oops: this document is published but is not in the cache (internal error)"
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
if(newsItemExists)
{
e.Cancel = true;
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
Then I tried adding code to unpublish but its not working i.e the node is getting published. Below is my code
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
int itemId=1234; //CurrentPublishedNodeId
if(newsItemExists)
{
IContent content = ContentService.GetById(itemId);
ContentService.UnPublish(content);
library.UpdateDocumentCache(item.Id);
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
But with the above code, if you give the CurrentPublishedNodeId=2345 //someOthernodeId its unpublished correctly.
Can you please help me on this issue.
You don't have to do this, Umbraco will automatically append (1) to the name if the item already exists (so it IS unique).
If you don't want this behavior you can check in the following way:
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(Umbraco.Core.Publishing.IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
var contentService = UmbracoContext.Current.Application.Services.ContentService;
// It's posible to batch publish items, so go through all items
// even though there might only be one in the list of PublishedEntities
foreach (var item in e.PublishedEntities)
{
var currentPage = contentService.GetById(item.Id);
// Go to the current page's parent and loop through all of it's children
// That way you can determine if any page that is on the same level as the
// page you're trying to publish has the same name
foreach (var contentItem in currentPage.Parent().Children())
{
if (string.Equals(contentItem.Name.Trim(), currentPage.Name.Trim(), StringComparison.InvariantCultureIgnoreCase))
e.Cancel = true;
}
}
}
I think your problem might be that you're not looping through all PublishedEntities but using some other way to determine the current page Id.
Note: Please please please do not use the library.UpdateDocumentCache this, there's absolutely no need, ContentService.UnPublish will take care of the cache state.

Lightswitch printing an html file - System.UnauthorizedAccessException: Invalid cross-thread access

I make a new button in Lightswitch and put this code inside to print only a single file:
partial void StampaDeposito_Execute()
{
PrintDocument printInvoice = new PrintDocument();
printInvoice.PrintPage +=
new EventHandler<PrintPageEventArgs>(printInvoice_PrintPage);
printInvoice.Print("TemplateEmail.htm");
}
void printInvoice_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.HasMorePages = false;
}
but when I click the button following error appears: System.UnauthorizedAccessException: Invalid cross-thread access.
Is there a workaround to solve this?
Try this:
using Microsoft.LightSwitch.Threading
partial void StampaDeposito_Execute()
{
Dispatchers.Main.BeginInvoke(() => {
PrintDocument printInvoice = new PrintDocument();
printInvoice.PrintPage +=
new EventHandler<PrintPageEventArgs>(printInvoice_PrintPage);
printInvoice.Print("TemplateEmail.htm");
});
}
void printInvoice_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.HasMorePages = false;
}
When you get an error about thread access, more often than not you can fix it by invoking the code on the main dispatcher.

Resources