Is it possible to intermix Modular templating and legacy VBScript CT? - tridion

In particular, the case I have in mind is this:
##RenderComponentPresentation(Component, "<vbs-legacy-ct-tcm-uri>")##
The problem I'm having is that in my case VBS code breaks when it tries to access component fields, giving "Error 13 Type mismatch ..".
(So, if I were to give the answer, I'd say: "Partially, of no practical use")
EDIT
The DWT above is from another CT, so effectively it's a rendering of component link, that's why parameterless overload as per Nuno's suggestion won't work unfortunately. BTW, the following lines inside VBS don't break and give correct values:
WriteOut Component.ID
WriteOut Component.Schema.Title
EDIT 2
Dominic was absolutely wright: it's a missing dependencies.
A bit more insight to make this info generally useful:
Suppose, the original CT looked like this ("VBScript [Legacy]" type):
[%
Call RenderComponent(Component)
%]
This CT was meant to be called from a PT, also VBS-based. That PT had a big chunk of "#include" statements in the beginning.
Now the story changes: the same CT is being called from another, DWT-based, CT. Obviously (thanks you all for your invaluable help!), dependencies are now not being included anywhere.
The solution to make original CT working again is to explicitly hand-pick and include all necessary VBS TBBs, so the original CT becomes:
[%
#include "tcm:<uri-of-vbs-tbb>"
Call RenderComponent(Component)
%]

Yes - it's perfectly possible to mix and match legacy and modular templates. Perhaps obviously, you can't mix and match template building blocks between the two techniques.
In VBScript "Error 13 Type mismatch" is sometimes used as a secret code that really means "I don't recognise the name of one of your variables, (including the names of Functions and Subs)" In the VBScript templating engine, variables from the page template could be in scope in your component template; it was very common, for example, to put the #includes in the PT so they could be used by the CT. My guess is that your component template is trying to use such a Function, and not finding it.

I know that you can render a Modular Page Template with VBScript Component Presentations, and also a VbScript page template can render a modular Component Template.
Your error is possibly due to something else? Have you tried just using the regular ##RenderComponentPresentation()## call without specifying which template?

The Page Template can render Compound Templates of different flavors - for example Razor, VBS, or XSLT.
The problem comes from the TBBs included in the Templates. Often the Razor templates will need to call functions that only exist in VBScript. So, the starting point when migrating templates is always to start with the helper functions and utility libraries. Then migrate the most generic PT / CT you have to the new format (Razor, XSLT, DWT, etc). This provides a nice basis to migrate the rest of the Templates as you have time to the new format.

Related

Division of a Price in Django Template Syntax

Basically, what I'm trying to do is get a 1/4 of a price in a Django Template Editor.
quote.total is a generated value by the system, for example: 1235.00, and I need to manipulate that value to show 308.75 (1235.00 divided by 4).
I've tried things like using {% widthratio quote.total 4 1 %} to get the quotient, however widthratio rounds the quotient, and I need an exact one.
I've also tried {% widthratio quote.total 4 100 %}, to get the quotient multiplied by 100 (implying that all I'd need to do is figure out how to place a decimal point two places over), but have found no way of using CSS to place a decimal point in.
It is also worth noting that because of the products I am working with quote.total will never have a value in the tenths or hundreths place. I've tried using that to my advantage by adding modulus operators and complex math rules & logic with no success.
The one problem with the system I am using is I have no access to the backend to create custom functions, and because of the way the system parses the template, I cannot use script tags.
EDIT: I see you cannot use tags since you have no access to the back end. You may need a JS-based solution. I'll leave this answer up in case it helps someone.
This is a pretty common use case. Consider using a custom filter, something like:
template.html
{% load quarter %}
{{quote.total|quarter}}
/your_app/templatetags/quarter.py
from django import template
register = template.Library()
#register.filter()
def quarter(value):
return (float(value) * 0.25)
Documentation on custom filters is here in the Django Docs. Also, as with any template tag, be sure to restart your server after adding it, or it will django will not register the tag and will throw an error. This is true of production and development servers.

How to make code syntax highlighters compatible?

