Elegant way of switching between ValidationSummary and single validation strings - c#

In a nutshell, let's say I have two textboxes, both have RequiredFieldValidator controls. I want to display only a single string in ValidationSummary control if both of the values are not valid and one string, in the place of RequiredFieldValidator if only one is not valid.
Currently, What I have is working but it is a bit messy. Was wondering if there is easier, more elegant way, of doing this.
if ((!Text1Valid.IsValid) && (!Text2Valid.IsValid))
{
// Make sure the individual validator shows nothing and ValidationSummary is visible.
Text1Valid.Display = ValidatorDisplay.None;
Text2Valid.Display = ValidatorDisplay.None;
ValidSummary.Visible = true;
Text1Valid.ErrorMessage = "Both of the values are wrong!";
Text2Valid.ErrorMessage = String.Empty;
}
else
{
// Single validation strings visible and ValidationSummary hidden.
Text1Valid.Display = ValidatorDisplay.Dynamic;
Text2Valid.Display = ValidatorDisplay.Dynamic;
ValidSummary.Visible = false;
Text1Valid.ErrorMessage = "The value is wrong.";
Text2Valid.ErrorMessage = "The value is wrong.";
}

There definitely is not an out of box way to do what you want in a an easier/elegant fashion that I'm aware of. In terms of custom code it's a bit difficult to get a really elegant solution because the validation logic is very coupled. I can totally imagine the situation where you have a variety of validators on each input, differing numbers of "linked" inputs, and different types of input elements. If this is a one off situation, a solution similar to yours is probably ok. If this is a recurring theme for you project then you probably want to think about how much time you can afford to invest into a more robust solution.

Related

Ways to handle different data type restrictions in a "textbox" that come from SQL Server - C# Winforms

I am currently developing a software to integrate and be a nice front end UI to a database that doesn't have a front end UI. Part of this UI has a spot where there is a listbox on the left and on the right will be multiple sections of a drop down box on the left and a "textbox" on the right with an "and" and "or" radio button below it. It looks similar to the following linked picture.
So with that being said, one of the things I want to do is based on the column that is chosen on the left, the "textbox" will restrict/force reformat the data entered accordingly. So if it is a column of datetime formatting, then the textbox will only allow that kind of input. If the restriction is int[x], then the only input will be no more than the limitation of the integer, etc. etc. but not allow any letters to be inputted.
So this is where the real struggle comes in. I am struggling to figure out how to only allow specific input to the box based on the column chosen. Do I leave it as a text box and then use conditional statements that restrict the data input based on the formatting of the column? (Which this is how I am planning on currently programming it. However, this requires a lot of conditions and making sure to try and handle any and all possibilities out there.) Or is there a better way to handle the different types of SQL Server data types that will potentially be present? As in I create a box with the appropriate input restrictions and somehow dynamically swap them in/out based on the column selected at the time.
The biggest one that makes me question is the datetime formatting. I would love to use a date picker box (make sure I make it as idiot proof as I can). However, I am not sure if there would be an easy way to switch between a date picker box and any other boxes that could be necessary to have and have it all be seamless.
NOTE: All of the data will be stored so that if you go back to a column you already input data for, it will pull it back up.
Grateful for all of the feedback and input.
The way I read your question, you have solved the issue of determining the datatype of the SQL Server column. If that is correct, then all you would need to do is swap out controls based on the datatype of the column. Something like the following:
switch (columnType)
{
case int:
TextBoxInt.Visible = true;
TextBoxString.Visisble = false;
DateTimePicker.Visible = false;
break;
case string:
TextBoxString.Visible = true;
TextBoxInt.Visible = false;
DateTimePicker.Visible = false;
break;
case DateTime:
DateTimePicker.Visible = true;
TextBoxInt.Visible = false;
TextBoxString.Visible = false;
break;
}
Then you can handle limiting the input for each of the controls appropriately based on the datatype that it is for.
Maybe what you're looking for is to possibly handle the datatypes by letting sql do the work for you.
Sometimes it seems there's no way out of validating the user input with conditionals, but there are ways of making it simpler.
For many of problems handling the conditions you can probably use different parsing methods that throw exceptions. When the exceptions is thrown you can have it control the bool condition for submit. DateTime.Parse() is one of them.
For the date-time parsing problem you may be experiencing maybe this post to convert the textbox to a string and use DateTime.Parse(). DateBox Forced Formatting Logic.
Additonally, rather than a text box it may be useful to use a DateTimePicker object.

How to centrally maintain a mathematical formula in C# (web) so it can be changed if needed?

