Generating HTML Programmatically in C#, Targeting Printed Reports - c#

I've taken over a C# (2.0) code base that has the ability to print information. The code to do this is insanely tedious. Elements are drawn onto each page, with magic constants representing positioning. I imagine the programmer sitting with a ruler, designing each page by measuring and typing in the positions. And yes, one could certainly come up with some nice abstractions to make this approach rational. But I am looking at a different method.
The idea is that I'll replace the current code that prints with code that generates static HTML pages, saves them to a file, and then launches the web browser on that file. The most obvious benefit is that I don't have to deal with formatting-- I can let the web browser do that for me with tags and CSS.
So what I am looking for is a very lightweight set of classes that I can use to help generate HTML. I don't need anything as heavyweight as HTMLTextWriter. What I'm looking for is something to avoid fragments like this:
String.Format("<tr><td>{0}</td><td>{1}</td></tr>", foo, bar);
And instead take have this kind of feel:
...
table().
tr().
td(foo).
td(bar)
Or something like that. I've seen lightweight classes like that for other languages but can't find the equivalent (or better) for C#. I can certainly write it myself, but I'm a firm believer in not reinventing wheels.
Know anything like this? Know anything better than this?

Just as an idea: why do you want to assemble the HTML in your applications code? Sounds a bit tedious to me. You could aggregate the data needed for the report and pass this on to one of the template engines (that are "normally" used for web apps) existing for C#. Then you save the result of the template engine to a html file.
The main benefits I see with this approach:
separates view from business logic
html templates can be edited by non-C# developers, html/css knowledge is enough
no need to recompile the application if the html changes
I havent used it yet, but I heard that the Spark View Engine is OK: http://sparkviewengine.com/ (not sure if it is for C# 2.0 though)
Some time ago I experimented (in PHP) with Gagawa ( http://code.google.com/p/gagawa/ ), where you can do stuff like:
$div = new Div();
$div->setId("mydiv")->setCSSClass("myclass");
$link = new A();
$link->setHref("http://www.example.com")->setTarget("_blank");
$div->appendChild( $link );
But soon dropped such an approach in favor of an template engine.

Another approach is converting the data to XML and applying an XSL stylesheet. In order to change the HTML formating you just need to replace the stylesheet.

Related

How to exports strings from a WPF application code for internationalization?

I'm trying to modify an existing C# application for internationalization. The process for WPF has some documentation here and seems reasonably transparent as I can continue to develop normally and run msbuild from time to time and check if everything holds. However, while going through the sample project, I realized that it won't cover strings defined in code. In my case, most of them are used for logging and could more or less be easily exported with regexes. This seems a bit hazardous as well as I'm not certain the center will hold if I try to extract C# source with regex. I guess that I could wrap every string in a translation function that will perform the lookup in resources.
I'm not sure how to proceed from there. I'll have a bunch of strings that I could dump in a resx file and another set of strings extracted from the baml files internationalized in another way. Since I'm expecting each method to bring their own complications, I'd rather deal with only half of those complications if possible.
Is there any way to have either method work for both cases? I'd honestly prefer the second one since it makes more sense to me but I guess I could roll with generating a gazillion of Uids and only using 5% - 10% of them.
I develop multi-language check-in kiosks for one of the worlds busiest international airports (either #1 or #3, depending on how you define it), and in my experience the best solution for this in WPF apps is custom markup extensions. First, you can use regular language as your key, which means all of your XAML can be written in whatever language is most convenient for your developers. Secondly, you can add custom namespaces to the XAML namespaces, which helps keep your XAML tidy. Third, it's very easy to write utilities to extract your XAML extensions and collate them into Excel spreadsheets (say) for your translators, then incorporate the translations themselves back into your application. Finally, the translation tables themselves can be easily switched at runtime, allowing you to change your language on-the-fly.
Put all this together and all your XAML looks like this:
<TextBlock Text="{Translate 'Text to be translated appears here'}" />
And of course it's easy to control which text goes through your translation engine and which text doesn't, by simply controlling exactly where you use your Translate markup extension.

XML with .NET - Build in code or read from a file?

I am building a web application that will generate charts and graphs using a 3rd party charting component. This charting component requires it receive an XML file containing the design parameters and data in order to render the chart. The application may render up to 10 to 20 charts per page view. I am looking for suggestions for the most efficient way to handle this.
I need to load XML templates, of which there will be about 15-20, one for each chart type definition. With the templates loaded, I will them add the chart specific data and send it off to the charting component for rendering. Some of the possible ways of handling this off the top of my head include ->
Build each XML template in code, using StringBuilder
Build each XML template in code, using one of the .NET XML classes
Store each XML template in a file, load it from the disk on demand
Store each XML template in a file, load them all at once on application start
Storing the XML templates in files would greatly simplify the development processes for me, but I don't know what kind of performance hit I would take, especially if I was continually reading them off the disk. It seems like option 4 would be the better way to go, but I'm not quite sure the best practice way to implement that solution.
So.. any thoughts out there?
I'm just taking a crack at it but I'd save the templates into a constant like so and then use string.format to substitute any values and convert to XML file and pass it along to the 3rd party component.
const string cChart1 = #"<chart type='pie'>
<total>{0}</total>
<sections count={1}>
<section>{2}</section>
<section>{3}</section>
<section>{4}</section>
</section>
</chart>";
XmlDocument xmlChart1 = new XmlDocument();
xmlChart1.LoadXML(String.format(cChart1, somevalue1, somevalue2, somevalue3, somevalue4, somevalue5));
3rdPartyChartComponent cc = new 3rdPartyChartComponent(xmlChart1);
Thanks for your suggestions everyone.
I created a test application that ran x number of trials for each of the suggested methods to see which performed best. As it turns out, building the XML string directly using StringBuilder was orders of magnitude faster, unsurprisingly.
Involving an XmlDocument in any way greatly reduced performance. It should be noted that my results were based off of running thousands of trials for each method... but in a practical sense, any of these method are fast enough to do the job right, in my opinion.
Of course, building everything using StringBuilder is a bit on the messy side. I like Jarealist's suggestion, it's a lot easier on the eyes, and if I handle the XML as a string throughout rather than loading it into an XmlDocument, its one of the fastest ways to go.
Are the same templates used more than once? You could store the template as a static variable. Then add a property getter that builds the template (I would probably use your #2) if it hasn't yet been created, and then return it.
This would impose a performance hit the first time the template is used and be very fast after that.
I am pretty sure you can tell the compiler to bundle those XML files inside your CLR exe. Reading from these would not imply a noticeable performance hit as they would be already in memory. You will need to research a bit as i cant get the code out of my head right now, too sleepy.
EDIT.
http://msdn.microsoft.com/en-us/library/f45fce5x(v=vs.100).aspx - More info on the subject.
Another benefit from using this approach is that the CLR can guarantee the readability and existance of those files, else your executable will be corrupt and wont run.

Is good or bad to write everything in c# rather than using web controls?

I'm confused with choosing between several ways of getting result in ASP.NET.
For example, Web form control SqlDataSource, you retrieve data from database and show results in other controls such as DataGridView, BulletedList etc. However all those things can be written in C#, creating a string which will hold your HTML codes with the retrived data, then you insert your Html code into div using innerHTML. What's the difference?
Example:
[ <div id='block1' runnat='server'></div]
and in CodeBehind
[ block1.innerHTML = myString;]
After writing C# code SqlConnect, Loops, Datatable, you put value of your HTML string into myString.
Why not to implement everything with C#?
Think about what's easiest. For simple cases, using markup, templates and databinding is usually easiest and most simple, because most of what's written is static markup - so we can stay in markup's "native land". But if the markup could radically change based on programmatic logic, then trying to express that in ASP.NET markup can be tedious at best.
Also think about deployment and reuse - templates might also be easier to maintain for a single application, but harder to package and reuse in different applications.
You want to minimize effort and complexity. Achieving these flow directly into less bugs and more stability, plus shorter delivery time. So think about how effort and complexity are affected by:
How hard will it be for you to write?
How hard will it be for you (or others) to change? - if this is a throwaway application, or unlikely to change much, this is less of a concern.
How hard will it be to deploy?
How hard will it be to reuse? - if there is no reuse, this is not a concern.
Writing it all in pure C# is possible but not very convenient when you are trying to achieve a specific html layout - it is painful to maintain, and very hard to work alongside a developer if you want to take their html and just tweak it to add the data.
Personally I'd look at MVC here; for example, I've been playing with razor recently which allows very elegant integration between C# and html in the same file:
<div id="#obj.Id">
<ul>
#foreach(var item in obj.Items) {
<li>#item.Name</li>
}
</ul>
</div>
There I can:
clearly see at a glance how the code maps to the source I can see at the client
make changes with confidence, both from visual inspection and the IDE telling me if I do something obviously wrong
compare to the designer's draft easily
Mostly for maintenance reasons.
Can you imaging how much difficult it can get to make changes to it or debug it? And since it is not a traditional approach, any programmer after you that has to work on that code will of course not be happy with it.
Always remember,
HTML is for markup (for example, Building)
UI customization/styles go to CSS and Themes are for Server Control customization (for example, Paint)
C# (or code-behind to be specific) is for logic (for example, Amenities or wiring up).

Creating a scripting language to be used to create web pages

I am creating a scripting language to be used to create web pages, but don't know exactly where to begin.
I have a file that looks like this:
mylanguagename(main) {
OnLoad(protected) {
Display(img, text, link);
}
Canvas(public) {
Image img: "Images\my_image.png";
img.Name: "img";
img.Border: "None";
img.BackgroundColor: "Transparent";
img.Position: 10, 10;
Text text: "This is a multiline str#ning. The #n creates a new line.";
text.Name: text;
text.Position: 10, 25;
Link link: "Click here to enlarge img.";
link.Name: "link";
link.Position: 10, 60;
link.Event: link.Clicked;
}
link.Clicked(sender, link, protected) {
Image img: from Canvas.FindElement(img);
img.Size: 300, 300;
}
}
... and I need to be able to make that text above target the Windows Scripting Host. I know this can be done, because there used to be a lot of Docs on it around the net a while back, but I cannot seem to find them now.
Can somebody please help, or get me started in the right direction?
Thanks
You're making a domain-specific language which does not exist. You want to translate to another language. You will need a proper scanner and parser. You've probably been told to look at antlr. yacc/bison, or gold. What went wrong with that?
And as an FYI, it's a fun exercise to make new languages, but before you do for something like this, you might ask a good solid "why? What does my new language provide that I couldn't get any other (reasonable) way?"
The thing to understand about parsing and language creation is that writing a compiler/interpreter is primarily about a set of data transformations done to an input text.
Generally, from an input text you will first translate it into a series of tokens, each token representing a concept in your language or a literal value.
From the token stream, you will generally then create an intermediate structure, typically some kind of tree structure describing the code that was written.
This tree structure can then be validated or modified for various reasons, including optimization.
Once that's done, you'll typically write the tree out to some other form - assembly instructions or even a program in another language - in fact, the earliest versions of C++ wrote out straight C code, which were then compiled by a regular C compiler that had no knowledge of C++ at all. So while skipping the assembly generation step might seem like cheating, it has a long and proud tradition behind it :)
I deliberately haven't gotten into any suggestions for specific libraries, as understanding the overall process is probably much more important than choosing a specific parser technology, for instance. Whether you use lex/yacc or ANTLR or something else is pretty unimportant in the long run. They'll all (basically) work, and have all been used successfully in various projects.
Even doing your own parsing by hand isn't a bad idea, as it will help you to learn the patterns of how parsing is done, and so then using a parser generator will tend to make more sense rather than being a black box of voodoo.
Languages similar to C# are not easy to parse - there are some naturally left-recursive rules. So you have to use a parser generator that can deal with them properly. ANTLR fits well.
If PEG fits better, try this: http://www.meta-alternative.net/mbase.html
So you want to translate C# programs to JavaScript? Script# can do this for you.
Rather than write your own language and then run a translator to convert it into Javascript, why not extend Javascript to do what you want it to do?
Take a look at jQuery - it extends Javascript in many powerful ways with a very natural and fluent syntax. It's almost as good as having your own language. Take a look at the many extensions people have created for it too, especially jQuery UI.
Assuming you are really dedicated to do this, here is the way to go. This is normally what you should do: source -> SCANNER -> tokens -> PARSER -> syntax tree
1) Create a scanner/ parser to parse your language. You need to write a grammar to generate a parser that can scan/parse your syntax, to tokenize/validate them.
I think the easiest way here is to go with Irony, that'll make creating a parser quick and easy. Here is a good starting point
http://www.codeproject.com/KB/recipes/Irony.aspx
2) Build a syntax tree - In this case, I suggest you to build a simple XML representation instead of an actual syntax tree, so that you can later walk the XML representation of your DOM to spit out VB/Java Script. If your requirements are complex (like you want to compile it or so), you can create a DLR Expression Tree or use the Code DOM - but here I guess we are talking about a translator, and not about a compiler.
But hey wait - if it is not for educational purposes, consider representing your 'script' as an xml right from the beginning, so that you can avoid a scanner/parser in between, before spitting out some VB/Java script/Html out of that.
I don't wan to be rude... but why are you doing this?
Creating a parser for a regular language is a non-trivial task. Just don't do it.
Why don't you just use html, javascript and css (and jquery as someone above suggested)
If you don't know where to begin, then you probably don't have any experience of this kind and probably you don't have a good reason, why to do this.
I want to save you the pain. Forget it. It's probably a BAD IDEA!
M.
Check out Constructing Language Processors for Little Languages. It's a very good intro I believe. In fact I just consulted my copy 2 days ago when I was having trouble with my template language parser.
Use XML if at all possible. You don't want to fiddle with a lexer and parser by hand if you want this thing in production. I've made this mistake a few times. You end up supporting code that you really shouldn't be. It seems that your language is mainly a templating language. XML would work great there. Just as ASPX files are XML. Your server side blocks can be written in Javascript, modified if necessary. If this is a learning exercise then do it all by hand, by all means.
I think writing your own language is a great exercise. So is taking a college level compiler writing class. Good luck.
You obviously need machinery designed to translate langauges: parsing, tree building, pattern matching, target-language tree building, target-language prettyprinting.
You can try to do all of this with YACC (or equivalents), but you'll discover that parsing
is only a small part of a full translator. This means there's a lot more work
to do than just parsing, and that takes time and effort.
Our DMS Software Reengineering Toolkit is a commercial solution to building full translators for relatively modest costs.
If you want to do it on your own from the ground up as an exercise, that's fine. Just be prepared for the effort it really takes.
One last remark: designing a complete language is hard if you want to get a nice result.
Personally I think that every self-imposed challenge is good. I do agree with the other opinions that if what you want is a real solution to a real life problem, it's probably better to stick with proved solutions. However, if as you said yourself, you have an academic interest into solving this problem, then I encourage you to keep on. If this is the case, I might point a couple of tips to get you on the track.
Parsing is not really an easy task, that is way we take at least a semester of it. However, it can be learned. I would recommend starting with Terrence Parr's book on language implementation patterns. There are many great books about compiling and parsing, probably the most loved and hated been the Dragon Book.
This is pretty heavy stuff, but if you are really into this, and have the time, you should definitely take a look. This would be the Robisson Crusoe's "i'll make it all by myself approach". I have recently written an LR parser generator and it took me no more than a long weekend, but that after reading a lot and taking a full two-semesters course on compilers.
If you don't have the time or simply don't want to learn to make a parser "like men do", then you can always try a commercial or academic parser generator. ANTLR is just fine, but you have to learn its meta-language. Personally I think that Irony is a great tool, specially because it stays inside C# and you can take a look at the source code and learn for yourself. Since we are here, and I'm not trying to make any advertisement at all, I have posted a tiny tool in CodePlex that could be useful for this task. Take a look for yourself, it's open-source and free.
As a final tip, don't get scared if someone tells you it cannot be done. Parsing is a difficult theoretical problem but it's nothing that can't be learned, and it really is a great tool to have in your portfolio. I think it speaks very good of a developer that he can write an descent-recursive parser by hand, even if he never has to. If you want to pursuit this goal to its end, take a college-level compilers course, you'll thank me in a year.

