Implementing linqtosql partial DataContext class - how to inspect before/after values - linq-to-sql

I'm trying to extend the linqtosql classes generated by the VS designer and need to determine if the value of a specific field has changed. Is there a way for me to access the before and after values for a field in the DataContext Update method for a table/entity?
Here's my code:
public partial class DataClassesDataContext
{
partial void UpdateActivity(Activity instance)
{
this.ExecuteDynamicUpdate(instance);
//need to compare before and after values to determine if instance.AssignedTo value has changed and take action if it has
}
}
I'm also open to adding a property to the Activity entity class to signal whether the value has changed but I can't figure out how to tell if the value has changed there either. I can't just use the OnAssignedToChanged method of the Activity class because it fires whenever the property value is set, not necessarily changed. I'm using the ListView and LINQDataSource control for updating so it gets set no matter what.
I also thought I might be able to use the OnAssignedToChanging method but the Activity instance does not seem to have current values at that point. The following code does not work as this.AssignedTo is always null.
partial void OnAssignedToChanging(int? value)
{
if (value != this.AssignedTo)
{
_reassigned = true;
}
}

You should be able to do this:
public partial class DataClassesDataContext
{
partial void UpdateActivity(Activity instance)
{
Activity originalActivity = Activities.GetOriginalEntityState(instance);
if (instance.Property != originalActivity.Property)
{
// Do stuff
}
this.ExecuteDynamicUpdate(instance);
//need to compare before and after values to determine if instance.AssignedTo value has changed and take action if it has
}
}
Another alternative:
public partial class DataClassesDataContext
{
partial void UpdateActivity(Activity instance)
{
ModifiedMemberInfo[] changes = Activities.GetModifiedMembers(instance);
foreach (var change in changes)
{
Console.WriteLine("Member: {0}, Orig: {1}, New: {2}", change.Member, change.OriginalValue, change.CurrentValue);
}
this.ExecuteDynamicUpdate(instance);
//need to compare before and after values to determine if instance.AssignedTo value has changed and take action if it has
}
}
I just checked into your other option (OnAssignedToChanging(int? value)), and it seems to work fine for me. Are you sure the initial value wasn't actually null? I tested it with a new object as well as one pulled from a database and it appears to work correctly.

Related

Use AdditionalFields to compare to field in a different class

