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

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.

Related

How to keep loading sign active until page loads completing.Page comes later after ProgressDialog loading sign stops at xamarin native android

My page load later after ProgressDialog loading sign stops. Inside my page images list view are loading via GetImageBitmapFromUrl. Can u pls suggest how can I keep loading sign on until my page loads properly....
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
var mDialog = new ProgressDialog(this.Context);
mDialog.SetMessage("Please wait...");
mDialog.SetCancelable(false);
mDialog.Show();
_data = (await ServiceContext.Current.Duas.GetAll()).ToList();
DuasAdapter adapter = new DuasAdapter(this.Context, _data);
_lstDuas.Adapter = adapter;
_lstDuas.ItemClick += LstDuas_ItemClick;
mDialog.Cancel();
}
From shared code , the reason why not waitting for data loaded may be the follow line :
_data = (await ServiceContext.Current.Duas.GetAll()).ToList();
You need to check whehter ServiceContext.Current.Duas.GetAll() also contains the await method . If no , there will no wait to invoke the next line code .
I will show the sample code here , TaskMethod can be looked as LoadDataMethod .
if code as follow :
private async void Button_Clicked(object sender, EventArgs e)
{
Console.WriteLine("Start code");
int codeResult = await TaskMethod();
Console.WriteLine("End code :" + codeResult);
}
private async Task<int> TaskMethod()
{
Task.Delay(3000);
return 1;
}
When I clicked the Button , you will see the result is :
01-10 14:14:48.474 I/mono-stdout( 5920): Start code
01-10 14:14:48.510 I/mono-stdout( 5920): End code :1
You will see no wait , then End code . The task has not finished .
If code as follow , you will see as your expected .
private async void Button_Clicked(object sender, EventArgs e)
{
Console.WriteLine("Start code");
int codeResult = await TaskMethod();
Console.WriteLine("End code :" + codeResult);
}
private async Task<int> TaskMethod()
{
await Task.Delay(3000);
return 1;
}
The result is :
01-10 14:19:59.396 I/mono-stdout( 6040): Start code
01-10 14:20:02.455 I/mono-stdout( 6040): End code :1
Now the Code end until Task finished .
hi I have solved by modifying my code below...
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
var mDialog = new ProgressDialog(this.Context);
mDialog.SetMessage("Please wait...");
mDialog.SetCancelable(false);
mDialog.Show();
_vdos = (await ServiceContext.Current.IslamicVdo.GetAll()).ToList();
VdoAdapter adapter = new VdoAdapter(this.Context, _vdos);
_lstVdo.Adapter = adapter;
fragsIDActivity.RunOnUiThread(() => mDialog.Hide());
}

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.

Detecting when a template was loaded in wpf

I am working with an attached behavior for logging user actions on a ScrollBar.
my code:
class ScrollBarLogBehavior : Behavior<ScrollBar>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
}
void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
...
var track = (Track)AssociatedObject.Template.FindName("PART_Track", AssociatedObject);
// ** HERE is the problem: track is null ! **
...
}
How can I detect that the template has loaded and I can find the Track?
(when I call AssociatedObject.Template.LoadContent() the result containt the requested Track, so it i a matter of timing and not a matter of wrong template or naming)
Override the method OnApplyTemplate
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var textBox = Template.FindName("PART_Textbox", this) as TextBox;
}
I did not find any good way to detect when the template was loaded. However, I did find a way to find the Track:
in OnAttached() - register to Scroll event fo the ScrollBar (this can only happen after the entire template is loaded, of course):
protected override void OnAttached()
{
base.OnAttached();
_scrollHandler = new ScrollEventHandler(AssociatedObject_Scroll);
AssociatedObject.AddHandler(ScrollBar.ScrollEvent, _scrollHandler, true);
}
When handling the Scroll event, remove registration and find the Thumb:
void AssociatedObject_Scroll(object sender, ScrollEventArgs e)
{
var track = (Track)AssociatedObject.Template.FindName("PART_Track", Associated
if (track == null)
return;
AssociatedObject.RemoveHandler(ScrollBar.ScrollEvent, _scrollHandler);
// do my work with Track
...
}
If I understand correctly, you wish to create an attached behavior that will reference a template part after the ScrollBar has been loaded.
The following should work:
internal static class ScrollBarLogBehavior
{
public static readonly DependencyProperty LogUserActionProperty = DependencyProperty.RegisterAttached(
"LogUserAction",
typeof(bool),
typeof(ScrollBarLogBehavior),
new UIPropertyMetadata(default(bool), LogUserActionChanged));
public static bool GetLogUserAction(DependencyObject obj)
{
return (bool)obj.GetValue(LogUserActionProperty);
}
public static void SetLogUserAction(DependencyObject obj, bool value)
{
obj.SetValue(LogUserActionProperty, value);
}
public static void LogUserActionChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
if (s is ScrollBar scrollBar)
{
scrollBar.Loaded += OnScrollBarLoaded;
}
}
private static void OnScrollBarLoaded(object sender, RoutedEventArgs e)
{
if (sender is ScrollBar scrollBar)
{
if (scrollBar.Template != null)
{
// I'm not sure, but the `name` in the following method call might be case sensitive.
if (scrollBar.Template.FindName("PART_Track", scrollBar) is Track track)
{
// do work with `track` here
}
}
}
}
}
where you would "attach" the behavior in your XAML with:
<ScrollBar guiControls:ScrollBarLogBehavior.LogUserAction="True">
<!-- more here -->
</ScrollBar>
BE ADVISED: this implementation completely ignores the bool value that is being set for LogUserAction