We have an application that has a LOT of mathematical checks on the page and according to it, the user is given a traffic light (Red, green, yellow).
Green = He may continue
Red = Dont let him continue
Yellow = Allow to continue but warn
These formulas operate on the various text-fields on the page. So, for example, if textbox1 has "10" and texbox2 has "30"... The formula might be:
T1 * T2 > 600 ? "GREEN" : "RED"
My question is:
Is it possible to somehow centralize these formulas?
Why do I need it?
Right now, if there is any change in a formula, we have to replicate the change at server-side as well (violation of DRY, difficult to maintain code)
One option could be to
- store the (simple) formula as text with placeholders in a config(?)
- replace the placeholders with values in javascript as well as server-side code
- use eval() for computation in JS
- use tricks outlined here for C#
In this approach issue could be different interpretations of same mathematical string in JS and C#.
Am i making sense or should this question be reported?!! :P
Depending on your application's requirements, it may be acceptable to just do all the validation on the server. Particularly if you have few users or most of them are on a reasonably fast intranet, you can "waste" some network calls to save yourself a maintenance headache.
If the user wants feedback between every field entry (or every few entries, or every few seconds), you could use an AJAX call to ask the server for validation without a full page refresh.
This will, of course result in more requests than doing the validation entirely on the client, and if many of your users have bad network connections there could be latency in giving them the feedback. My guess is the total bandwidth usage is about the same. You use some for every validation round-trip, but those are small. It may be outweighed by all that validation JS that you're not going to send to clients.
The main benefit is the maintenance and FUD that you'd otherwise have keeping the client and server validation in sync. There's also the time savings in never having to write the validation javascript.
In any case, it may be worth taking a step back and asking what your requirements are.
The Microsoft.CSharp.CSharpCodeProvider provider can compile code on-the-fly. In particular, see CompileAssemblyFromFile.
This would allow you to execute code at runtime from a web.config for instance; however use with caution.
You could write C# classes to model your expressions with classes such as Expression, Value, BooleanExpr, etc. (an Abstract Syntax Tree)
e.g.
Expression resultExpression = new ValueOf("T1").Times(new ValueOf("T2")).GreaterThan(600).IfElse("RED","GREEN")
^Variable ^Variable ^Value=>BoolExpr ^(Value, Value) => Value
These expressions could then be used to evaluation in C# AND to emit Java script for the checks:
String result = resultExpression.bind("T1", 10).bind("T2",20).evaluate() //returns "RED"
String jsExpression resultExpression.toJavaScript // emits T1 * T2 > 600 ? "RED" : "GREEN"
You can make a low level calculator class that uses strings as input and pushes and pops things onto a stack. Look up a "Reverse Polish Calculator". If the number of inputs you are using doesn't change this would be a pretty slick way to store your equations. You would be able to store them in a text file or in a config file very easily.
for instance:
string Equation = "V1,V2,+";
string ParseThis = Equation.Replace("V1", "34").Replace("V2", "45");
foreach(string s in ParseThis.split(',')) {
if (s == "+") {
val1 = stack.Pop();
val2 = stack.Pop();
return int.parse(val1) + int.Parse(val2);
}
else {
stack.Push(s);
}
}
obviously this gets more complicated with different equations but it could allow you to store your equations as strings anywhere you want.
apologies if any of the syntax is incorrect but this should get you going in the right direction.
The simplest solution would be to implement the formulae once in C# server-side, and use AJAX to evaluate the expressions from the client when changes are made. This might slow down the page.
If you want the formulae evaluated client-side and server-side but written only once, then I think you will need to do something like:
Pull the formulae out into a separate class
For the client-side:
Compile the class to Javascript
Call into the javascript version, passing in the values from the DOM
Update the DOM using the results of the formulae
For the server-side:
Call into the formulae class, passing in the values from the form data (or controls if this is web-forms)
Take the necessary actions using the results of the formulae
.. or you could do the converse, and write the formulae in Javascript, and use a C# Javascript engine to evaluate that code server-side.
I wouldn't spend time writing a custom expression language, or writing code to translate C# to Javascript, as suggested by some of the other answers. As shown in the questions I linked to, these already exist. This is a distraction from your business problem. I would find an existing solution which fits and benefit from someone else's work.

Better method of handling/reading these files (HCFA medical claim form)

