How to know whether a model is feasible - c#

I am using C# api. Given a gurobi model
GRBModel model = new GRBModel(env);
after populating constraint, giving objective function, and doing
model.Optimize();
is there a way to determine whether the model is feasible?

You need to check the optimization status code after solving the model. In most cases, you simply need to test that the status is OPTIMAL. For an example, see mip2_cs.cs in the examples\c# subdirectory.

Related

Model Binding vs Form Collection, performance, scalability, change, etc.? [duplicate]

I've inherited a code base written in ASP.Net MVC 4. Every post method takes a FormCollection. Aside from annoyance of having to access the values through quoted strings, it also leads to drawbacks such as not being able to use things like ModelState.IsValid, or [AllowHtml] attributes on my ViewModel properties. They actually did create ViewModel classes for each of their views, (though they are pretty much just direct wrappers around the actual Entity Framework Model classes), but they are only used for the GET methods.
Is there anything I'm missing about FormCollection that gives a reason why this may have actually been a good idea? It seems to only have drawbacks. I'd like to go through and "fix" it by using ViewModels instead. This would take a good bit of work because the ViewModels have properties that are interfaces and not concrete classes, which means either writing a custom binder or changing the ViewModels.
But perhaps there's something I'm missing where it makes sense to use FormCollection?
Is there any good reason to use FormCollection instead of ViewModel?
No. I have following issues.
Issue - 1
In case FormCollection is being used...It will be mandatory to Type Cast the Primitive Type Values un-necessarily because while getting the entry of specific Index of the System.Collections.Specialized.NameValueCollection, value being returned is of type String. This situation will not come in case of Strongly Typed View-Models.
Issue - 2
When you submit the form and goes to Post Action Method, and View-Model as Parameter exists in the Action method, you have the provision to send back the Posted Values to you View. Otherwise, write the code again to send back via TempData/ViewData/ViewBag
View-Models are normal classes, created to bind data to-from Views
Issue - 3
We have Data Annotations that can be implemented in View Model or Custom Validations.
ASP.Net MVC simplifies model validatons using Data Annotation. Data Annotations are attributes thyat are applied over properties. We can create custom validation Attribute by inheriting the built-in Validation Attribute class.
Issue - 4
Example you have the following HTML
<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />
Question : How can we access the value of customAttr1 from the above eg from inside the controller
Answer : When a form get posted only the name and value of elements are posted back to the server.
Alternatives : Use a bit of jQuery to get the custom attribute values, and post that along with the form values to action method
Another option is to rather put what you got in your custom attributes in hidden controls
That's the reason, I would always prefer to use View-Models
The only advantage I can think of is if you want to use the automatically generated controller provided when you don't specify a EF model to be strongly typed to. In that case, your Create and Edit actions will use the FormCollection object as it is a reliable, pre-existing artifact of the framework to work with for this purpose. Perhaps the previous developer chose this option while creating his controllers, and stuck with it since Visual Studio must know what it's doing :)
But, in reality, I would never recommend this headstart of a few seconds. It's always better to build out viewmodels, I would recommend looking at the effort to move in that direction if only for maintenance purposes. With model binding and strongly typed views and html helpers, you are much more likely to reduce the number of run-time errors as a result of changing some magic string and not realizing it until your page blows up.
Ok, I see the general consensus here is that it isn't liked. To offer another perspective, I've always liked using the formcollection passed into the controller on POST actions. It offers the use of the TryUpdateModel method from the controller which will map the collection to your strongly typed class. TryUpdateModel also has overloads that allow you to white list the properties of the model that you want to allow to be updated.
if (TryUpdateModel(viewModel, new string[] { "Name" }))
{
//Do something
}
It still allows all the model binding you want, but helps to keep anything other than the "Name" property on my viewmodel from being updated.
You can see more about the TryUpdateModel method here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.108).aspx
There are always workarounds for getting away from a FormCollection lol.. you can have hidden fields bound to your view model variables in the form to your heart's content.
Form collections mostly emerge from the laziness of creating a view model but still end up taking time trying to get figure out how to get the values out of it in your controller :P
I think it was simply created in the very beginning of MVC as an alternative to using strongly typed views when having very simple forms - back in the days when everyone used ViewBag :) ... and once hey had it in there they couldn't just take it out as simple as that.
Maybe you can use it if you are absolutely sure your view will never have more than one form input? Probably still a bad idea though..
I cant find any recent articles talking about any advantages of form collections.. while strongly typed views are everywhere.
Yes. Sometimes, it can be useful. Here's an example:
Let's say we have in our db "date_and_time_field".
In Razor View, we want to use two form fields. The first one "Date" (maybe with jQuery UI Datepicker). The second one "Hour".
In the Controller Action, we compose the "date_and_time_field" by means of Request.Form["Date"] and Request.Form["Hour"].
There are other scenarios where it can be useful:
A cross-table (with checkBoxes in Razor view)
The collection Request.Unvalidated().Form (maybe this is not part of your question: I don't wanna be off-topic)
The default model binder will do almost everything you need it to do. I resorted to the FormCollection once - only to later figure out how to bind arrays of elements into a collection on the ViewModel.
Just go ViewModel. Better all around, for every reason enumerated.
With form collection you will be able to get all the values inside the form. There can be situations where you may need to pass some additional values from the form which may not be part of your view model.
Just take an example of passing 10 hidden values from the form. The form collection makes sense.
The only difficulty that you may face is type casting. All form collection items that you get will be string; you may need to type cast based on your requirement.
Also model state validation is another area where you may face a challenge.
You can always add the form collection properties to your method signatures. They will automatically be populated by form values with corresponding keys.
Well with Forms Collection you will find a quick way to get the values of a form. Otherwise you have to create a class that mimics the Form Fields and people are sometime lazy to create custom classes for less important/rarely used Forms.
No there is no extra benefit (in fact limited) of forms collection over a custom class as action parameters and it should be avoided whenever possible.
Responding to the title question: yes.
There are some situations that FormCollection needs to be used. For instance, suppose a ViewModel that has a property that implements the 1 to N relation (in concrete case, a TimesheetViewModel with ICollection<TimesheetEntryViewModel>), and the Controller has to perform a validation between the time entries to not get a time collision between the end time of an entry and the start time of the following entry. To mark a related entry with a validation error, how can be the line index be retrieved?
Well, with the default model binding, the index value is lost in the Controller logic. Fortunately, FormController stores the index you used in the View and a more specific validation can be done.
There are type of SPA apps where you have no idea about your model (there is no ViewModel at all and views are created dynamically (for short ;))), so FormCollection is your only choice where you implement custom post validation having entire page input values...
If your view has a knowledge about the model then, of course, you can use your concrete ViewModel object. That's easy ;)