I want to show splash screen until i am done with downloading xml files from server and after completion show next screen

I am trying to download xml files from server when my application starts. So i want to show splash screen until am done with downloading and then show next screen. below is my code:
Here, i want to show My splash screen when getTopNotDoc() method is under execution. and after completion of that method show next screen.
//get _topics and notification document<br>
_getDoc = new ServerConnectivity(this);
public class ServerConnectivity {
private Document _questionDoc;
private Document _topics;
private Document _notifications;
public ServerConnectivity(ApplicationSession appSession){
//getTopNotDoc();
_this = this;
_appSession = appSession;
new Thread(new Runnable(){
public void run(){
getTopNotDoc();
}
}).start();
}
}
private void getTopNotDoc(){
InputStream inputStream = null ;
try{
// Build a document based on the XML file.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
inputStream = getClass().getResourceAsStream("topics.xml");
_topics = builder.parse( inputStream );
inputStream = getClass().getResourceAsStream("notification.xml");
_notifications = builder.parse( inputStream );
if(_topics == null || _notifications == null){
Dialog.alert("Unable to connect to internet");
}
}
catch ( Exception e ){
System.out.println( e.toString() );
}
finally{
if(inputStream != null){
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usually when I do this, I create a loading screen, then I just extend the Thread class.
So I would create a loading screen like this:
public class LoadingScreen extends MainScreen {
public LoadingScreen() {
super();
this.setTitle("loading...");
// add a spinning animated gif or whatever here
final Screen me = this;
new Thread(new Runnable(){
public void run(){
// do something that takes a long time
try { Thread.sleep(1000);} catch (Exception e) {}
}
}){
public void run() {
super.run();
synchronized (UiApplication.getEventLock()) {
UiApplication.getUiApplication().popScreen(me);
}
}
}.start();
}
}
Then I push this screen, it will perform the long task, and then pop itself when its done.
(you may or may not want to disable the back button and menus on this screen)
I made the Runnable as an anonymous inner class just to compact the code, but you probably have this code already in a class somewhere else, so you would pass it in instead.
To add some flexibility and keep your classes loosely coupled together, you could make some modifications to your ServerConnectivity class so your calls could go something like the following:
// push your splash screen on to the stack
//
final SplashScreen splashScreen = new SplashScreen();
UiApplication.getUiApplication().pushScreen(splashScreen);
_getDoc = new ServerConnectivity(this, new ServerConnectivityListener() {
public void onCompleted(ServerConnectivity sender) {
// display next screen
//
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
splashScreen.close();
UiApplication.getUiApplication().pushScreen(new NextScreen());
}
});
}
public void onError(ServerConnectivity sender) {
splashScreen.close();
// display error message, retry, etc...
}
});
For this to work, you need an interface with the following definition:
public interface ServerConnectivityListener {
void onCompleted(ServerConnectivity sender);
void onError(ServerConnectivity sender);
}
So, your ServerConnectivity class maintains a reference to some object that implements the interface called ServerConnectivityListener This allows you to maintain loose coupling between the subject class and any observers that need to listen for events.
Within ServerConnectivity, you would make calls to the listener's methods something like this:
// begin excerpt from above...
//
if(_topics == null || _notifications == null) {
_listener.onError(this);
} else {
_listener.onCompleted(this);
}
catch ( Exception e ){
System.out.println( e.toString() );
_listener.onError(this);
//
// end excerpt from above...
Here is code for splash screen in java........after and call that view.........
http://www.randelshofer.ch/oop/javasplash/javasplash.html
import java.awt.*;
import java.awt.event.*;
public class SplashTest extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(130,250,280,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 130, 260);
g.fillRect(130,270,(frame*10)%280,20);
}
public SplashTest() {
super("SplashScreen demo");
setSize(500, 300);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = (Graphics2D)splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(200);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
public static void main (String args[]) {
SplashTest test = new SplashTest();
}
}
Since,it is a thread based one,We cannot do it the normal way.So Check the following link
http://supportforums.blackberry.com/t5/Java-Development/What-is-the-Event-Thread/ta-p/446865
and Check whether parsing is done,Until that have the same screen,Check the condition of whehter it is downloaded or not ,and then push the screen

Resources