building a "scriptable" application - c#

During development of a new application, I was wondering how the most flexible solution of a dynamic, let's say ‘scriptable’, system would look like.
In general, I would need a file in plain text (e.g. TXT or XML) wherein I define a trigger (in my example a hex string) and a corresponding action (open a window, execute a SQL transaction, …). I should be able to add new entries without recompiling the whole application.
As you see, it's not really scriptable this way, but I need a solution to define what happens with which input.
Has anyone got some experience with this?

There are various scripting languages you can use inside your .NET application; IronPython being one obvious example, but others are available - javascript for example (talking to your .NET objects; not in a browser). One of these might have some application here?

If you have only simple program flow you can use Windows Workflow Foundation Rules Engine.
Features
Inlcuded in dotnet3.0 runtime, no extra costs
RuleSetDialog can be integrated into your code to edit rules including intellisense
persistable as xml-files.
ruleengine can evaluate expressions and can perform actions
See also
A quick and dirty Rules Engine using Windows Workflow Part1 and Part2
I first found this topic when reading the german languaged magazine dotnetpro 10/2010 on page 30 "Die Rule-Engine aus .NET ohne Workflow benutzen"

Well you can embed a .NET language like IronPython or possibly Boo

Related

Creating Inline Functions and Macros

I know this is wrong (trying to code in C# with a C/C++ mindset).
But is it possible to create inline functions / inline recursive functions (til the Nth call) / macros in C#?
Because if I intend to call the same function 1000 times, but it's a simple function, the overhead of creating the stack is quite big... And unnecessary.
In C i could use inline functions. Is there something like that in C#?
Again... I'm not saying that C/C++ is better... I'm just new to C# and have none to ask those simple questions...
Inline functions in C#?
Finally in .NET 4.5, the CLR allows one to force1 method inlining
using MethodImplOptions.AggressiveInlining value. It is also available
in the Mono's trunk (committed today).
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
void Func()
{
Console.WriteLine("Hello Inline");
}
The answer should be: don't worry about it. No need to start with micro-optimizations unless you've tested it and it's actually a problem. 1000 function calls is nothing until it's something. This is majorly overshadowed by a single network call. Write your program. Check the performance against the goals. If it's not performant enough, use a profiler and figure out where your problem spots are.
Yes, C# is a very powerful general purpose language that can do nearly anything. While, inline functions / macros are generally frowned upon, C# does provide you with multiple tools that can accomplish this in a more concise and precise fashion. For example, you may consider using template files which can be used (and reused) in nearly all forms of .NET applications (web, desktop, console, etc).
http://msdn.microsoft.com/en-us/data/gg558520.aspx
From the article:
What Can T4 Templates Do For Me?
By combining literal text, imperative code, and processing directives, you can transform data in your environment into buildable artifacts for your project. For example, inside a template you might write some C# or Visual Basic code to call a web service or open an Excel spreadsheet. You can use the information you retrieve from those data sources to generate code for business rules, data validation logic, or data transfer objects. The generated code is available when you compile your application.
If you're new to programming I would recommend against implementing templates. They are not easy to debug in an N-Tier application because they get generated and ran at run-time. However, it is an interesting read and opens up many possibilities.

Alternative localization with extension methods

I am about to start a localization project for my employer. It concerns a pre-existing project with many windows forms and an established code base, programmed in C# and ASP.NET. I have done research into how to localize an application in visual studio and found resources.
While these are an adequate solution to the problem, I am not entirely happy with the down sides of using resources. This is to say, it has a rather large footprint, requiring changes in each of the form files. Furthermore, the resource files are only editable from within Visual Studio. I would prefer enabling external translators without programming knowledge to do the translation.
So I came up with an alternative solution:
Build a static localization utility class with an extension method on String:
public static String Localize(this String s)
The utility class loads localization strings from file on startup. When the program needs a string somewhere, it is called as
"foo".Localize();
And the program would use the string itself as the key in the table to find the translation.
It seems a safe and effective solution, and I'm happy with the small footprint that it leaves on the existing codebase.
Basically I want to ask:
Are there downsides to my solution that I've missed?
Which file formats for the localization data should I look into (I've already encountered the .po file format)?
Is it a good enough reason to deviate from the resource files solution?
Any advice and/or considerations you may have will be appreciated.
You are trying to reinvent the wheel that MS invented long ago. You can use plenty of tools available for resources or even write your own Resources provider.
Some tools available: What tools are available for adding Localization to an ASP.NET project?
If you want to use a database for translators: Data Driven Resource provider from Rick Strahl
Are there downsides to my solution that I've missed?
I can point out some, what about the texts in the aspx files. Are you going to make your extension method available to them as well? That would be tough I guess.
e.g. <asp:Label Text="Title"> - how are you going to translate that?
Further, some of your claims are not entirely true.
the resource files are only editable from within Visual Studio
They are xml files , so you can use any editor to edit them or write a custom utility to do that.
Are there downsides to my solution that I've missed?
The standard resource files go beyond changing the text.
You might need to resize certain elements to fit the new text (if you don't use the existing layout management mechanism). And for some languages you will need to change the fonts/fonts sizes (think Chinese, Japanese, Korean) or alignment (think right-to-left languages like Arabic and Hebrew).
Also, translating standard files means that using an editor that is aware of the format one can see the dialog "as is", so it gives more context than stand-alone strings, which results in better translation quality.

c# compile source code from database

I would like to build an application framework that is mainly interpreted.
Say that the source code would be stored in the database that could be edited by the users and always the latest version would be executed.
Can anyone give me some ideas how does one implement sth like this !
cheers,
gabor
In .Net, you can use reflection and CodeDOM to compile code on the fly. But neither approach is really very simple or practical. Mono has some ability to interpret c# on the fly as well, but I haven't looked closely at it yet.
Another alternative is to go with an interpreted .Net language like Boo or IronPython as the language for your database code.
Either way, make sure you think long and hard about the security of your platform. Allowing users to execute arbitrary code is always an exercise fraught with peril. It's often too tempting to look for a simple eval() method, and even if one exists, that is not good enough for this kind of scenario.
Try Mono ( http://www.monoproject.org ). It supports many scripting languages including JavaScript.
If you don't want to use any scripting you can use CodeDOM or Reflection (see Reflection.Emit).
Here are really useful links on the topic :
Dynamically executing code in .Net (Here you can find a tool which can be very helpul)
Late Binding and On-the-Fly Code
Generation Using Reflection in C#
Dynamic Source Code Generation and
Compilation
Usually the Program uses a scripting language for the scriptable parts, i.e. Lua or Javascript.
To answer your technical question: You don't want to write your own language and interpreter. That's too much work for you to do. So pick some other language, say Python or Lua, and look for the documentation that lets your C program hand it blocks of code to execute. Of course, the script needs to be able to do something, so you'll need to find how to expose your program's objects to the script. Also, what will happen if a client is running the program when you update its source code in the database? Should the client restart? Are you going to store the entire program as a single row in this database, or did you want to store individual functions? That affects how you structure your updates.
To address other issues with your question: Why do you want to do this? Making "interpreted language" part of your design spec for a system is not often a good sign. Is the real requirement something like this: "I update the program often and I want users to always have the latest copy?" If so, there are other, better ways to go about this (just give us your actual scenario and requirements).

Project management: Implementing custom errors in VS compilation process

AGAIN: If you're voting -1, please leave a comment explaining why. This post isn't about whether or not you approve if this approach, but how to go about it.
Like many architects, I've developed coding standards through years of experience to which I expect my developers to adhere.
This is especially a problem with the crowd that believes that three or four years of experience makes you a senior-level developer.Approaching this as a training and code review issue has generated limited success.
So, I was thinking that it would be great to be able to add custom compile-time errors to the build process to more strictly enforce our in-house best practices and coding standards.
For instance, we use stored procedures for ALL database access, which provides procedure-level security, db encapsulation (table structure is hidden from the app), and other benefits. (Note: I am not interested in starting a debate about this.) Some developers prefer inline SQL or parametrized queries, and that's fine - on their own time and own projects.
I'd like a way to add a compilation check that finds, say, anything that looks like
string sql = "insert into some_table (col1,col2) values (#col1, #col2);"
and generates an error or, in certain circumstances, a warning, with a message like
Inline SQL and parametrized queries are not permitted.
Or, if they use the var keyword
var x = new MyClass();
Variable definitions must be explicitly typed.
Do Visual Studio and MSBuild provide a way to add this functionality? I'm thinking that I could use a regular expression to find unacceptable code and generate the correct error, but I'm not sure what, from a performance standpoint, is the best way to to integrate this into the build process.
We could add a pre- or post-build step to run a custom EXE, but how can I return line- and file-specifc errors? Also, I'd like this to run after compilation of each file, rather than post-link.
Is a regex the best way to perform this type of pattern matching, or should I go crazy and run the code through a C# parser, which would allow node-level validation via the parse tree?
I'd appreciate suggestions and tales of prior experience.
Comments
Several respondents have pointed out that it's possible to restrict the ability of a user to run anything but a stored proc through db permissions. However, we're in the process of porting a 350k+ line application from ASP 3.0 to ASP.NET MVC, and the existing code base relies pretty heavily on concatenated SQL, whereas the new stuff all uses Enterprise Library. I guess I could add a separate web user account for the .NET code with more restrictive permissions.
For coding standards I would look at writing custom rules for FxCop or StyleCop. I don't think Regex would be a suitable tool for the job.
For the specific case of requiring Stored Procedures - if you ensure the application doesn't have permission to do anything else on the production database, everyone will soon fall in line.
What about writing a plugin for Resharper? Here is a tutorial to start with: Writing plug-ins for ReSharper: Part 1 of Undefined
Implicit typing (var x = ....) is a feature that can be turned off on project level in visual studio.
The other one is trickier. Have you had a look at FxCop, which is the tool for enforcing code standards.
The requirement that only stored procedures can be used should be managed through database permissions. The rule against using var seems fairly arbitrary to me and I can't think of a way to enforce it. Do you have any more examples of your best practices?

How do I best localize an entire app to many different languages?

I'm using Visual Studio (2005 and up). I am looking into trying out making an application where the user can change language for all menues, input formats and such. How would I go on doing this, as I suppose that there is some complete feature within .Net that can help me with this?
I need to take the following into account (and fill me in if I miss some obvious stuff)
Strings (menues, texts)
Input data (parsing floats, dates, etc..)
Should be easy to add support for another language
I'm not an expert with .NET by any means but Localization is never just as simple as "swapping out String values" or "changing date formats". There is much more to be taken into consideration such as layout, proper text placement.
Take Chinese for example. The way you read is top to bottom not left to right. If properly localized the app should take that into account.
http://msdn.microsoft.com/en-us/library/y99d1cd3(VS.80).aspx seems to be a good start though if you're dealing with Windows Forms.
The classic recipe is: design the app with no native language but a localization facility, and develop an initialization into one language (e.g., English). So you build the app and localize it into English every night; without the localization step it would not be usable. Do that well, and the resources for the initial sample localization can be replaced with those for any other language. Take into account non-roman scripts from the beginning. It's much cleaner to have a no-language app that always requires localization rather than a language-specific app that needs to have its native language subtracted and a replacement added.
For strings you should just separate your strings from your code (having an XML/DLL that will transform string IDs to real strings is one way to go). However you do need to make sure that you are supporting double byte characters for some languages (this is relevant if you use C/C++).
For input data what you want is to have different locale's. In Java this is relatively easy, and if you use C# it probably is quite easy also. In C/C++ I don't really know. The basic idea is that the input parsers should be different based on the locale selected at that time. So each field (textfield, textbox, etc.) must have an abstract parser that is then implemented by a different class depending on the locale (right to left, double byte, etc.).
Check the Java implementation for details on how they did it. It is quite functional.
You definitely need to be using the .NET ResourceManager and the resx file xml format, however there are a number of approaches to using this.
It really depends on what you are wanting to achieve. For me I wanted a single xml resource file (for each supported language) that could be modified by anyone. I created a helper class that loaded the global resource file into ResourceManager (once only) and I had a helper function that gives me the required resource for a given name. The only disadvantage in this approach was that I could not leverage dynamic binding of resources to properties.
I found this better and easier to manage than multiple or embedded resource files for every form. Additionally exactly the same approach can used in an ASP.NET application. I also found this approach means that outsourcing translation of resources and shipping language packs to customers much more manageable.
Microsoft's recommended approach is to use satellite assemblies, as described in Packaging and Deploying Resources. If you're using a ResourceManager to load resources, .NET will load the correct resources for the CurrentUICulture. This defaults to the user's current UI language setting in Windows.
It is possible to localize Windows Forms either through Visual Studio or an external tool, WinRes.exe. This article describes WinRes and how to use Visual Studio to localize the form.

Categories

Resources