There are several tags used for code syntax highlighters, such as pre and code. How to make them compatible at the same site?
# Use PreCode for Windows Live Writer
<pre class="brush: py; toolbar: false;">
...
</pre>
# Install the plugin SyntaxHighlighter Evolved (for WordPress), the source codes will render as:
<div id="highlighter_539499" class="syntaxhighlighter python">
...
</div>
# in markdown, insert code blocks by:
```python
...
```
# will render as:
<pre><code class="python">
...
</code></pre>
# OR
[code lang=python]
...
[/code]
PS: I install the plugin SyntaxHighlighter Evolved, use PreCode in Windows Live Writer for offline blogging and WP markdown editor for online blogging.
Frustratingly, there is no standard for this. The HTML5 Spec provides a suggestion, but then specifically stats that it is not a formal specification:
There is no formal way to indicate the language of computer code being marked up. Authors who wish to mark code elements with the language used, e.g. so that syntax highlighting scripts can use the right rules, can use the class attribute, e.g. by adding a class prefixed with "language-" to the element.
An example is also provided:
The following example shows how a block of code could be marked up using the pre and code elements.
<pre><code class="language-pascal">var i: Integer;
begin
i := 1;
end.</code></pre>
A class is used in that example to indicate the language used.
As it is only a suggestion, no one is required to follow it. My suggestion would be to file a bug report with any syntax highlighting project which does not support the HTML5 suggested format. If they don't want to break backward compatibility with their existing users (understandable), they can always add on a second format (some projects have already done this). If everyone did this, then eventually everyone would be using the same format and the current disparity would no longer exist. If you need some arguments for why the HTML5 spec is a good format, my rather lengthy analysis (from a few years back) may be helpful.
One final remark about the "language-" prefix. While some highlighters do accept it, I have not seen any that require it. And, in fact, most Markdown implementations (which support the [non-standard] fenced-code-blocks) do not insert the prefix. If you really wanted the prefix, then you can add it yourself to your Markdown:
```language-python
...
```
I have also come across some highlighters which also accept the alternate prefix: "lang-". My point is that the prefix part of the suggestion seems to be the weakest link and I would not expect to see any consistency there. Of course, a formal specification would clear this up, but until then, we can only work with what we have.

Get AST from .Net assembly without source code (IL code)

I'd like to analyze .Net assemblies to be language independent from C#, VB.NET or whatever.
I know Roslyn and NRefactory but they only seem to work on C# source code level?
There is also the "Common Compiler Infrastructure: Code Model and AST API" project on CodePlex which claims to "supports a hierarchical object model that represents code blocks in a language-independent structured form" which sound exactly for what I looking for.
However I'am unable to find any useful documentation or code that is actual doing this.
Any advice how to archive this?
Can Mono.Cecil maybe doing something?
You can do this and there is also one (although tiny) example of this in the source of ILSpy.
var assembly = AssemblyDefinition.ReadAssembly("path/to/assembly.dll");
var astBuilder = new AstBuilder(new DecompilerContext(assembly.MainModule));
decompiler.AddAssembly(assembly);
astBuilder.SyntaxTree...
The CCI Code Model is somewhere between a IL disassembler and full C# decompiler: it gives your code some structure (e.g. if statements and expressions), but it also contains some low level stack operations like push and pop.
CCI contains a sample that shows this: PeToText.
For example, to get Code Model for the first method of the Program type (in the global namespace), you could use code like this:
string fileName = "whatever.exe";
using (var host = new PeReader.DefaultHost())
{
var module = (IModule)host.LoadUnitFrom(fileName);
var type = (ITypeDefinition)module.UnitNamespaceRoot.Members
.Single(m => m.Name.Value == "Program");
var method = (IMethodDefinition)type.Members.First();
var methodBody = new SourceMethodBody(method.Body, host, null, null);
}
To demonstrate, if you decompile the above code and show it using PeToText, you're going to get:
Microsoft.Cci.ITypeDefinition local_3;
Microsoft.Cci.ILToCodeModel.SourceMethodBody local_5;
string local_0 = "C:\\code\\tmp\\nuget tmp 2015\\bin\\Debug\\nuget tmp 2015.exe";
Microsoft.Cci.PeReader.DefaultHost local_1 = new Microsoft.Cci.PeReader.DefaultHost();
try
{
push (Microsoft.Cci.IModule)local_1.LoadUnitFrom(local_0).UnitNamespaceRoot.Members;
push Program.<>c.<>9__0_0;
if (dup == default(System.Func<Microsoft.Cci.INamespaceMember, bool>))
{
pop;
push Program.<>c.<>9.<Main0>b__0_0;
Program.<>c.<>9__0_0 = dup;
}
local_3 = (Microsoft.Cci.ITypeDefinition)System.Linq.Enumerable.Single<Microsoft.Cci.INamespaceMember>(pop, pop);
local_5 = new Microsoft.Cci.ILToCodeModel.SourceMethodBody((Microsoft.Cci.IMethodDefinition)System.Linq.Enumerable.First<Microsoft.Cci.ITypeDefinitionMember>(local_3.Members).Body, local_1, (Microsoft.Cci.ISourceLocationProvider)null, (Microsoft.Cci.ILocalScopeProvider)null, 0);
}
finally
{
if (local_1 != default(Microsoft.Cci.PeReader.DefaultHost))
{
local_1.Dispose();
}
}
Of note are all those push, pop and dup statements and the lambda caching condition.
As far as I know, it's not possible to build AST from binary (without sources) since AST itself generated by parser as part of compilation process from sources.
Mono.Cecil won't help because you can only modify opcodes/metadata with them, not analyze assembly.
But since it's .NET you can dump IL code from dll with help of ildasm. Then you can pass generated sources to any parser with CIL dictionary hooked up and get AST from parser. The problem is that as far as I know there is only one publically available CIL grammar for parser, so you don't really have a choice. And ECMA-355 is big enough so it's bad idea to write your own grammar.
So I can suggest you only one solution:
Pass assembly to ildasm.exe to get CIL.
Then pass CIL to ANTLR v3 parser with this CIL grammar wired up (note it's a little bit outdated - grammar created at 2004 and latest CIL specification is 2006, but CIL doesn't really change to much)
After that you can freely access AST generated by ANTLR
Note that you will need ANTLR v3 not v4, since grammar written for 3rd version, and it's hardly possible to port it to v4 without good knowledge of ANTLR syntax.
Also you can try to look into new Microsoft ryujit compiler sources at github (part of CoreCLR) - I don't sure that it's helps, but in theory it must contains CIL grammar and parser implementations since it works with CIL code. But it's written in CPP, have enormous code base and lacks of documentation since it's in active development stage, so it's may be easier to stuck with ANTLR.
If you treat the .net binary file as a stream of bytes, you ought to be able to "parse" it just fine.
You simply write a grammar whose tokens are essentially bytes. You can certainly build a classical lexer/parser with almost any set of lexer/parser tools by defining the lexer to read single bytes as tokens.
You can then build the AST using standard AST-building machinery for the parsing engine (on your own for YACC, automatically with ANTLR4).
What you will discover, of course, is that "parsing" isn't enough; you'll still need to build symbol tables, and carry out control and data flow analyses if you are going to do serious analysis of the corresponding code. See my essay on LifeAfterParsing.
You will also likely have to take into account "distinguished" functions that provide key runtime facilities to the particular programming languages that actually generated the CIL code. And these will make your analyzers language-dependent. Yes, you still get to share the part of the analysis that works on generic CIL.

