C# Allow user to enter conditional rules - c#

I write code in isolation, that is I work for myself. I need some advice on how you might implement the following functionality or if there are some tools that already exist to help make this task easier to accomplish.
I have a scenario (C# application) in which I would like the user to be able to enter conditional rules which will then be used elsewhere in the program for various calculations.
As a simple example let's say we have a TimeRequiredForJob property and we need to calculate this in the program based upon the users rules. A simple rule might be
TimeRequiredForJob = 200 Balloons multiplied by 5 min each, or
TimeRequiredForJob = 20% of HoursInAfternoon
I am guessing its pretty hard to see what I am looking for so maybe the following image will help:
This is from DevExpress XtraGrid and it allows a user to filter data displayed in the grid based upon the users custom filter rules. I would like to implement something similar but be able to save the rules to a database and use those rules later in the application.
Any suggestions or tips welcome.
[Late Edit]
Actually I am getting some good information from this question but any additional information will be appreciated.

Forgetting about the GUI for a second, you will need to first need to build some kind of rule evaluation processor.
You may find this article on building an Evaluation Engine helpful. It describes processing text expressions into a form that can be evaluated.
Once you have a way of representing these rules (either as an object structure or as text expressions) the task of building a GUI to suit your specific requirements will become easier.

Related

User Friendly way to use formula for calculation

I have an object model that I need the user to be able to create a formula based on, and also use some built-in functions. For example:
AddWorkDays(MyObject.StartDate, 3)
MyObject has various properties that the user may access. We may also need to do some If/Then statements. The users are very familiar with Excel formulas, because that is how they currently do their work.
I see two possible options:
create my own parser using one of the many available C# Libraries
Adapt an Excel-based parser to be context aware of my objects.
The issue with option 1 is I don't want to re-invent the wheel. I would expect someone has already built a parser that can handle basic functions and math operations and is context aware based on class(es) passed in. I can't seem to find something like this.
Option 2 would allow the user to re-use their existing Excel knowledge to build formulas like:
=if(MyObject.Type = "A", AddWorkDays(MyObject.StartDate, 3), AddWorkDays(MyObject.StartDate, 5)
I see XLParser is advertised as being great for parsing Excel formulas, but it seems I would need to add-on the Context-aware part for reading and validating properties on MyObject.
Any experience, examples, warnings, etc. on how to proceed are welcome
I solved this issue by using the FLEE library: https://github.com/mparlak/Flee
It supports "Context" where you can define variables that should be in context. Out of the box it supports regular syntax for things like addition, subtraction, and even a basic IF statement. It is easily extensible to add your own functions. I made it Excel-like by defining some of the common functions: AND, OR, MIN, MAX. This was less than 100 lines of code to do.
I use it to process relatively large data sets (200,000 items with 5 formulas for each item) and it processes in under 10 seconds if used correctly.

Using application data structures other than xml

I'm designing a survey tool. The survey will be very static and because of that, I can avoid building some kind of table-driven survey designer to accommodate the 167 questions on the survey (all 1-5 rating questions in a radio box or checkbox layout).
I was thinking of building the survey questions in a large XML file, but my non-technical co-worker that will be making frequent edits to the survey will likely do things that will break the integrity/validity of the raw xml file (think punctuation and special characters).
The XML file might look something like:
<questions>
<question>
<type>checkbox</type>
<text>Which beers do you like most</text>
<choices>Bud,Miller,Piels</choices>
<Required>true</Required>
</question>
<question>
<type>radio</type>
<text>Which beer is your favorite</text>
<choices>Bud,Miller,Piels</choices>
<Required>true</Required>
</question>
</questions>
Please use your imagination that this structure will be a bit more complex and that there will be 165 more questions.
Complicating matters, I need these questions in some form of object-oriented layout so that I can take the results and align them to other stuff. I had considered hard-coding a very lengthy survey form with 167 questions, but I need the data in blocks so that I can parse out question 37 and align it to something else in some other feature, that is related to question 37.
Here's what I'd like to do in a .Net app:
Define a enumerable class for this.
Do something where I can manually fill an enumerable collection of this class with all of the data I need. Using the p-code that would be familiar in my .asp world . . .
questions q = new questions()
q.type = "checkbox";
q.text = "which beers do you enjoy"'
q.choices = "Bud,Miller,Peils";
q.required = true;
q.add
q.type = "radio";
q.text = "what is your favorite beer";
q.choices = "Bud,Miller,Peils";
q.required = true;
q.add
My hope is that this .cs file (though foreign looking to the lay person) would be much easier for my co-worker to maintain, without me having to worry about syntax errors.
So, I guess what I'm looking for some feedback on:
Is this just a dumb idea. Should I do this in XML and I'll just consume the XML file and be done with it.
WWYD - What would you do? Is there an easier way to do this?
I don't care about performance as a relatively small number of users are using this.
I don't care about maintainability, because we will write this feature properly in the summer.
I just need to create a data structure that is not in a DB and that can be maintained by a non-technical person with a text-editor (for now).
If anyone made it this far, I appreciate it.
Everyone uses Excel...so consider using a CSV format which can be read by you as well as Excel which your counterpart will be using. One must specify to the user that the columns can't be changed, which is not a drawback per-se, but the user exports the dynamic changes to CSV which the program reads and can verify.
Plus the user does not have to be trained to use Excel so it is a win/win situation per your requirements not to use XMl.
As permanent store XML is good.
But that does not mean the user needs to edit the XML directly.
I would build the ability to edit, add, and delete the questions in the app.
Yes a bit a trouble but if they hack the XML then that is also a lot of trouble.
How do you plan to save survey results?
How do you plan to collect the survey results?
There is more to this project than you are realizing.
Do you need to combine results from more than one device?
If more than one device then you need to separate the questions from the results so you can update the questions on more than one device.
There are tools to read and write XML to disk.
Reading XML with the XmlReader
I don't agree with doug that you need to embed a database.
For a small number of questions I would use XML.
I would read all the XML into an object collection (A List).
You don't need a class the implements IEnumerable.
You put you objects in a a collections that implements IEnumerable.
I would go WPF over WinForms.
A ListBox with a DataTemplate.
On the DataTemplate you can have a dynamic selector in code behind but that is a real hassel.
Consider a single template that you manipulate in code behind.
So they are not RadioButtons but you uncheck the others in code behind.
For filtering I would go LINQ in public properties but there is also CollectionViewSource.
Used XML for an app that was used to collect field measurements.
A lot like this in measuring devices could change and need to collect the measurements.
If you are set on user editing the questions directly then XML with XSD is the best I can think of.
If you are looking for a simple human readable structured format, then you could be interrested by YAML.
YAML is a human-readable data serialization format that takes concepts
from programming languages such as C, Perl, and Python, and ideas from
XML and the data format of electronic mail.
Your question file would look like this:
questions:
- id: 1
type: checkbox
text: Which beers do you like most
choices: Bud,Miller,Piels
Required: true
- id: 2
type: radio
text: Which beer is your favorite
choices: Bud,Miller,Piels
Required: true
Some YAML libraries exists in .NET (from the article):
https://github.com/aaubry/YamlDotNet
http://yaml.codeplex.com/
http://www.codeproject.com/Articles/28720/YAML-Parser-in-C
http://yaml-net-parser.sourceforge.net/
There are plenty of xml editing tools out there that will actually make it easier to edit than editing a text file directly. I use XML Marker and it's pretty easy to use. http://symbolclick.com/
It will be quicker to train them to edit using the tool than it will be to build one.
Two answers here;
a: Write it to allow a proper admin interface, using a database to allow admin users to add/edit questions, response options and include appropriate security, auditing etc. You mention that this may not be feasible in the short term or that a 'proper' feature will be added soon, in which case, scrap this!
b: People say they have frequent edits/changes to make, but is this not a requirement which is co-related to a complete feature? Could you not in the short term, accept manual requests for change via email or something else documented, and make them yourself? Do you think the time taking to add a question/response or change some wording would be less than needing to parse XML manually to find a syntax error from someone who isn't familiar?
You'll need to weigh up frequency of change with impact to yourself of making a change vs likelihood of user error, vs estimated time needed to identify and resolve a syntax error (plus the possible bad-will of having a change break things).
Despite what some people think, users don't like making mistakes! putting them in a position where they have admin level powers over a system they don't have a full technical grasp of, could reduce confidence and future buy-in to the feature you're due to develop.
TLDR; In my opinion, unless it's a major hassle, do the changes yourself in the short term, perhaps with a maximum amount of time you'll make them (I make one change set a week, on a Friday for example). Keep the system working perfectly, and involve the users without putting them in an uncomfortable position being an non voluntary early adopter for a feature which isn't finished.
I used my complete mastery over winforms to create a little mock GUI application that enables users to quickly create one dimensional non conditional lists of questions with different question types.
Once you decided on an xml scheme you can easily import and export xml files.
Are you interested in further development of the magical survey creator? If so tell me and I will send you a practically finished prototype tomorrow morning. (You should provide me with an xml scheme though, otherwise I will do it in CSV)
I enjoy the exercise.
Picture related. Don't be put off by the colors, that's how I like it during development, to see the pixel exact boundaries of controls.
Unless your coworkers have some experience with programming or xml editing they will hate you if you instruct them to edit any sort of "code".
Our secretaries put their hand in front of their faces and start chanting "no, no, no..." when I tell them how to operate VBA macros.

ASP.Net: Best Way To Handle Multi-Function Form Based on User

In my scenario, let's say there is a ASP.Net 4.0 C# page containing a form with several inputs on it. Based upon which state the user is in, the form needs to act in entirely different ways: some fields might be required, some not visible at all, some might have different requirements (state A might only allow numbers 1-5, state B numbers 5-10), etc.
So, to simplify things, let's just say for any given input on the form, I need to determine whether or not it's required for the user, again based on their state. For those of you who run into this scenario quite a bit, what's the best way of implementing a system to handle this? I can see the following options:
Hardcoded - Difficult to maintain, obviously
Custom Database Rule Framework - This seems like it would work; however, it would be somewhat of a pain to maintain depending on how complicated the logic is
Windows Workflow Foundation - This would be able to handle just about any kind of logic, and be decent to maintain, but I'm not sure how this would do performance wise. (could be stored externally in database)
Dynamic Code - Store the logic in a database and run it directly based upon the user. I've never done this.. is it possible?
That's all I've come up with at this point, but I'm hoping someone out there has found an elegant solution to handle scenarios with complicated forms like this.
Thanks!
I have never worked with WWF, but I have encountered a scenario like this and implemented an entry form for it that works well and is easy to maintain once you understand the system.
I will discourage you from using hardcoded logic because any degree of complexity will quickly become impossible to maintain. I tried a hybrid approach that included some hardcoding initially and it did not turn out well.
I ended up creating, as you call it, a custom database rule framework. It is a little extra work to set up config forms to associate user groups with certain codes and pieces of functionality, but in the end it is well worth it for everything to automatically configure itself. Also in my case I was able to farm out user & code setup work to a supervisor in the department that uses the application, so that is a big plus.
Hardcoding -- not so hard to maintain, just depending on how fluid the rules are. I.e., if your "states" are relatively fixed, you're not adding new ones or changing the way those states interact with the page, then hardcoding might be fine. My only recommendation in this case would be to keep it in a separate class so you can re-use it, modify & re-publish easier, etc.
If you want the flexibility to change the rules a lot, create new states (I'm thinking of these as "roles"), then storing the info in a database would make more sense.
Personally, I use the database approach. It saves me some re-publsihing of the app, and it has allowed me to build additional interfaces for my end-users to have limited capability to manage their own app in terms of role assignments ("states" as you put it), etc. For example, my end-users can grant one of their clients (based on the client's login) access to a certain report. Or in your situation, they could change the min number for some range-validator your .aspx is using.
Since this approach lets me delegate some admin functions to my end-users, it allows them to do on-the-fly changes (to a limited extent), and also saves me a lot of rush-work / do it yesterday work as far as my own to-do list is concerned.

Any tools, libraries or suggestions to simplify dynamic question functionality?

I am working on an ASP.NET project that is relatively simple except for one requirement which requires custom questionnaires be attached to specific types of tasks. These questionnaires need to be customized regularly and no development, within the app itself, should be needed add questionnaires. The questionnaires currently do not require an editing tool and can be done by uploading a template, changing something in a DB, whatever. They can be stored in any format and the resulting output needs to be captured to be edited or viewed later.
The types of questions in the questionnaire could be:
Selections (select one from a list)
Input (text, integers, dates, etc)
Yes/No
The ability to display questions based on answers from other questions. For example if they answer yes to question X, display question Y else display question Z. Need to be able to apply data validation such as required fields, ranges, etc on questions (could all be probably capture by basic regex).
The simplest break down would be:
Create a new event.
Based on the type of event display a specific questionnaire.
Questionnaires can change over time but they can be considered as new version each time and data will always be related to a specific version and not need to be migrated to updated versions.
The questionnaire output (data elements and a final calculated value) must be captured.
XML output (or any other format) of data elements entered.
The optimal (unicorn) scenario would be to have a basic template in XML or something that a user can learn to create easily and it would be stored and versioned in a DB. When a user makes a new event, the app would fetch the appropriate template which would display the questionnaire to the user. The user would fill it out and the output would be posted as some type of output (again XML would be nice but not required). That output would be attached to the event. Done.
Are there any .NET compatible tools/libraries that I could leverage to accomplish this? InfoPath seems like a tool that might be of use but I have almost zero experience with it so I am not sure about its constraints / implementation and if it is just overkill. The solution needs to be contained within the ASP.NET application. An external editor tool for creating templates would be ok but the templates must be viewable and editable on the web with no constraints to the user.
Can anyone provide examples of this being done or hints on how you might have tackled this?
Since the application is relatively easy to create other than this one feature, I would rather not spend 80% of my time trying to implement the custom questionnaire functionality and spend more time on the problem the application is trying to solve.
Tech available: ASP.NET, Silverlight, SQL Server
I would suggest having a look at a dot net nuke implementation, I am sure there should be a lot of viable options (if not all free).
DotNetNuke
Have a look at the Forge to see free plugins
Consider evaluating SurveyMaster at CodePlex. It's licensed under Microsoft Public License (Ms-PL), and you can modify its source for your needs.

Ndepend and other automatic code analyser revelence?

Since yesterday, I am analyzing one of our project with Ndepend (free for most of its features) and more I am using it, and more I have doubt about the real value of this type of software (code-analysis software).
Let me explain, The system build a report about the health of the system and class by Rank every metric. I thought it would be a good starting point to do modifications but most of the top result are here because they have over 100 lines inside the class (we have big headers and we do use VS comments styles) so it's not a big deal... than the number of Afferent Coupling level (CA) is always too high and this is almost very true for Interface that we used a lot... so at this moment I do not see something wrong but NDepend seem to do not like it (if you have suggestion to improve that tell me because I do not see the need for). It's the samething for the metric called "NOC" for Number of children that most of my Interface are too high...
For the moment, the only very useful metric is the Cyclomatic Complexity...
My question is : Do you find is worth it to analyse code with Automatic Code Analyser like NDepend? If yes, how do you filter all information that I have mentionned that doesn't really show the real health of the system?
Actually metrics are just one feature of NDepend, did you try to use VisualNDepend that lets you analyze your project much more in depth than the report? By reading your comment, I am almost sure you didn't play with NDepend UI (standalone or integrated in Visual Studio) which is the best way to filter data about your code base.
I am one of the developers of NDepend and we use it a lot to analyze our own code. Basically we write our own quality rules with Code Rules over LINQ Queries (CQLinq). These rules automatically make sure that we don't have regression on our design. Here you'll find the list of around 200 default code rules.
Here are some unique features of NDepend and not related to code metrics:
Write CQLinq rules to make sure we don't have architectural flaws, such as dependency cycles between our components, UI using directly the DB or DB entangled with the business objects.
Make sure we don't have problem with code coverage by tests (like we make sure with a CQLinq rule that if a class is supposed to be 100% covered, it will remain 100% covered in the future)
Enforce side-effects-free code (immutable class/pure methods)
Use the ability to compare 2 analysis to code review changes since the last release, before doing a new release. More specifically, I enjoy using NDepend to know which method has been added and refactored since the last release, and is not 100% covered by tests.
Having an optimal encapsulation for all our members and types (like knowing which internal methods can be declared as private). This is also related to dead-code detection that NDepend also supports.
For a complete list of features if NDepend, see here.
I don't necessarily see NDepend results as "good" or "bad" in software engineering, there's always a good reason why an application is designed the way it is. I see it as a report that can probably help me point out issues with my design, but I have the final word when it comes to deciding if a method needs to be refactored or if it's good the way I designed it. In general, don't get too caught up trying to answer if it's worth it or not. It definitely is, instead I would suggest you carefully review the results. This will help you view your design from another perspective and there may be occasions where you decide the way you designed it is the best to achieve your applications goals.

Categories

Resources