Storing viewmodel data in Session creates problems with validation using FluentValidation

I'm currently working on a large project involving Sitecore CMS (7.2). For viewmodel validation we are using FluentValidations. Because of the combination of Sitecore and FluentValidations I seem to be running in some kind of technical deadlock. I sort-of found a solution myself, but I'm not sure whether this is the right approach or not. Here's the problem:
Situation
There is a Sitecore component which contains a HTML form. Via the modelbinder each value of this form is binded to it's corresponding field in the (complex) viewmodel. This is standard .NET MVC approach.
However, some values in the viewmodel are NOT part of the form. For instance, a date at which the mutation will be applied is calculated by the application. The user can only see this date-value as plain text, and thus can not edit it. It's still part of the viewmodel though. To make sure this value is being posted back to the model in code, one would normally use a hidden field. But if I use a hidden field, it means that users are able to spoof that date and because some validations depend on this value, they are able to spoof the entire validity of the form.
Moreover, in the same viewmodel I have a list of complex objects that I can't simply put in a hidden field (or I should serialize it to JSON, which I don't want).
The conclusion is that I need to store this data somewhere else. Somewhere the user can't spoof it, but I'm still able to validate user input with FluentValidations. I therefore decided to put the entire viewmodel in the users Session, and delete it directly after a succesful mutation.
Problem
By using session data I run into problems. Let's first see these steps:
(GET) Viewmodel is created. Calculated date is set and list of complex types is retrieved once from a (slow) webservice.
Entire viewmodel is stored as session data.
Form is shown to the user, who fills the form. Some data is only shown as readonly, like the date and list of complex types.
User submits form, FluentValidations kicks in to validate the data (POST).
That's where I run into problems. The validation done by FluentValidations kicks in before it reaches the POST controller method. That's exactly the way we want it, because that means validation errors are automatically added to the ModelState. However, because of security reasons I don't want to add this data as hidden fields to the cshtml file, which means they are empty at the time FluentValidations is going to validate the form.
This is creating problems because some of the form validations rely on the missing data. What I basically want is to merge the viewmodel that is stored in the session with the viewmodel that was posted to the controller method. But I have to do that before FluentValidations is going to do it's work.
My current solution
Gladly, I learned about FluentValidation's IValidatorInterceptor: an interface that can be used to 'do stuff' before or after the validations process kicks in. I used the BeforeMvcValidation method to do my merging process. The code is as follows:
public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext)
{
if (controllerContext.HttpContext.Session == null)
return validationContext;
var sessionData = controllerContext.HttpContext.Session["some_identifier"];
if (sessionData == null)
return validationContext;
var mergedObjectToValidate = Utils.MergeViewModelData(sessionData, validationContext.InstanceToValidate);
// Unfortunately, we have to do this..
var privateSetterProperty = validationContext.GetType().GetProperty(ValidationContextInstancePropertyName);
if (privateSetterProperty == null)
return validationContext;
privateSetterProperty.SetValue(validationContext, mergedObjectToValidate);
return validationContext;
}
Basically this interceptor method allows me to do my merging-process before validation. So I thought I had the solution here, but as you can see I am using reflection to set a property. That is because the property InstanceToValidate in the ValidationContext object has a private setter. I simply can not set it without using reflection. Which is, obviously, a bit dirty.
It does work exactly as I want though! :) I do not need any hidden fields that can be spoofed (which is horrible for straight-trough-processing) and I can still use FluentValidations exactly as I always did before. Also, the MVC modelbinding-process is left untouched, which I prefer.
The actual question
So the above solution works exactly as you want so what are your questions?! Well, simple:
I'm using reflection to set a private property in a 3rd party library (FluentValidations). The obvious answer is: don't go that way. But in this case it works flawlessly. If the InstanceToValidate-property had a public setter, I wouldn't even be posting this question at all: I would feel like I nailed it. But unfortunately it is private, so are there any real reasons why I shouldn't do this, maybe someone being an expert in FluentValidations behaviour?
Let's say there is a genuine reason why I shouldn't go this way; is there another approach which has the same effect? Can I hook in even earlier, so before FluentValidations kicks in, perhaps some kind of 'hook' just after the MVC model-binding process but before validation kicks in?
Is this entire approach simply wrong and should I tackle it in a completely different way?
Thanks!