How powerful is the <script> tag in ASP.NET?

I'm new at web development with .NET, and I'm currently studying a page where I have both separated codebehinds (in my case, a .CS file associated to the ASPX file), and codebehind that is inside the ASPX file inside tags like this:
<script runat="server">
//code
</script>
Q1:What is the main difference (besides logical matters like organization, readability and ETC), what could be done in one way that could not be done in another? What is each mode best suited for ?
Q2:If I'm going to develop a simple page with database connection, library imports, access to controls (ascx) and image access in other folders.. which method should I choose ?
Anything you can do in a code-behind, you can do in an inline script like what you posted. But you should use a code-behind most of the time anyway. Some things (like using directives) are just a little easier there, and it helps keep your code organized.
Q1: Nothing. Aside from what you and the others have mentioned (separation, readability), you can do everything "code behind" can do with "inline" (code within page itself) coding.
Inline coding doesn't necessarily mean its like "spaghetti code" where UI and code are mixed in (like old-school ASP). All your code can live outside of UI/HTML but still be inline. You can copy/paste all the code-behind code into your inline page and make a few adjustments (wiring, namespaces, import declarations, etc.) and that's that.
The other comments hit the nail: portability and quick fixes/modifications.
Depending on your use case, you may not want certain sections of code exposed (proprietary), but available for use. This is common for web dev professionals. Inline code allows your customers to quickly/easily customize functionality any way they want to, and can use some of your (proprietary) libraries (dlls) whenever they want to, without having to be code jocks (if they were, they wouldn't have hired you in the first place).
So in practical terms, it's like sending off an "html" file to clients containing instructions on how to change things around (without breaking things)...instead of sending off source code files along with html (aspx) pages and hoping your clients know what to do with them....
Q2: While either style (inline or code-behind) will work, its really a matter of looking at your application in "tiers". Usually, it will be: UI, business logic and data tiers. Thinking about things this way will save you a lot of time.
Practical examples:
If more than one page of your web app must expose/access data, then having a data tier is the best approach. Actually, even if you currently have a 1 page need, its likely never going to stay that way, so think of it as best practice.
If more than one page of your web app will collect input from users (i.e. contact us, registration/sign up, etc.) then you're likely going to need to validate input. So instead of doing this on a page by page basis, a common input validation library will save you time, and lessen the amount of code you need.
In the above examples, you've "separated" a lot of the processing into their own tiers. Your individual html/aspx pages can then use the "code libraries" (data and input validation) quickly with minimal code at the "page level". Then the decision to use either inline or code-behind styles at the "page level" wouldn't matter much - you've essentially "dumbed it down" to whatever your use case is at the time.
Hope this helps....
Keep it separated. Use the .aspx page for your layout, use the .aspx.cs page for any page specific code and for preference, pull your data access/business logic out into their own layer, makes for much simpler maintenance/re-use later on.
Slight caveat there - ASP.net MVC uses inline scripts in it's views, and I've really come round to that idea - it can keep the simple stuff simple, but the architecture used in MVC ensures that your business code remains separate from your presentation code.
I'm not saying you should ever be hacking live code... but one bit of flexibility from having the "code behind" as in-line script is that you could hack in changes without having to rebuild/publish the site.
Personally, I don't ever do this but I've heard instances where people have done it to get in an emergency fix.
There is no difference between the script tag and code behind. The code behind option actually came out of using the script tag or the <% %> from "Classic ASP". A lot of developers didn't like the fact that they server side code sat along side the UI code, because it made the file look messy, and it was a lot more difficult for the HTML people (web designers or whatever you would like to call them) to develop on the same page as the developers at the same time.
Most people like using the code behind option (It's actually considered the standard way of doing things), because it keeps the UI and the Code separate. It's what I prefer, but you really can use either.
You can use all the same stuff
Always try to keep the code separated unless you have a compelling reason not to
Funnily enough, I used the <script runat="server"> in the code infront only today! I did this because you do not need to Build the whole web application to deploy a fix that needs code behind. Yes- it was a bug fix ;)

Categories