Introduction
In MVC Core I have a base ViewModel and two ViewModels included in the base model as properties, like so:
public class BaseViewModel
{
public FirstViewModel First { get; set; }
public SecondViewModel Second { get; set; }
}
In FirstViewModel I added a custom validation attribute on one of the properties, inheriting from RemoteAttribute. My goal is to use this attribute comparing the value to a property in SecondViewModel. I've set this up using the AdditionalFields property of the RemoteAttribute.
I think my problem lies in the way the HTML attributes are added to the control in the razor view:
data-val-remote-additionalfields="*.PropOfModelFirst,*.PropOfModelSecond"
When the clientside validation is calling the controller action, the *. is replaced by the framework by First., which is wrong, because the second value is not part of the First-class.
I tried prepending the classname to the second property, resulting in
data-val-remote-additionalfields="*.PropOfModelFirst,*.Second.PropOfModelSecond"
but as can be expected this is changed to First.Second.PropOfModelSecond.
Question
Can the AdditionalFields property be used to compare against values from another ViewModel?
You cannot use AdditionalFields to compare against values from another ViewModel. The reason is that the rules are added to jquery.validate.js by the jquery.validate.unobtrusive.js plugin (which reads the data-val-* attributes generated by the HtmlHelper methods). Specifically it is the adapters.add("remote", ["url", "type", "additionalfields"], function (options) { method that is pre-pending First to the property names.
One option would be to use a single 'flat' view model containing all properties.
If that is not desirable, then you can just write your own ajax code to call your server method that performs the validation. This actually has some added performance benefits as well. By default, after initial validation triggered by the .blur() event, validation is performed on every .keyup() event, meaning that you are potentially making a lot of ajax and database calls if the user initially entered an invalid value.
Remove the [Remote] attribute, and add the following script (I'll assume the properties are First.ABC and Second.XYZ)
$('#First_ABC').change(function() {
var url = '#Url.Action(...)'; // add your action name
var input = $(this);
var message = $('[data-valmsg-for="First.ABC"]'); // or give the element and id attribute
$.post(url, { abc: input.val(), xyz: $('#Second_XYZ').val() }, function(response) {
var isValid = response === true || response === "true";
if (isValid) {
input.addClass('valid').removeClass('input-validation-error');
message.empty().addClass('field-validation-valid').removeClass('field-validation-error');
} else {
input.addClass('input-validation-error').removeClass('valid');
message.text(response).addClass('field-validation-error').removeClass('field-validation-valid');
}
})
});
where the controller method would be
[HttpPost]
public ActionResult Validate(string abc, string xyz)
{
bool isValid = .... // code to validate
if (isValid)
{
return Json(true, JsonRequestBehaviour.AllowGet);
}
else
{
return Json("your error message", JsonRequestBehaviour.AllowGet)
}
}

PowerMock: mock out private static final variable, a concrete example

what is the absolute minimal mocking that must be done to pass this test?
code:
class PrivateStaticFinal {
private static final Integer variable = 0;
public static Integer method() { return variable + 1; }
}
test:
#RunWith(PowerMockRunner.class)
#PrepareForTest(PrivateStaticFinal.class)
class PrivateStaticFinalTest {
#Test
public void testMethod() {
//TODO PrivateStaticFinal.variable = 100
assertEquals(PrivateStaticFinal.method(), 101);
}
}
related: Mock private static final variables in the testing class (no clear answer)
Disclaimer: After a lot of hunting around on various threads I have found an answer. It can be done, but the general concensus is that it is not very safe but seeing as how you are doing this ONLY IN UNIT TESTS, I think you accept those risks :)
The answer is not Mocking, since most Mocking does not allow you to hack into a final. The answer is a little more "hacky", where you are actually modifying the private field when Java is calling is core java.lang.reflect.Field and java.lang.reflect.Modifier classes (reflection). Looking at this answer I was able to piece together the rest of your test, without the need for mocking that solves your problem.
The problem with that answer is I was running into NoSuchFieldException when trying to modify the variable. The help for that lay in another post on how to access a field that was private and not public.
Reflection/Field Manipulation Explained:
Since Mocking cannot handle final, instead what we end up doing is hacking into the root of the field itself. When we use the Field manipulations (reflection), we are looking for the specific variable inside of a class/object. Once Java finds it we get the "modifiers" of it, which tell the variable what restrictions/rules it has like final, static, private, public, etc. We find the right variable, and then tell the code that it is accessible which allows us to change these modifiers. Once we have changed the "access" at the root to allow us to manipulate it, we are toggling off the "final" part of it. We then can change the value and set it to whatever we need.
To put it simply, we are modifying the variable to allow us to change its properties, removing the propety for final, and then changing the value since it is no longer final. For more info on this, check out the post where the idea came from.
So step by step we pass in the variable we want to manipulate and...
// Mark the field as public so we can toy with it
field.setAccessible(true);
// Get the Modifiers for the Fields
Field modifiersField = Field.class.getDeclaredField("modifiers");
// Allow us to change the modifiers
modifiersField.setAccessible(true);
// Remove final modifier from field by blanking out the bit that says "FINAL" in the Modifiers
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
// Set new value
field.set(null, newValue);
Combining this all into a new SUPER ANSWER you get.
#RunWith(PowerMockRunner.class)
#PrepareForTest()
class PrivateStaticFinalTest {
#Test
public void testMethod(){
try {
setFinalStatic(PrivateStaticFinal.class.getDeclaredField("variable"), Integer.valueOf(100));
}
catch (SecurityException e) {fail();}
catch (NoSuchFieldException e) {fail();}
catch (Exception e) {fail();}
assertEquals(PrivateStaticFinal.method(), Integer.valueOf(101));
}
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
}
Update
The above solution will work only for those constants which is initialized in static block.When declaring and initializing the constant at the same time, it can happen that the compiler inlines it, at which point any change to the original value is ignored.

Entity Framework Code First Update Does Not Update Foreign Key

I'm using EF 4.1 Code First. I have an entity defined with a property like this:
public class Publication
{
// other stuff
public virtual MailoutTemplate Template { get; set; }
}
I've configured this foreign key using fluent style like so:
modelBuilder.Entity<Publication>()
.HasOptional(p => p.Template)
.WithMany()
.Map(p => p.MapKey("MailoutTemplateID"));
I have an MVC form handler with some code in it that looks like this:
public void Handle(PublicationEditViewModel publicationEditViewModel)
{
Publication publication = Mapper.Map<PublicationEditViewModel, Publication>(publicationEditViewModel);
publication.Template = _mailoutTemplateRepository.Get(publicationEditViewModel.Template.Id);
if (publication.Id == 0)
{
_publicationRepository.Add(publication);
}
else
{
_publicationRepository.Update(publication);
}
_unitOfWork.Commit();
}
In this case, we're updating an existing Publication entity, so we're going through the else path. When the _unitOfWork.Commit() fires, an UPDATE is sent to the database that I can see in SQL Profiler and Intellitrace, but it does NOT include the MailoutTemplateID in the update.
What's the trick to get it to actually update the Template?
Repository Code:
public virtual void Update(TEntity entity)
{
_dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual TEntity Get(int id)
{
return _dbSet.Find(id);
}
UnitOfWork Code:
public void Commit()
{
_dbContext.SaveChanges();
}
depends on your repository code. :) If you were setting publication.Template while Publication was being tracked by the context, I would expect it to work. When you are disconnected and then attach (with the scenario that you have a navigation property but no explicit FK property) I'm guessing the context just doesn't have enough info to work out the details when SaveChanges is called. I'd do some experiments. 1) do an integration test where you query the pub and keep it attached to the context, then add the template, then save. 2) stick a MailOutTemplateId property on the Publicaction class and see if it works. Not suggesting #2 as a solution, just as a way of groking the behavior. I"m tempted to do this experiment, but got some other work I need to do. ;)
I found a way to make it work. The reason why I didn't initially want to have to do a Get() (aside from the extra DB hit) was that then I couldn't do this bit of AutoMapper magic to get the values:
Publication publication = Mapper.Map<PublicationEditViewModel, Publication>(publicationEditViewModel);
However, I found another way to do the same thing that doesn't use a return value, so I updated my method like so and this works:
public void Handle(PublicationEditViewModel publicationEditViewModel)
{
Publication publication = _publicationRepository.Get(publicationEditViewModel.Id);
_mappingEngine.Map(publicationEditViewModel, publication);
// publication = Mapper.Map<PublicationEditViewModel, Publication>(publicationEditViewModel);
publication.Template = _mailoutTemplateRepository.Get(publicationEditViewModel.Template.Id);
if (publication.Id == 0)
{
_publicationRepository.Add(publication);
}
else
{
_publicationRepository.Update(publication);
}
_unitOfWork.Commit();
}
I'm injecting an IMappingEngine now into the class, and have wired it up via StructureMap like so:
For<IMappingEngine>().Use(() => Mapper.Engine);
For more on this, check out Jimmy's AutoMapper and IOC post.

ASP.NET MVC2 UpdateModel not updating a public property included in whitelist

I have a class Foo with a field UpdateMe of type Confirmation as described below..
public class Foo
{
public Confirmation UpdateMe{get;set;}
public int BarInt{get;set}
}
public enum Confirmation
{
N = 0,
Y = 1
}
I have a whitelist that has UpdateMe, and runs the following way...
[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Update(Foo foo)
{
if(ModelState.IsValid)
{
//this is the Foo as it exists in the backend..using Linq2Sql read/record behavior
Foo existingFoo = _Service.GetFoo();
string[] whitelist = { "UpdateMe" };
UpdateModel(existingFoo, whitelist);
//do persistence stuff down here...
}
}
the model is bound just fine, the incoming Foo has whatever UpdateMe value I set, however the UpdateModel procedure is not updating the property.
This has been ridiculously simplified, but rest assured the UpdateModel is working for other properties coming through the action.
Any idea why this particular public property is not updating?
Ok, heres the scoop.
The issue is that the field was mapped to a checkbox. When not writing the checkbox using an HtmlHelper it was not propagating into the ModelState, and therefore not being included in the UpdateModel.
When I switched to using an HtmlHelper, the ModelState was then including the checkbox value regardless of being selected(desired)...however this brought back the ugliness of mapping an enum type to a checkbox.

Updating database row from model

I'm haing a few problems updating a row in my database using Linq2Sql.
Inside of my model I have two methods for updating and saving from my controller, which in turn receives an updated model from my view.
My model methods like like:
public void Update(Activity activity)
{
_db.Activities.InsertOnSubmit(activity);
}
public void Save()
{
_db.SubmitChanges();
}
and the code in my Controller likes like:
[HttpPost]
public ActionResult Edit(Activity activity)
{
if (ModelState.IsValid)
{
UpdateModel<Activity>(activity);
_activitiesModel.Update(activity);
_activitiesModel.Save();
}
return View(activity);
}
The problem I'm having is that this code inserts a new entry into the database, even though the model item i'm inserting-on-submit contains a primary key field.
I've also tried re-attaching the model object back to the data source but this throws an error because the item already exists.
Any pointers in the right direction will be greatly appreciated.
UPDATE:
I'm using dependancy injection to instantiate my datacontext object as follows:
IMyDataContext _db;
public ActivitiesModel(IMyDataContext db)
{
_db = db;
}
There should be an insert in case of the InsertOnSubmit method usage, this is an expected behaviour.
We recommend the Attach() method usage in your Update() method implementation. In case you have IsVersion column in the entity then everything is simple, in the other case you will have to pass the original values also to the Attach call. More information is available here in MSDN.
I fixed this issue by re-obtaining and updating my object in the Update method.
Instead of trying to re-attach or get the data context to realise it was the same object that belonged to it before I basically did as follows:
[HttpPost]
public ActionResult Edit(Activity activity)
{
Activity myActivity = activitiesModel.getActivityById(activity.id);
myActivity.name = activity.name;
myActivity.date = activity.date;
_dbContext.SubmitChanges();
return View(activity);
}
This isn't my exact code and to be more precise, I created another partial class to my datacontext and stored my update code in there.