When to check and when not to check ModelState.IsValid

I'm using ASP.NET MVC2.
I love how I can annotate my model's fields and check ModelState.IsValid.
The obvious reason to check it is when doing validation, but should you always check it in case new validation rules are applied to the model?
That way you don't forget / need to check whether the controller checks IsValid.
Is there some reason not to do this check in all cases? Maybe just when the controller action has side-effects (DB-writing etc)?
but should you always check it in case new validation rules are
applied to the model?
You should do this check always else you end up persisting models that don't have valid state.
Generally, in asp.net-mvc, models passed to actions are view models, and they contain all and only data needed for action to act. If that data is invalid, theoretically it should be impossible for action to do its job.
ModelState.IsValid ensures that all data needed for action is in good state, ready to be acted on. I do not see reason where you would not want to validate that data.
You should always check if the model is valid immediately before attempting to use the data collected in the model to do something. That's the purpose of validation in the first place.
It looks obvious to mention, but i will give it a shot.
There is NO need to check model state when you are NOT posting your model. The common scenarios are when you are getting your data from service and displaying on a get action.

Where is the most convenient place to validate a property length of a saveable object?

I wonder where is the most convenient place to validate a property length on a persistent object.
Let's say, there is a table called Country in my Db with CountryCode nvarvhar(3).
And I have a mapped object Country wiht property CountryCode which can be saved into Db.
Where should I check if the Country code set by user does not exceed 3 characters:
In the setter of property CountryCode
OR at the time of saving into Db
Can you please advice?
Thanks
I've found that it is easiest to allow properties to be set to any value (of the correct data type anyway) and then validate it before saving it.
I like to use the validation attributes built into .Net. This keeps the logic associated with the property. There is a StringLengthAttribute class that should do the trick for what you are asking for.
The attributes are in the System.ComponentModel.DataAnnotations namespace (you'll need to reference the assembly of the same name).
MVC and EntityFramework have a built in way to validate the data. If you need to perform the logic yourself, here is some code that might help you get started...
var ctx = new ValidationContext(obj, null, null);
Validator.ValidateObject(obj, ctx);
According to code secure recomendations, all checks should be performed as early as possible. Additionally, it's recommended that each party performs the checks by itself without relying on other parties verifications.

Is is a good practice to store propery names in a public constant string?

In order to protect ourself from failure because of any renaming of properties (Let's say you regenerate your poco classes because you have changed some column names in the relevant Db table) is it a good practice to decalre constant strings that keep the property names inside?
public const string StudentCountPropertyName = "StudentCount";
public int StudentCount {get;set;}
For example: Think about a DataBinding; where you type the property name in the DataFieldName attribute explicitly.
Or this is not a good idea and there is a better and still safer way?
It is always a good idea IMHO to move any 'magic strings' to constants.
You could consider using lambda expressions to 'pick' your properties, for example:
GetDataFieldName(studentCollection => studentCollection.Count)
You will have to implement GetDataFieldName yourself, using a bit of reflection. You can look at HtmlHelperExtensions from MVC to see how it can be done. This will be the most safe approach, which gives you compile-time errors when something goes wrong and allows easy property renaming using existing refactoring tools.
From one point of view: if you using this property name multiple times it is good practice. It will help for sure with the refactoring and when you for example change property name you see that you need change this const also.
From another point of view i guess it will be ugly when my class with 10 properties will have 10 additional consts. Another solution if you want avoid consts or explicit name typing can be getting property names through the reflection.
Use such approach or not you should decide yourself.
I think it's a common practice to put this "magical string" or "magical numbers" in some kind of strong typed store.
Something you can consider is to code it in a Aspect Orientied Way.
For example the calls to notifypropertychagned can be realized with an attribute implemented with an aop framework, like PostSharp .
[NotifyChange]
public int Value {get;private set}
This tools also have some downsides but i think there are scenarios where they can save you a lot of work
I do not know if I fully understand your question, but if I understand it right I would have used an attribute for that, an example could be the use of ColumnAttribute in Linq which you use to map a property to a specific column in a database (http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.dbtype.aspx), like in this example:
[Column(Storage="ProductID", DbType="VarChar(150)", CanBeNull=False)]
public string Id { get; set; }
And I would never use DataFieldName, I would DataBind to the strongly typed objects (and of course also make an interface to the class that uses the property above so I easily can change the implementation in the future ;))
I suppose if the names are used in many places then it would be easier just to change them in this one place and use the constant as described in your comment.
However, a change to a database column name and object property name implies a change to your conceptual data model. How often do you think this is going to happen? In the early stages of a project, whilst conceptual modelling and implementation are paralellised across a dev team, this may be quite fluid, but once the initial conceptual modelling is done (whether this in a formalised conscious manner or just organically), it's usually quite unlikely that fundamental things like these are going to change. For this reason I think it's relatively unusual to have do this and the technique will only be productive in edge cases.
Absolutely. It's a good idea.
By the way, I would argue that these kind of things could be better stored in application settings, because you can define such things in an application configuration file later by overriding these settings.
Doing that this way you'll avoid re-compiling if some database, POCO or whatever changes, and as in newer Visual Studio versions like 2010, you can tell it to generate settings with "public" accessibility, you can share strongly-typed settings with any assembly that reference the one containing them.
At the end of the day, I'd change your code with DataBindingSettings.StudentCountPropertyName instead of a constant.
Easy to manage, more re-usable, and readable, as "you configure a data-binding with its settings".
Check this MSDN article to learn more about application settings:
http://msdn.microsoft.com/en-us/library/a65txexh(v=VS.100).aspx

Categories