Printing reports from WPF - wpf

I've been searching the web for over 2 days now for a good and easy to use something to print reports from a WPF application.
I've been trying to use the DocumentViewer but it's a pain to add Controls to it and style them. Is it me or can this only be done in code behind and how can a grid over multiple pages dynamically be generated?
Second I found the control FlowDocumentReader. This looks like an interesting thing since you can add Tables which are much easier to style and I was able to do this in xaml. Unfortunately, I have no clue how to print from it. I tried to edit the template of the reader but without success.
Last I found this post (What's the best approach to printing/reporting from WPF?) but it's dated to 2008 so I'm not sure if the information is still accurate.
My conclusion is that it is pretty hard to get a nice looking report printed from WPF without writing lots of code behind or editing templates which (by me) fail to do what I want.
So my question is, is there any good approach to my problem? I'm really bothered that I lost this much time for something that I thought was so trivial to do.
I was wonder, what about this guy's approach: https://stackoverflow.com/questions/17647939/how-do-we-handle-different-printing-needs-by-using-fixeddocument?rq=1?

Crystal Reports is indeed a good choice for complicated reports but if your reports will be simple in design I'll recommend using CodeReason reports, it's an xaml based reports. Too bad it's not updated anymore but it's really easy to use for simple reports.
For more information: http://wpfreports.codeplex.com/

Related

How can I write WPF efficiently?

When I first learned about Microsoft's then-new framework for developing desktop applications, WPF, I thought that one of the biggest benefits of it would be its efficiency. After all, I already know what the GUI controls and elements were that I wanted to use--I just have to slap them all on the page and then wire up all my bindings right, and I'll be done. After that, I learned about the MVVM pattern, which promised clean separation of concern within my WPF app.
I thought this was going to be great! I got into creating several different admin and data entry WPF apps with my team at work, and thus I began to crank out working software with robust but simple GUIs, right?
Not so fast, there, cowboy coder. My experience is that writing WPF is S-L-O-W.
Well, at least the way I do it. You see, after I have a picture of my GUI on a whiteboard, I code up the XAML with the controls that I want. This part, as expected, is fast--laying out the whole of a window is pretty quick. After that, its all the little stuff you want these elements to do takes awhile. I always seem to want to make this text bold in some cases; show a red error box in these other cases.
Then things unravel: this binding isn't working right over here--I have to write a converter and adjust the layout for the right values. Whoops, I forgot that extra NotifyPropertyChanged there. Oh, and I want to use a different template in this state vs. that, so I have to figure out what I can use to swap the templates in certain situation. This data is coming in asynchronously, so I need to make sure the right thing is happening on the right thread and that Property gets NotifyChanged as well. Crap, when I maximize my window, it doesn't stretch like I thought it would--must be because its container height isn't defined, but I don't want to define that, so I have to make it stretch in its parent. Oh, now I really want to make a user control out of this stuff over here, so I better implement some dependency properties...
On and on I go, spending hours and days on stuff that just feels so small and minor. I soon resort to cutting usability features and look-and-feel enhancements because this is taking just too darn long.
Does anyone have any tips or principles I need to try in order to write WPF efficiently?
A couple of things that have saved a lot of time for me:
Use DockPanel as your default panel for layout unless you have a good reason not to.
Keep a folder full of useful classes: a ViewModelBase class that implements INotifyPropertyChanged, a RelayCommand class, etc. There's no need to get fancy and try to make this a separate assembly that you build into your project; just write reasonably good implementations and copy/paste them into your new projects.
Get Resharper and use it. Use templates for creating dependency properties, properties that do change notification, and commands.
Find or build a good library for asynchronous task management.
I find that even for very simple applications I get more done faster with WPF than I did with Windows Forms. For applications that aren't very simple, there's absolutely no comparison.
For the most part, WPF applications are a lot of work to develop because it's harder to make the case for cutting out UI features. You can't just say, "Oh, that's not possible," because it probably is possible (whatever "it" is).
Write your own library, or find an existing one.
WPF is great, but out of the box it is missing some things that would make coding faster. I got tired of writing the same things repeatedly, so I ended up creating my own library full of things like converters, visual tree helpers, attached properties, custom controls, etc., and since then, my development time has sped up considerably.
In addition to my own library, I've also started using Microsoft's Prism and Galasoft's MVVM Light Toolkit. Both contain useful objects that I use all the time and are better than what I could code on my own. (Most used are NotificationObject from Prism, RelayCommand from MVVM Light Toolkit, and EventAggregator or Messenger from either one depending on the project, etc.)
Another thing I've done to speed up coding time is to take advantage of Visual Studio's macros. For example, to create a property with Change notification, I write the private property, hit Ctrl+E, Ctrl+R which generates the public version, then run a macro which automatically sets up the PropertyChanged notification in the setter method.
I almost never change the setter methods from the default macro'd one, and instead use the PropertyChanged event to handle any changes that should occur on the setter. This not only makes it easier to track application flow, but also greatly reduces the time I used to waste browsing through my public properties to alter a setter method.
I believe the right answer isn't for WPF at all, but it can fit what you're looking for.
Most of the times, when you want to leverage a new technology there's a time while you're not efficient, productive and your solutions aren't that impressive, innovative or just doesn't look like others.
What will give you more efficiency is working with WPF itself.
It's more about project management topics than programming. After finishing some project, your team and you should go to some room and discuss:
Success stories.
Problems during development.
Pros and cons.
Fails in the application architecture.
Communication problems within the team and customer.
... and so on.
If everyone shares their knowledge, project manager or team leader does a good job documenting each project story, finally everyone will have a "know-how".
In addition, it's important that you won't need to reinvent the wheel for every new project: if some pattern worked fine, do the same way next time, even if it's not the best way of doing it. And try to enhance it, if possible.
Design patterns, technologies, paradigms, languages, companies, colleagues and nothing are a silver bullet: Microsoft said WPF is a step-forward in Windows client developments, and it is that: a more modern approach to provide shinny user interfaces and a programming paradigm that fits nowadays' desired approaches, easing the relation between coders and designers, as WPF has XAML, which allows not only separation of concerns, but separation of professionals by area (designers, UI programmers, business programmers, ...).
Finally, as I said above, WPF won't be your silver bullet: learn from your own success and read a lot, see sample applications, download open source solutions, listen your colleagues, drink a coffee and, after all, after some headaches, some day in the near future, you'll leverage these technologies (and many others).
EDIT
I'd like to add that a good way of using the know-how is creating a Visual Studio guidance pack, so you can automate a lot of tasks like creating managers, views, models and other things just in the way your team would do by hand.
For example, you can create a guidance pack for a WPF CRM-like application and you can automate module creation. When you want to add a new module, guidance pack starts a process which adds all the necessary classes to start development this new module, and it can create a sample form already associated with a navigation manager, controller or whatever (it's just an example).
Guidance pack and T4 would be both good tools for automating tedious or repetitive tasks in everyday's tasks:
http://msdn.microsoft.com/en-us/library/ff631854.aspx
http://msdn.microsoft.com/en-us/library/bb126445.aspx
I have been using WPF since 2008 and can honestly say to do it right and clean does take more time than the same thing in WinForms would take to develop. I have written a lot more WPF than Winforms. That being said - if I need a simple internal utility - it is ALWAYS Winforms. If I have something forward facing to a client - it is always WPF. Why? Winforms are cheap and dirty and you get a lot for free. What you don't get is the fit and polish that WPF can provide. The flexibility with WPF does come at a cost - but in the longer run it's worth it for public facing software.
Yes WPF is a hurdle but it also has rewards. You are on the right track with a design pattern such as MVVM. Sounds like you have not even gotten to the "rewards" of dependency properties or event bubbling. But the control over the UI is great. Almost everything is a content control. In forms I was always writing custom controls to get the UI I wanted. In WFP I have never had to write a custom control for UI and doubt I ever will. The syntax is new but it is compact - I rewrote a Form app in WPF and the WPF has 1/3 the lines and more features. Read a whole book on WPF just to get grounded - I like PRO WPF in C# 2010. You could also say LINQ is complex but man does it do a lot in just a few key strokes. WPF is not something you just pick up on the fly as you next application.

WPF Blend tools vs hand-coded XAML for interface controls

Hi this might seem like a dumb question, but I was looking for a little feedback. I am designer working with a development team on a WPF application. We installed Expression Blend 4. I new to WPF/Silverlight, but I have jumped right in and I think it's great.
However, I did notice that xaml code that can get generated when using Expression Blend can sometimes be overly obnoxious. For example, I created a Control Template for a button with Blend and the markup was like 100 lines of code. Then I created my own control template that was only 20 lines or so and it did exactly the same thing. I did the same thing for a listview and wow, that amount of code that was generated for a ListView template was RIDICULOUS. So again, I created my own styles and templates and the result was A LOT less xaml code.
The app we are creating is going to be pretty big I guess, so my question is, is it that much of a concern for performance if I were to simply create all design/interface elements using blend GUI, even though the generated code can be a lot more extensive? I can see how using Blend tools for design can make things a lot easier, but just like when designing websites, I have never used design view in Dreamweaver because the code that gets generated is pure crap.
Any insight would be greatly appreciated.
Thanks a lot
Personally i would only use any designer for drafting and real-time display of the visual representation of my hand-written code. The generated code may not be horrible but once you need to go into it to do something manually you will have a hard time finding everything you need if you did not write it yourself. Also Blend slices things up quite a lot (create resource & reference it) while i like to nest things in place if they are only used once (i do not know if the code generator could be adjusted in that regard).
It should not be performace concern that the templates are big, if you just copy the default ones used they are quite huge themselves and it's not really an issue.
I'm guessing the control template you generated for the button didn't actually do the exact same thing as the default one which you copied in Blend. You may think it did, but I'm guessing it was missing something. For example, did your template handle all 9 visual states that are used by a button? If you had only 20 lines of XAML, probably not. And yes, the ListView control template is quite large because it's quite a complicated control under the covers.
In general, I wouldn't worry about generating large control templates. It's going to happen. The runtime handles this quite well, in general. Unlike Dreamweaver, Blend generally gives you pretty good code. Performance only becomes an issue if you misuse resource dictionaries by doing something ill-advised such as setting the build action to embedded resource in visual studio. (I believe this creates a loose XAML file which must be parsed and compiled at runtime instead of compile time.)
The key to maintaining your sanity is organization. Just like with a website, you need to come up with an organization scheme for how you're going to store your control templates.

Generating and printing an invoice

I would like to generate an invoice and print it in the background (without being showed to the user of the application),once the cashier has received the cash from the customer.
I don't know how to do that in WPF,i tried to create a user control and pass the needed objects and bind it to a DataGrid control into this user control and print it.
Someone suggested to use Crystal Report and pass a parameter then generate the invoice and print it,but i don't know how to do that technically.
Thanks in advance
In WPF you have many possibilities:
Printing via XPS, look here for more information. It's really flexible and powerfull but also a little complex. Here you will find a short example.
Create a FlowDocument and print out this. This way is more simple, has a lot of features and also gives you good print quality. However it has a specific goal: Support of flowing documents. Therefore it's not always the best choice because of formatting limitations.
A very simple possibility to use PrintDialog.PrintVisual. With this you can print out quickly the contents of a visual. This is good for a simple solution but very limitted.
Use a reporting tool such as Microsoft Report Viewer. You can use it also from WPF and it is very powerfull and free. Take care, there are many different versions out there. I would use the newest one (V3). This is the version VS2010 has an integrated designer.
All these ways can be used to print out without direct user-interaction.
You have written: I don't know how to do that in WPF,i tried to create a user control and pass the needed objects and bind it to a DataGrid control into this user control and print it.. To see how the result becomes, take the PrintDialog.PrintVisual-method, it seems you also have all you need and then you will see if it fits your needs. Otherwise choose one of the other technologies.
For creating nice formatted print-documents, I would propose to use a reporting technology, because of the flexibility they provide. You can do it also in XPS but in general, this is much more work (the more complex the layout becomes) and is also less supportable. However, it's also an effort to learn and embedd the reporting technology into your app.

How to speed up WPF development

I've been developing with WPF for many months now. It's a great framework and I'm able to do fancy, elegant stuff that would have been a lot more difficult with WinForms.
However, I do have the feeling that for normal "line of business" type of applications without any special UI requirements, it still takes me longer to code the UI in XAML than it did to drag-and-drop it in WinForms.
For example, in WinForms, I would just drop an additional label and an additional textbox on the form and arrange everything (using the helper lines) until it looks nice. In WPF, I'd start by factoring out the properties of the existing label and textbox into a style, so I can reuse them; think about the most suitable layout element, maybe refactor some dockpanels/stackpanels into a grid (or vice versa); try different values for the margins etc. Although I have a lot of experience in WPF, it still takes a long time.
I know that I could just forget about "clean XAML" and use the GUI designer in Visual Studio 2008 (which just absolutely positions everything inside a huge grid), but I fear that I would lose a lot of the advantages that XAML offers by doing that.
Have you experienced something similar? If yes, what did you do to speed up everyday WPF development?
What I do to speed up everyday WPF development:
Ignore look and feel for as long as I can. Ideally, tweaking alignments and margins and defining styles is the very last thing I do.
Use the DockPanel before using a Grid, and a Grid before using a StackPanel.
When using the Grid, star-size everything. I'll come back and fix this later, but during prototyping, having a clear idea of how many rows and columns the Grid actually has is enormously helpful.
Prototype in Kaxaml, finish in Expression Blend, test in Visual Studio. Figuring out a methodology for this has taken a lot of time, and it's still very much a work in progress. But Kaxaml is great for quickly seeing how a XAML prototype will behave, and Blend is great for working out the visuals and encapsulating things into user controls and styles.
When using Blend, don't create layouts in the artboard, create them in the object outline. When I'm first developing a WPF UI, the hierarchy of objects is a hundred times more important than how it looks on the screen. I'm still learning to do this, and it seems possible that once I get good enough at it I won't need to prototype in Kaxaml anymore.
Work on the smallest thing possible. This requires a lot of discipline. I've got a nice big complex XAML file, and I decide that I need to edit the template of a control The first thing to do is to create a tiny XAML file with that control in it, and edit the control template there. The temptation to work like this in situ is strong, as editing the control template is only a right-click away. Don't do it.
Don't even think about whether or not I should develop a view model for my tiny little one-off application. Yes, I should.
Learn Blend. Really, really learn it. Learn what all of the tiny icons that surround the selected object mean, and pay attention to them. (Here's a shortcut: I didn't set margins on that thing, but Blend did. That's the answer to maybe 30% of my "what the hell is Blend doing now?" questions.) Use the Blend UI even if I know it would be faster to edit the XAML by hand. This is again a matter of discipline, resisting the temptation to get it done now so that I can improve my ability to get more of it done later.
That's kinda like saying "Sliced apples are easy to make, but apple pie tastes better. How can I make apple pie as easily as I can slice apples?" Well, you can make it easier by using pre-made pie crusts or buying pre-sliced apples, but it will never be quite as easy, because lets face it, you're making something that's a lot more complex and potentially tastier.
It sounds like making styles holds you up. You could get off to a much quicker start if you just imported the same styles with every project. Usually I fly right along once I have all of my styles made.
Otherwise, the only way to make it as easy as the drag-and-drop WinForms designer is to use the drag-and-drop WPF designer.
I've been using WPF for a couple of years now - for optimal speed, I disable the design-view, use snippets, intellisense intensively (and of course ReSharper).
And then I make things simple - I have descided to use standard layout for almost everything - ie. main-screen bit -> DockPanel, ToolBar docked top -> snippet.
Popup screen -> DockPanel, ToolBar docked top, custom Persistent section docked bottom (Save and Cancel buttons) - properties of the viewmodel -> UserControl with grid, labels and properties.
For styling - first do that when I have at least 3 screens for each type - create resource dictionaries for each type. Define common stylings - Header textblock etc. Import ResourceDictionary in each screen and apply styles.
Apply coloring, margins, padding etc. in App.Xaml with non-keyed styles.
I can't think of a faster way. At least for me, I don't really need to think while doing it this way (so, I can use my brainpower later for the complex stuff) - and it gives a consistent "LOB-look" that is relatively easy to style, theme and change later on. It's basically a matter of typing.
My biggest challenge at the moment is that I'm constantly thinking of ways that the UI could be composed dynamically with data templates, which can often get in the way of simpler solutions when the extra flexibility is not required. Other than that, I've become faster now that I'm getting used to the different containers and their quirks. It's such a dramatically different technology that it's going to take time before I develop the appropriate mental tool set for my day-to-day UI tasks, especially since I still need to use WinForms regularly. I figure it's just a matter of time, however, before I have standard patterns in mind that I can deploy quickly and easily.
The advice about VS2010 is very good; its visual designer is actually useful, compared to VS2008's XAML designer, which was less than useless.
Microsoft's PR machine pushes the "Model-View-ViewModel" pattern extensively for line-of-business apps, to the point where they actually recommend things that can waste your time.
Do not spend hours trying to shoe-horn everything into XAML, unless your company or client has procedures which require it. If you can code it faster in VB or C#, and the code is still maintainable, testable, and readable, do it.
Do not become an MVVM purist; not even Microsoft has figured out the appropriate balance for this pattern, and even with the Silverlight 4 stuff, they haven't come up with a good set of development tools or best practices for the pattern, even though it's now been almost five years since it was first proposed; there are still very valid reasons to abandon ICommand and INotifyPropertyChanged in favor of just calling a method on your ViewModel from the code-behind. Also, no non-Microsoft WPF/Silverlight expert I've listened to in the past few months has failed to say, "I'm not sure about MVVM yet, I'm not a purist."
Find a balance and use XAML for what works for you, and C# or VB for what works for you. MS devs on their blogs are fond of calling XAML "markup", and C# or VB is "code, unfortunately". Well, if you're typing it in or laying it out, it's all code, and the truth is that all that XAML gets interpreted and then turned into C# or VB in files you can't see or readily edit, before it's compiled down. (For example, Application.g.vb is generated from Application.xaml as a partial class.)
There are XAML constructs like animations and storyboards which take many lines to lay out in XAML, but in the procedural languages might only take one or two lines of code and actually be easier to read, especially if the animation responds to an event under only certain conditions. Do what works best.
Also, if you're coding along and keep hitting run-time exceptions which make no sense, take a step back, find an alternate answer that gets you functioning, and implement it. Most XAML errors can't be caught by Intellisense or the compiler. It's possible to bang your head for weeks against a XAML problem, that can be coded in C# or VB with early binding in a comparatively much shorter time.
In short, relax and code to your own best practices, using the VS2010 tools, and you should be able to pick up speed.
If you use VS2010 I think the visual designer for the XAML is better now and I think brings the development time more in line with classic winforms development.
If you still need to target .NET 3.5 you can by setting the solution to compile to 3.5 instead of 4.0. This might be a good option for you if you aren't using VS2010 yet.
I feel your pain... Everytime we add a new field into the database, another TextBox/ComboBox has to be made on the form. I've found that using Expression Blend allows me to be much quicker at laying out the form. The downside is that using Blend tends to create more xaml than writing it by hand, so I usually end up cleaning up the xaml a bit.
In the end, Blend is a much better designer than Visual Studio (2010 included), so it's much quicker to do your design work in Blend, and development work in VS. (just my two cents)

Using the MVVM Light Toolkit to make Blendable applications

A while ago, I posted a question regarding switching between a Blend-authored GUI and a Visual Studio-authored one. I got it to work okay by adding my Blend project to my VS2008 project and then changing the Startup Application and recompiling. This would result in two applications that had completely different GUIs, yet used the exact same ViewModel and Model code. I was pretty happy with that.
Now that I've learned about the Laurent Bugnion's MVVM Light Toolkit, I would really like to leverage his efforts to make this process of supporting multiple GUIs for the same backend code possible. The question is, does the toolkit facilate this, or am I stuck doing it my previous way?
I've watched his video from MIX10 and have read some of the articles about it online. However, I've yet to see something that indicates that there is a clean way to allow a user to either dynamically switch GUIs on the fly by loading a different DLL. There are MVVM templates for VS2008 and Blend 3, but am I supposed to create both types of projects for my application and then reference specific files from my VS2008 solution?
UPDATE
I re-read some information on Laurent's site, and seemed to have forgotten that the whole point of the template was to allow the same solution to be opened in VS2008 and Blend. So anyhow, with this new perspective it looks like the templates are actually intended to use a single GUI, most likely designed entirely in Blend (with the convenience of debugging through VS2008), and then be able to use two different ViewModels -- one for design-time, and one for runtime.
So it seems to me like the answer to my question is that I want to use a combination of my previous solution, along with the MVVM Light Toolkit. The former will allow me to make multiple, distinct GUIs around my core code, while the latter will make designing fancy GUIs in Blend easier with the usage of a design-time ViewModel. Can anyone comment on this?
I checked your previous question and this one, and I had never really heard about switching projects to work in Blend and in Studio, and end up with two different UIs. I think this was not the intent of MSFT when they built Blend. Instead, the possibility to open the exact same project and code files in both IDEs (and all the discussions I had with the various teams at MSFT) hints that the intent was in fact to have one application only which can be edited in both environments.
I think that in the end, the goal is to have a variety of tools that you can use to edit your UI - XAML, Visual Studio designer, Blend. Depending on your role in the project (developer, designer, integrator) and depending on your ability with the tools, you can choose one or the other.
This doesn't mean that we never switch templates! Depending on the kind of application (for example between a SL4 desktop application or a WinPhone7 application), we use the same ViewModel (and below) code, but slap a different UI altogether on the files. I demoed how to do that in this video:
http://channel9.msdn.com/posts/kreekman/TechDays-2010-Understanding-the-Model-View-ViewModel-pattern/
This is the same talk I gave at MIX but extended by 15 minutes where I show how to reuse the ViewModel and model files, but use a completely different UI for WinPhone7.
Another application is switching templates when a window is resized (used very often in WPF, but also applicable to Silverlight) in order to show less details or a different layout for different screen sizes.
I hope that this reply doesn't confuse you :) and in fact, I'd love to hear your comments on that before we continue the discussion.
Cheers,
Laurent
I think MEFedMVVM would be a good candidate for this. It is simple and you can combine it with other frameworks.

Resources