Meteor how to save templates in mongo

I want to give my users the possibility to create document templates (contracts, emails, etc.)
The best option I figured out would be to store these document templates in mongo (maybe I'm wrong...)
I've been searching for a couple of hours now but I can't figure out how to render these document template with their data context.
Example:
Template stored in Mongo: "Dear {{firstname}}"
data context: {firstname: "Tom"}
On Tom's website, He should read: "Dear Tom"
How can I do this?
EDIT
After some researches, I discovered a package called spacebars-compiler that brings the option to compile to the client:
meteor add spacebars-compiler
I then tried something like this:
Template.doctypesList.rendered = ->
content = "<div>" + this.data.content + "</div>"
template = Spacebars.compile content
rendered = UI.dynamic(template,{name:"nicolas"})
UI.insert(rendered, $(this).closest(".widget-body"))
but it doesn't work.
the template gets compiled but then, I don't know how to interpret it with its data context and to send it back to the web page.
EDIT 2
I'm getting closer thanks to Tom.
This is what I did:
Template.doctypesList.rendered = ->
content = this.data.content
console.log content
templateName = "template_#{this.data._id}"
Template.__define__(templateName, () -> content)
rendered = UI.renderWithData(eval("Template.#{templateName}"),{name:"nicolas"})
UI.insert(rendered, $("#content_" + this.data._id).get(0))
This works excepted the fact that the name is not injected into the template. UI.renderWithData renders the template but without the data context...
The thing your are missing is the call to (undocumented!) Template.__define__ which requires the template name (pick something unique and clever) as the first argument and the render function which you get from your space bars compiler. When it is done you can use {{> UI.dynamic}} as #Slava suggested.
There is also another way to do it, by using UI.Component API, but I guess it's pretty unstable at the moment, so maybe I will skip this, at least for now.
Use UI.dynamic: https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/
It is fairly new and didn't make its way to docs for some reason.
There are few ways to achieve what you want, but I would do it like this:
You're probably already using underscore.js, if not Meteor has core package for it.
You could use underscore templates (http://underscorejs.org/#template) like this:
var templateString = 'Dear <%= firstname %>'
and later compile it using
_.template(templateString, {firstname: "Tom"})
to get Dear Tom.
Of course you can store templateString in MongoDB in the meantime.
You can set delimiters to whatever you want, <%= %> is just the default.
Compiled template is essentially htmljs notation Meteor uses (or so I suppose) and it uses Template.template_name.lookup to render correct data. Check in console if Template.template_name.lookup("data_helper")() returns the correct data.
I recently had to solve this exact (or similar) problem of compiling templates client side. You need to make sure the order of things is like this:
Compiled template is present on client
Template data is present (verify with Template.template_name.lookup("data_name")() )
Render the template on page now
To compile the template, as #apendua have suggested, use (this is how I use it and it works for me)
Template.__define__(name, eval(Spacebars.compile(
newHtml, {
isTemplate: true,
sourceName: 'Template "' + name + '"'
}
)));
After this you need to make sure the data you want to render in template is available before you actually render the template on page. This is what I use for rendering template on page:
UI.DomRange.insert(UI.render(Template.template_name).dom, document.body);
Although my use case for rendering templates client side is somewhat different (my task was to live update the changed template overriding meteor's hot code push), but this worked best among different methods of rendering the template.
You can check my very early stage package which does this here: https://github.com/channikhabra/meteor-live-update/blob/master/js/live-update.js
I am fairly new to real-world programming so my code might be ugly, but may be it'll give you some pointers to solve your problem. (If you find me doing something stupid in there, or see something which is better done some other way, please feel free to drop a comment. That's the only way I get feedback for improvement as I am new and essentially code alone sitting in my dark corner).

Are there solutions for streamlining the update of legacy code in multiple places?

I'm working in some old code which was originally designed for handling two different kinds of files. I was recently tasked with adding a new kind of file to this code. Most of my problems were solved by filling out an extensive XML file with a new entry that handled everything from what lists were named to how the file is written in plural lower case. But this ended up being insufficient, as there were maybe 50 different places in 24 different code files where I had to update hardcoded switch-statements that only branched for the original two file types.
Unfortunately there is no consistency in this; there are methods which operate half from the XML file, and half off of hardcode. Some of the files which look like they would operate off of the XML file don't, and some that I would expect that I'd need to update the hardcode don't need it. So the only way to find the majority of these is to run through testing the whole system when only part of it is operational, finding that one step to fix (when I'm lucky that error logging actually tells me what is going on), and then running the whole thing again. This wastes time testing the parts of the code which are already confirmed to work, time better spent testing the new parts I have to add on top of it all.
It's a hassle and a half, and to my luck I can expect that I will have to add yet another new kind of file in the near future.
Are there any solutions out there which can aid in this kind of endeavour? Something which I can input some parameters of current features, document what points in a whole code project actually need to be updated, and run something nice the next time I need to add a new feature to the code. It needn't even be fully automated, something that'll help me navigate straight to the specific points in everything and maybe even record what kind of parameters need to be loaded.
Doubt it matters specifically, but the code is comprised of ASP.NET pages, some ASP.NET controls, hundreds of C# code files, and a handful of additional XML files. It's all currently in a couple big Visual Studio 2008 projects.
Not exactly what you are describing, but if you can introduce a seam into the code and lay down some interfaces you can break out and mock, a suite of unit/integration tests would go a long way to helping you modify old code you may not fully understand well.
I completely agree with the comment about using Michael Feathers' book to learn how to wedge new tests into legacy code. I'd also strongly recommend Refactoring, by Martin Fowler. What it sounds like you need to do for your code is to implement the "Replace conditionals with polymorphism" refactoring.
I imagine your code today looks somewhat like this:
if (filetype == 23)
{
type23parser.parse(file);
}
else if (filetype == 69)
{
filestore = type69reader.read(file);
File newfile = convertFSto23(filestore);
type23parser.parse(newfile);
}
What you want to do is to abstract away all the "if (type == foo)" kinds of logic into strategy patterns that are created in a factory.
class FileRules : pReader(NULL), pParser(NULL)
{
private:
FileReaderRules *pReader;
FileParserRules *pParser;
public:
void read(File* inFile) {pReader->read(inFile);};
void parse(File* inFile) {pParser->parse(inFile);};
};
class FileRulesFactory
{
FileRules* GetRules(int inputFiletype, int parserType)
{
switch (inputFiletype)
{
case 23:
pReader = new ASCIIReader;
break;
case 69:
pReader = new EBCDICReader;
break;
}
switch (parserType)
... etc...
then your main line of code looks like this:
FileRules* rules = FileRulesFactory.GetRules(filetype, parsertype);
rules.read(file);
rules.parse(file);
Pull off this refactoring, and adding a new set of file types, parsers, readers, etc., becomes as simple as writing one exclusive to your new type.
Of course, go read the book. I vastly oversimplified it here, and probably got stuff wrong, but you should get the general idea of how to approach it from this. I can also recommend another book, "Head First Design Patterns", which has a great section on the Factory patterns (if you like those "Head First" kinds of books.)

Resources