I'm looking for some suggestions on better approaches to handling a scenario with reading a file in C#; the specific scenario is something that most people wouldn't be familiar with unless you are involved in health care, so I'm going to give a quick explanation first.
I work for a health plan, and we receive claims from doctors in several ways (EDI, paper, etc.). The paper form for standard medical claims is the "HCFA" or "CMS 1500" form. Some of our contracted doctors use software that allows their claims to be generated and saved in a HCFA "layout", but in a text file (so, you could think of it like being the paper form, but without the background/boxes/etc). I've attached an image of a dummy claim file that shows what this would look like.
The claim information is currently extracted from the text files and converted to XML. The whole process works ok, but I'd like to make it better and easier to maintain. There is one major challenge that applies to the scenario: each doctor's office may submit these text files to us in slightly different layouts. Meaning, Doctor A might have the patient's name on line 10, starting at character 3, while Doctor B might send a file where the name starts on line 11 at character 4, and so on. Yes, what we should be doing is enforcing a standard layout that must be adhered to by any doctors that wish to submit in this manner. However, management said that we (the developers) had to handle the different possibilities ourselves and that we may not ask them to do anything special, as they want to maintain good relationships.
Currently, there is a "mapping table" set up with one row for each different doctor's office. The table has columns for each field (e.g. patient name, Member ID number, date of birth etc). Each of these gets a value based on the first file that we received from the doctor (we manually set up the map). So, the column PATIENT_NAME might be defined in the mapping table as "10,3,25" meaning that the name starts on line 10, at character 3, and can be up to 25 characters long. This has been a painful process, both in terms of (a) creating the map for each doctor - it is tedious, and (b) maintainability, as they sometimes suddenly change their layout and then we have to remap the whole thing for that doctor.
The file is read in, line by line, and each line added to a
List<string>
Once this is done, we do the following, where we get the map data and read through the list of file lines and get the field values (recall that each mapped field is a value like "10,3,25" (without the quotes)):
ClaimMap M = ClaimMap.GetMapForDoctor(17);
List<HCFA_Claim> ClaimSet = new List<HCFA_Claim>();
foreach (List<string> cl in Claims) //Claims is List<List<string>>, where we have a List<string> for each claim in the text file (it can have more than one, and the file is split up into separate claims earlier in the process)
{
HCFA_Claim c = new HCFA_Claim();
c.Patient = new Patient();
c.Patient.FullName = cl[Int32.Parse(M.Name.Split(',')[0]) - 1].Substring(Int32.Parse(M.Name.Split(',')[1]) - 1, Int32.Parse(M.Name.Split(',')[2])).Trim();
//...and so on...
ClaimSet.Add(c);
}
Sorry this is so long...but I felt that some background/explanation was necessary. Are there any better/more creative ways of doing something like this?
Given the lack of standardization, I think your current solution although not ideal may be the best you can do. Given this situation, I would at least isolate concerns e.g. file read, file parsing, file conversion to standard xml, mapping table access etc. to simple components employing obvious patterns e.g. DI, strategies, factories, repositories etc. where needed to decouple the system from the underlying dependency on the mapping table and current parsing algorithms.
You need to work on the DRY (Don't Repeat Yourself) principle by separating concerns.
For example, the code you posted appears to have an explicit knowledge of:
how to parse the claim map, and
how to use the claim map to parse a list of claims.
So there are at least two responsibilities directly relegated to this one method. I'd recommend changing your ClaimMap class to be more representative of what it's actually supposed to represent:
public class ClaimMap
{
public ClaimMapField Name{get;set;}
...
}
public class ClaimMapField
{
public int StartingLine{get;set;}
// I would have the parser subtract one when creating this, to make it 0-based.
public int StartingCharacter{get;set;}
public int MaxLength{get;set;}
}
Note that the ClaimMapField represents in code what you spent considerable time explaining in English. This reduces the need for lengthy documentation. Now all the M.Name.Split calls can actually be consolidated into a single method that knows how to create ClaimMapFields out of the original text file. If you ever need to change the way your ClaimMaps are represented in the text file, you only have to change one point in code.
Now your code could look more like this:
c.Patient.FullName = cl[map.Name.StartingLine].Substring(map.Name.StartingCharacter, map.Name.MaxLength).Trim();
c.Patient.Address = cl[map.Address.StartingLine].Substring(map.Address.StartingCharacter, map.Address.MaxLength).Trim();
...
But wait, there's more! Any time you see repetition in your code, that's a code smell. Why not extract out a method here:
public string ParseMapField(ClaimMapField field, List<string> claim)
{
return claim[field.StartingLine].Substring(field.StartingCharacter, field.MaxLength).Trim();
}
Now your code can look more like this:
HCFA_Claim c = new HCFA_Claim
{
Patient = new Patient
{
FullName = ParseMapField(map.Name, cl),
Address = ParseMapField(map.Address, cl),
}
};
By breaking the code up into smaller logical pieces, you can see how each piece becomes very easy to understand and validate visually. You greatly reduce the risk of copy/paste errors, and when there is a bug or a new requirement, you typically only have to change one place in code instead of every line.
If you are only getting unstructured text, you have to parse it. If the text content changes you have to fix your parser. There's no way around this. You could probably find a 3rd party application to do some kind of visual parsing where you highlight the string of text you want and it does all the substring'ing for you but still unstructured text == parsing == fragile. A visual parser would at least make it easier to see mistakes/changed layouts and fix them.
As for parsing it yourself, I'm not sure about the line-by-line approach. What if something you're looking for spans multiple lines? You could bring the whole thing in a single string and use IndexOf to substring that with different indices for each piece of data you're looking for.
You could always use RegEx instead of Substring if you know how to do that.
While the basic approach your taking seems appropriate for your situation, there are definitely ways you could clean up the code to make it easier to read and maintain. By separating out the functionality that you're doing all within your main loop, you could change this:
c.Patient.FullName = cl[Int32.Parse(M.Name.Split(',')[0]) - 1].Substring(Int32.Parse(M.Name.Split(',')[1]) - 1, Int32.Parse(M.Name.Split(',')[2])).Trim();
to something like this:
var parser = new FormParser(cl, M);
c.PatientFullName = FormParser.GetName();
c.PatientAddress = FormParser.GetAddress();
// etc
So, in your new class, FormParser, you pass the List that represents your form and the claim map for the provider into the constructor. You then have a getter for each property on the form. Inside that getter, you perform your parsing/substring logic like you're doing now. Like I said, you're not really changing the method by which your doing it, but it certainly would be easier to read and maintain and might reduce your overall stress level.

Clearing a TextBox in ASP.NET

I have webpage where there is textbox with some default value. I have to clear that value from the textbox. I have two options:
textbox.text="";
or
textbox.text.remove(0,length);
Which one should I use? Does it make any impact on page performance (there are many textboxes placed on my page)?
The best way to do this is
textbox.text = string.Empty;
Also remember that string type is immutable!
It makes no difference - do what is most readable for you and your colleagues.
Many prefer to use string.Empty.
The performance difference between the two options will be too small to measure, most likely.
TextBox.Text = String.Empty; is a lot more readable. It clearly states what you're trying to do: "set the text property of this text box to an empty string".
I recommend you go with the assignment, as it is both faster, and much more clear.
Presumably, you mean clear the value with javascript when a user clicks int the box? If so, it won't make any difference to performance.
I use jQuery in most pages, so I just hook up this function to clear default values onClick, using the ClientId of the textbox:
$('#ctl00_TextBox').click(function() { $('#ctl00_TextBox').val('');
If you mean clear it in codebehind use this:
yourTextBox.Text = String.Empty;
textbox.text="";
or
foreach (var item in Page.Controls)
{
if (item is TextBox)
{
((TextBox)item).Text = "";
}
}
The impact on performance will be minimal even with hundreds/thousands of calls, however
textbox.text = "";
should in theory be very slightly quicker, since you're just assigning a new value rather than processing the string (as .Remove does)
The best way to do this would be to do
textbox.text = String.Empty;
Update: if you're counting clock-cycles, String.Empty will actually execute faster as well, because it doesn't create a new object, whereas "" will create a new String object.
However, you should really not be too concerned about this, there aren't many ways to set a string to empty that will cause performance issues! You should use whichever is the most readable...

SubSonic RESTHandler Question

I'm playing with the SubSonic RESTHandler for the first time and it's awesome... There is one quirk tho, that I'm curious about.
RESTHandler.cs (line 319):
//if this column is a string, by default do a fuzzy search
if(comp == Comparison.Like || column.IsString)
{
comp = Comparison.Like;
paramValue = String.Concat("%", paramValue, "%");
}
This little blurp of code forces all searches on string columns to wildcard searches by default. This seems counter intutive, since you've provided a nice set of comparisons we can add to a parameter (_is, _notequal, etc...). Is there a reason this was done? The EvalComparison uses "Comparison.Equals" as it's default, so unless a like is explicitly needed the " || column.IsString" looks like it should be removed since it breaks the ability to use different types of comparisons.
This was driving me crazy, since you can't do a "WHERE Field = X" without modifiying code...
Just curious if this is more of a feature than a bug...
Thanks!
Zach
It's because this is a LIKE operation which for a DB usually allows string operations. The feeling at the time was that if you wanted equals you could just use that.
It's been a while since I've touched this code - if you'd be kind enough to open a bug I'll take a look at it.
It does indeed look like a feature. It's based on the idea that, if I am searching for a string in a column without the wildcards, I must match the string exactly or I get no hits. I suspect that this was done to make programming search textboxes easier.

Categories