Need to print UWP MapControl with route results - printing

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);
}
}

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());
}

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

navigating a image from page to other in mono android

I have an ImageView and Button in an Activity, lets call it A. When clicking on the Button, I start the image gallery, where I select an image and load that into the ImageView.
On the ImageView I subscribe to the Touch events, where I want to launch another Activity, B.
My question is, how can I in Activity B get the image, which was selected in Activity A? How is data passed fomr Activity to another Activity?
Here is my code in Activity A:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
_imageView.Touch += TouchMeImageViewOnTouch;
Button button = FindViewById<Button>(Resource.Id.button1);
button.Click += ButtonOnClick;
}
private void ButtonOnClick(object sender, EventArgs eventArgs)
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Uri uri = data.Data;
_imageView.SetImageURI(uri);
string path = GetPathToImage(uri);
Toast.MakeText(this, path, ToastLength.Long);
}
}
private string GetPathToImage(Uri uri)
{
string path = null;
string[] projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (var cursor = ManagedQuery(uri, projection, null, null, null))
{
if (cursor != null)
{
int columnIndex = cursor.GetColumnIndexOrThrow(
Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
}
return path;
}
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
}
In your TouchMeImageViewOnTouch method, you will need to start Activity B. This is done by creating an Intent. This Intent can hold extra stuff the Activity you launch (B), will be able to get hold of.
So I see that you already found out how to get the path to the image, which you simply can pass along to Activity B in the Intent which is done like this:
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
var intent = new Intent(this, typeof (MainActivity));
intent.PutExtra("imagePath", path);
StartActivity(intent);
}
Then in Activity B you can get the path with:
Intent.GetStringExtra("imagePath");
Then do whatever you want with it.

Umbraco 6: How to put newly created node on top

In Umbraco 6, when you create a new node, it is put at the bottom.
You have to sort it manually if you want it to be on the top.
How can you make new nodes appear on the top by default?
You could create an event handler that changes the sort order of the nodes when the new node is created. See Application startup events & event registration for more details on implementing an handler of your own.
Rough untested example which I am sure you could make more elegant but should point you in the right direction:
public class YourApplicationEventHandlerClassName : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentService.Created += ContentServiceCreated;
}
private void ContentServiceCreated(IContentService sender, NewEventArgs<IContent> e)
{
var cs = ApplicationContext.Current.Services.ContentService;
var content = e.Entity;
var parentNode = content.Parent();
content.SortOrder = parentNode.Children().OrderBy(n => n.SortOrder).First().SortOrder - 1;
cs.Save(content);
}
}
The ContentService.Created event did not work for me. Took some battles, but in v7 of Umbraco, I've used the ContentService.Saved event instead, with some double checking on dirty properties to ensure you don't end up in a saving infinite loop:
private void ContentSaved(IContentService sender, SaveEventArgs<IContent> e)
{
foreach (var content in e.SavedEntities)
{
var dirty = (IRememberBeingDirty)content;
var isNew = dirty.WasPropertyDirty("Id");
if (!isNew) return;
var parentNode = content.Parent();
if (parentNode == null) return;
var last = parentNode.Children().OrderBy(n => n.SortOrder).FirstOrDefault();
if (last != null)
{
content.SortOrder = last.SortOrder - 1;
if (content.Published)
sender.SaveAndPublishWithStatus(content);
else
sender.Save(content);
}
}
}
public class AppStartupHandler : ApplicationEventHandler
{
protected override void ApplicationInitialized(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
ContentService.Saved += ContentSaved;
}
}

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