Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Che Delilas
Nov 23, 2009
FREE TIBET WEED

epalm posted:

I guess I was just looking for some guidance, I'll proceed and report back with my findings.

The more you use EF, the more you will look into something and find that the answer is, "EF can't do that right now" or "This is a bug in EF," usually accompanied by "We have no plans to work on this issue." What fun! :v:

Adbot
ADBOT LOVES YOU

Che Delilas
Nov 23, 2009
FREE TIBET WEED

epalm posted:

Yes, it's a 1-time import. I'm looking into reseeding (which I suppose I'd do in a migration?).

If you're going to import records into a table with an identity column using SET IDENTITY INSERT ON, you're going to want to re-seed, yeah. Because chances are, once you've done that and start inserting records normally, the database is going to auto-generate an Id value that has already been taken by one of the imported records, and the insert will fail with some kind of duplicate-value error (I don't know the specific one right off). Re-seeding to some value greater than the largest existing value will prevent those problems.

Edit:

I do have another question for you though. Is there some reason you need to keep those old IDs intact? Like, is your new database going to be linked (like, linked servers linked) to an already-in-production database? If you're just migrating all the data over to a new self-contained database, there's no reason to keep those existing IDs at all. They're just references so tables can join.

Che Delilas fucked around with this message at 02:51 on Oct 4, 2014

epswing
Nov 4, 2003

Soiled Meat

Che Delilas posted:

I do have another question for you though. Is there some reason you need to keep those old IDs intact? Like, is your new database going to be linked (like, linked servers linked) to an already-in-production database? If you're just migrating all the data over to a new self-contained database, there's no reason to keep those existing IDs at all. They're just references so tables can join.

Good question. What I'm dealing with is 30ish mostly normalized mysql innodb tables, half of which contain on the order of hundreds of thousands of records (plus a mongodb datastore of equivalent size, but that's a separate can of worms). I know that's pretty small considering other systems, but it's not trivially small (for me). Just copying table "rows" directly and without DbContext change tracking seems logical and efficient, where a "reference to another table" is just assigning an int. I just need to make sure I copy the tables in the right order, so the references exist where the database demands them.

Otherwise I would have to copy "objects" and their graphs in some clever way as to not run out of memory, and not overload DbContext change tracking, and I can't think of a nice way to do that without it taking forever. (But then again what do I know.)

RICHUNCLEPENNYBAGS
Dec 21, 2010

Che Delilas posted:

The more you use EF, the more you will look into something and find that the answer is, "EF can't do that right now" or "This is a bug in EF," usually accompanied by "We have no plans to work on this issue." What fun! :v:

The lovely handling of Include with subtypes really cheeses me off but everything else I've eventually found a workaround I was satisfied with for.

epswing
Nov 4, 2003

Soiled Meat

Che Delilas posted:

The more you use <language/framework>, the more you will look into something and find that the answer is, "<language/framework> can't do that right now" or "This is a bug in <language/framework>," usually accompanied by "We have no plans to work on this issue." What fun! :v:

Fixed :v:

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Hah! True enough, though C# is remarkably good about this sort of thing in general, outside of EF. I think the only real headaches I've had with it have been related to Visual Studio's design view for WPF projects, and the particular issues I had have been fixed as far as I can tell. And that wasn't a problem with the language, but the IDE.

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug
Have you tried the Import/Export data feature in SSMS or use SQL Server Integration Services? I'm not sure how much manipulation is required for moving the data from MySQL to SQL Server but either tool should be able to do it.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Why in god's name wouldn't it be mentioned in the documentation of 'IsAjaxRequest' or 'Ajax.BeginForm' that neither of them do anything if the page that the ajax form is rendered on doesn't have access to jquery.unobtrusive-ajax.js? Jesus christ this has been a frustrating 24 hours.

mortarr
Apr 28, 2005

frozen meat at high speed

wwb posted:

I'd add some debug statements to spit out data about the pdf like how many pages it sees. Not familiar with the underlying library but my guess is it does something that makes it behave different running inside IIS versus running in testdriven.net.

It also might be worth hooking it into full-blown IIS on said machine to see if that somehow makes a difference. To do so and get debugging just setup a virtual site pointed to the app and run VS as administrator and connect to the right w3wp.exe process.

Turns out there was a memory issue... not suprisingly holding multiple versions of an A3-sized bitmap in memory only works on machines with heaps of ram. It's a vendor issue, and nothing to do with the setup/config of iis, visual studio, solution/project files or basically anything under my control.

Thanks for the heads up on debugging w3wp.exe though, I think that would have been my next step and I wasn't looking forward to it!

Withnail
Feb 11, 2004
Anyone know what IIS setting (I assume it's IIS) would send a 401 for an httpwebrequest (works fine in IE). The same request works fine to our dev server which also uses ssl and only allows windows authentication.

This was working up until last week, so something changed, but no sysadmin will admit it.


Code looks like this:
code:
            var url = new Uri("https://productionserver);
            var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
            req.AllowAutoRedirect = true;
            req.CookieContainer = cookieContainer;
            req.Credentials = CredentialCache.DefaultCredentials;
            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback
(ValidateServerCertificate);

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
Reposting from last page in case it got missed:
Anyone know the equivalent of {StaticResource PhoneAccentBrush} for Windows 8 Metro apps? I want the theme accent color (so if you're on Windows 8, the same color as the volume bar when you set volume), which I figured out on the phone, but can't find the right value on Desktop.

edit: ^^ maybe http://stackoverflow.com/questions/5572588/webrequest-getresponse-is-throwing-error-401-unauthorized ?

raminasi
Jan 25, 2005

a last drink with no ice
Ok, I've got a collection databound. The collection has changed. I want the bound view to update. My options are:
  • Use an ObservableCollection (hope I didn't need a more specialized collection type internally!)
  • Create a new collection every time something changes (WPF is about clarity!)
  • Get ahold of the actual binding expression and dick around with it (WPF is elegant!)
Is that right? There's actually no way to force it?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
You could manually raise a PropertyChanged event.

Che Delilas
Nov 23, 2009
FREE TIBET WEED
ASP.NET MVC5 Identity problem.

I've been beating my head against the wall trying to understand Identity and how to make it play well with anything beyond the default MVC application. I am at a complete loss on how to proceed.

I have an MVC5 project where users can add Products into a database. Each Product entry must keep track of the user who added that Product in the first place. The default MVC5 project includes an IdentityModel.cs file with ApplicationUser and ApplicationDbContext defined. So okay, we've got a DbContext already, so let's fold the rest of my domain model into it to keep things "simple." My question is, how do I get the Identity-related stuff to play nice with my business entities? (Code and specific error follows).

Product.cs
C# code:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ApplicationUser AddedByUser { get; set; }
}
IdentityModel.cs (Generated by default mvc project with my single addition at the end (DbSet<Product>))
C# code:
public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet<Product> Products { get; set; } //I added this line
}
ProductController Add method
C# code:
[HttpPost]
[Authorize]
public ActionResult Add(Product p)
{
    if (ModelState.IsValid)
    {
	//I got this line from the AccountController generated by the default mvc project
        var usrmgr = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  
        p.AddedByUser = usrmgr.FindById(User.Identity.GetUserId());
        using (var db = new ApplicationDbContext())
        {
            db.Products.Add(p);
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    return View();
}
The error I get when I log in and attempt to add a product is an InvalidOperationException with the message, "An entity object cannot be referenced by multiple instances of IEntityChangeTracker." It's on the db.Products.Add(p); line.

I know, or at least I think I know, that the problem is coming from the fact that there are two conflicting contexts: one from the OwinContext that I need to get my UserManager in order to find the logged in user, and one from the new ApplicationDbContext that I'm using to try and add the Product into the database.

How do I get these things to work together? I've been trying to learn ASP.NET MVC for a little while now, and while I understand the basics of controllers and views and routing, the auth/Identity stuff is so twisty and obfuscated that I can't penetrate it. I certainly don't understand enough about auth to just ditch Identity and roll my own solution; even if I could get something to work I'm sure it would be full of security holes.

Additionally, if someone knows a resource that really explains auth and/or Identity, that would be really helpful in general.

raminasi
Jan 25, 2005

a last drink with no ice

Bognar posted:

You could manually raise a PropertyChanged event.

Nope. I've got binding diagnostics hooked up, and the engine apparently sees the event but concludes that it doesn't need to actually inform the control of a change.

zokie
Feb 13, 2006

Out of many, Sweden

GrumpyDoctor posted:

Ok, I've got a collection databound. The collection has changed. I want the bound view to update. My options are:
  • Use an ObservableCollection (hope I didn't need a more specialized collection type internally!)
  • Create a new collection every time something changes (WPF is about clarity!)
  • Get ahold of the actual binding expression and dick around with it (WPF is elegant!)
Is that right? There's actually no way to force it?

Yes? If you want changes to be shown you have to actually notify things that the changes happened. What are you expecting? How would it work otherwise?

With the risk of sounding snaky, programming is about things happening only because you tell them to. The core of databinding is basically INotifyPropertyChanged and its collection twin.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

GrumpyDoctor posted:

Ok, I've got a collection databound. The collection has changed. I want the bound view to update. My options are:
  • Use an ObservableCollection (hope I didn't need a more specialized collection type internally!)
  • Create a new collection every time something changes (WPF is about clarity!)
  • Get ahold of the actual binding expression and dick around with it (WPF is elegant!)
Is that right? There's actually no way to force it?

If you need a better collection than ObservableCollection<T>, you could make your own, implementing INotifyCollectionChanged. It's like INotifyPropertyChanged but it's for when the collection itself changes (add, remove elements, capacity changes I think) rather than one of the elements' properties changing.

raminasi
Jan 25, 2005

a last drink with no ice

zokie posted:

Yes? If you want changes to be shown you have to actually notify things that the changes happened. What are you expecting? How would it work otherwise?

With the risk of sounding snaky, programming is about things happening only because you tell them to. The core of databinding is basically INotifyPropertyChanged and its collection twin.

My objection is that there actually isn't a way to perform explicit notification here, but, uh, thanks for your help?

Che Delilas posted:

If you need a better collection than ObservableCollection<T>, you could make your own, implementing INotifyCollectionChanged. It's like INotifyPropertyChanged but it's for when the collection itself changes (add, remove elements, capacity changes I think) rather than one of the elements' properties changing.

Yeah, I thought of this too, but it's still a huge pain in the rear end compared to some hypothetical way to say "No, really, this changed, I promise you."

ljw1004
Jan 18, 2005

rum

Knyteguy posted:

Anyone know the equivalent of {StaticResource PhoneAccentBrush} for Windows 8 Metro apps? I want the theme accent color (so if you're on Windows 8, the same color as the volume bar when you set volume), which I figured out on the phone, but can't find the right value on Desktop.

I'm not sure what you're talking about, and I'm not aware of the concept even existing. When I change the volume in the system tray there are no colors. Can you give more examples of its use?

When you go to ControlPanel > AppearanceAndPersonalization > Personalization it shows "color". Is that it?

I notice that dialog boxes &c. in Metro apps appear to use the same color as the background color I chose at startup. Is that it?

fankey
Aug 31, 2001

GrumpyDoctor posted:

Ok, I've got a collection databound. The collection has changed. I want the bound view to update. My options are:
  • Use an ObservableCollection (hope I didn't need a more specialized collection type internally!)
  • Create a new collection every time something changes (WPF is about clarity!)
  • Get ahold of the actual binding expression and dick around with it (WPF is elegant!)
Is that right? There's actually no way to force it?

Unless I'm misunderstanding you can force a refresh via the ListViewCollection
code:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;

namespace UpdateCollection
{
  public partial class MainWindow : Window
  {
    List<string> _Items = new List<string>();
    public IEnumerable<string> Items
    {
      get { return _Items; }
    }
    void AddSome()
    {
      for (int ix = 0; ix < 3; ix++)
      {
        _Items.Add(string.Format("item {0}", _Items.Count + 1));
      }
      ListCollectionView lcv = CollectionViewSource.GetDefaultView(Items) as ListCollectionView;
      if (lcv != null) lcv.Refresh();
    }
    public MainWindow()
    {
      InitializeComponent();
      DataContext = this;
      AddSome();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      AddSome();
    }
  }
}
code:
<Window x:Class="UpdateCollection.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
  <DockPanel LastChildFill="True">
    <Button DockPanel.Dock="Top" Click="Button_Click">Add</Button>
    <ListView ItemsSource="{Binding Items}"/>
  </DockPanel>
</Window>

aBagorn
Aug 26, 2004

Che Delilas posted:

ASP.NET MVC5 Identity problem.

I've been beating my head against the wall trying to understand Identity and how to make it play well with anything beyond the default MVC application. I am at a complete loss on how to proceed.

I have an MVC5 project where users can add Products into a database. Each Product entry must keep track of the user who added that Product in the first place. The default MVC5 project includes an IdentityModel.cs file with ApplicationUser and ApplicationDbContext defined. So okay, we've got a DbContext already, so let's fold the rest of my domain model into it to keep things "simple." My question is, how do I get the Identity-related stuff to play nice with my business entities? (Code and specific error follows).

Product.cs
C# code:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ApplicationUser AddedByUser { get; set; }
}
IdentityModel.cs (Generated by default mvc project with my single addition at the end (DbSet<Product>))
C# code:
public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet<Product> Products { get; set; } //I added this line
}
ProductController Add method
C# code:
[HttpPost]
[Authorize]
public ActionResult Add(Product p)
{
    if (ModelState.IsValid)
    {
	//I got this line from the AccountController generated by the default mvc project
        var usrmgr = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  
        p.AddedByUser = usrmgr.FindById(User.Identity.GetUserId());
        using (var db = new ApplicationDbContext())
        {
            db.Products.Add(p);
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    return View();
}
The error I get when I log in and attempt to add a product is an InvalidOperationException with the message, "An entity object cannot be referenced by multiple instances of IEntityChangeTracker." It's on the db.Products.Add(p); line.

I know, or at least I think I know, that the problem is coming from the fact that there are two conflicting contexts: one from the OwinContext that I need to get my UserManager in order to find the logged in user, and one from the new ApplicationDbContext that I'm using to try and add the Product into the database.

How do I get these things to work together? I've been trying to learn ASP.NET MVC for a little while now, and while I understand the basics of controllers and views and routing, the auth/Identity stuff is so twisty and obfuscated that I can't penetrate it. I certainly don't understand enough about auth to just ditch Identity and roll my own solution; even if I could get something to work I'm sure it would be full of security holes.

Additionally, if someone knows a resource that really explains auth and/or Identity, that would be really helpful in general.

This may not be 100% best practices, but I've never stored an actual user entity for audit tracking. You can just as easily just do this:

C# code:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string AddedByUserId { get; set; }
}
And then in your controller:

C# code:
[HttpPost]
[Authorize]
public ActionResult Add(Product p)
{
    if (ModelState.IsValid)
    {
        p.AddedByUserId = User.Identity.GetUserId();
        using (var db = new ApplicationDbContext())
        {
            db.Products.Add(p);
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    return View();
}
And you will have a Product updated with the Id of the user that updated it. Put a FK constraint on your product table and then when you are querying do a simple join on the Id field to get back the username.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

aBagorn posted:

This may not be 100% best practices, but I've never stored an actual user entity for audit tracking. You can just as easily just do this:

...

And you will have a Product updated with the Id of the user that updated it. Put a FK constraint on your product table and then when you are querying do a simple join on the Id field to get back the username.

I'm using code first and that's actually how it handles the schema creation when you include the full object in your entity. Product table has a User_Id field with a FK constraint on the ApplicationUsers table. I admit I didn't think of just forcing it that way, though; hack though it may be, bypassing the whole mess might be my best bet. Thanks for the idea, I'll have to play with it and see if I can make it work with the more complex full application.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

ljw1004 posted:

I'm not sure what you're talking about, and I'm not aware of the concept even existing. When I change the volume in the system tray there are no colors. Can you give more examples of its use?

When you go to ControlPanel > AppearanceAndPersonalization > Personalization it shows "color". Is that it?

I notice that dialog boxes &c. in Metro apps appear to use the same color as the background color I chose at startup. Is that it?

No not that one. I mean this one (volume color only shows up when adjusting the volume with a laptop/keyboard AFAIK):


That volume bar color changes when you change the accent color here:


I couldn't find that "Personalize" screen so I was having a hard time explaining it. Anyone know how to get that accent color value in a WPF Metro App?

E: so yes it's the value you chose when first installing if you haven't changed it since.
E2: clarity

Knyteguy fucked around with this message at 00:28 on Oct 7, 2014

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction

GrumpyDoctor posted:

Yeah, I thought of this too, but it's still a huge pain in the rear end compared to some hypothetical way to say "No, really, this changed, I promise you."

Heh, the default OC<T> claims another victim. Welcome brother.

Gul Banana
Nov 28, 2003

My current code base contains both "FastObservableCollection<T>" and "SlightlyObservableCollection<T>".
Inadequacies of the original aside, though, there's not much reason you should need a different collection type. This is viewmodel code! Its job is to present stuff to the view, in a format suitable *for* the view. If you want a unique set or lazy stream or keyed dictionary, put it in a model or controller - have the sync from that to the OC<T> BE your "forced" refresh.

ljw1004
Jan 18, 2005

rum

Knyteguy posted:

That volume bar color changes when you change the accent color here:


I see. I asked your question on the internal WinRT mailing list and got back a definitive "no it's not possible for a modern app to retrieve the accent color".

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

ljw1004 posted:

I see. I asked your question on the internal WinRT mailing list and got back a definitive "no it's not possible for a modern app to retrieve the accent color".

OK, well nothing that can be done then. Thanks for the help.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Che Delilas posted:

I'm using code first and that's actually how it handles the schema creation when you include the full object in your entity. Product table has a User_Id field with a FK constraint on the ApplicationUsers table. I admit I didn't think of just forcing it that way, though; hack though it may be, bypassing the whole mess might be my best bet. Thanks for the idea, I'll have to play with it and see if I can make it work with the more complex full application.

The problem is that the user manager has its own DbContext and you are trying to add an item from that context onto the new one that you're creating. Using the Id instead is a good way of doing it, but you need to make sure you still have a foreign key set up. This model should tell EF Code First to make AddedByUserId the foreign key for the AddedByUser relationship.

C# code:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ApplicationUser AddedByUser { get; set; }
    public int AddedByUserId { get; set; }
}

aBagorn
Aug 26, 2004

Bognar posted:

The problem is that the user manager has its own DbContext and you are trying to add an item from that context onto the new one that you're creating. Using the Id instead is a good way of doing it, but you need to make sure you still have a foreign key set up. This model should tell EF Code First to make AddedByUserId the foreign key for the AddedByUser relationship.

C# code:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ApplicationUser AddedByUser { get; set; }
    public int AddedByUserId { get; set; }
}

You also could add a Data Annotation to my solution to force the foreign key relationship.

Either way, what he's saying is why it's not working. The user entity can't exist in both contexts at once.

raminasi
Jan 25, 2005

a last drink with no ice

fankey posted:

Unless I'm misunderstanding you can force a refresh via the ListViewCollection

This did not work, unfortunately.

Gul Banana posted:

My current code base contains both "FastObservableCollection<T>" and "SlightlyObservableCollection<T>".
Inadequacies of the original aside, though, there's not much reason you should need a different collection type. This is viewmodel code! Its job is to present stuff to the view, in a format suitable *for* the view. If you want a unique set or lazy stream or keyed dictionary, put it in a model or controller - have the sync from that to the OC<T> BE your "forced" refresh.

Yeah, I know this is the "right" answer, but the way that WPF is missing certain kinds of duct tape is infuriating sometimes. :(

fankey
Aug 31, 2001

GrumpyDoctor posted:

This did not work, unfortunately.
Did GetDefaultView return null or did Refresh not actually do anything? My code had an unnecessary cast which might fail based on the view. Try this
code:
    void AddSome()
    {
      for (int ix = 0; ix < 3; ix++)
      {
        _Items.Add(string.Format("item {0}", _Items.Count + 1));
      }
      ICollectionView cv = CollectionViewSource.GetDefaultView(Items);
      if (cv!= null) cv.Refresh();
    }

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Bognar posted:

The problem is that the user manager has its own DbContext and you are trying to add an item from that context onto the new one that you're creating.

Yeah, I figured it was something like that.

quote:

Using the Id instead is a good way of doing it, but you need to make sure you still have a foreign key set up. This model should tell EF Code First to make AddedByUserId the foreign key for the AddedByUser relationship.

aBagorn posted:

You also could add a Data Annotation to my solution to force the foreign key relationship.

This is exactly what I ended up doing.

C# code:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string AddedByUserId { get; set; }

    [ForeignKey("AddedByUserId")]
    public virtual ApplicationUser AddedByUser { get; set; }
}
Lets me work with the Id when I'm assigning things, and lazily loads the full ApplicationUser object if I need it for display purposes (very rare in my application). Thanks guys, this portion of the project is working real smooth now - to the point that I'm a bit worried that I missed something, heh.

GrumpyDoctor posted:

Yeah, I know this is the "right" answer, but the way that WPF is missing certain kinds of duct tape is infuriating sometimes. :(

WPF is a bit of an odd duck sometimes. It's like they built parts of it with the goal of eventually adding a few more tools, and then just forgot. RelayCommand is the perfect example - it's so core to getting Command binding to work that Microsoft put out an article with a code snippet that they tell you to just copy and paste into a class for your projects to use. Just loving build it into the framework already!

Also for some reason they don't have a DatePicker control built in because reasons.

Gul Banana
Nov 28, 2003

GrumpyDoctor posted:

This did not work, unfortunately.


Yeah, I know this is the "right" answer, but the way that WPF is missing certain kinds of duct tape is infuriating sometimes. :(

it's definitely something that needs some really core pieces added and an iteration or two of simplification to codify best practices into the easy path.

instead they've spent half a decade rewriting it twice, for the web and then for tablets, modifying the existing bug set each time :/

Gul Banana
Nov 28, 2003

sometimes if i want to be really sad i think about how awesome WPF would be by now if its development had continued after 2008.

Ochowie
Nov 9, 2007

Cross posting from an SO question I started. Is there any way to simulate foreign key checks when unit testing a Repository on top of EF using Moq? I have the following code which should technically fail because one of the relationships isn't present in either the database or the mocked sets on the context. I have the following code which I would expect to fail because the foreign key reference is not in the context but it succeeds adding and verifying that SaveChanges() is called on the DbContext.

code:
var entitySet = new Mock<DbSet<MyEntity>>();
var mockContext = new Mock<MyContext>();
mockContext.Setup(x => x.Set<MyEntity>()).Returns(entitySet.Object);
var myentity = new MyEntity
{
    RefID = "ABCD", //Foreign Key that does not exist in the context
};

var repo = new MyRepo<MyEntity>(mockContext.Object);
repo.Add(myentity);         

//repo.Add()
public void Add(TEntity entity)
{
    DbSet.Add(entity);
    context.SaveChanges();
}
Since repo.Add() is successful even though it fails using a live database I'm not sure how the unit test is useful at all.

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug
How would a fake DbContext know that your relationship should fail? It's just going to let your code call into it, return pre-recorded behavior (Setup/Returns), and to allow you to Verify calls. If you want to test what happens when your code gives a bad relation you can have Moq throw an exception.

What you want is an integration test where you aren't mocking your DbContext but using a MyContext against a real database.

The Art of Unit Testing is a great book that goes over unit testing and touches on integration testing.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
This is a question that I've had for a while, but haven't delved into deeply enough to figure out it. If anyone here has some insight before I do, that would be great.

Does Entity Framework Code First with migrations support interacting with a database if the database has *newer* migrations?

EF rightfully explodes if the database it's talking to doesn't have the latest migration. However, there are situations where I would still want EF to continue to interact with the database even if the database has been updated to newer migrations.

For example, I might have a web site running 5 replicated web servers. I want to add a feature that requires adding a table to the database, and I want to update the web servers without a gap in uptime. Without EF, I can modify the database, and update the web servers one by one. However, with EF and migrations, the web servers with old code might blow up when trying to talk to a newer DB.

Most of the sites I've worked on have had one web server that got updated when the DB updated, and for 15 minutes we just told the users to hold on. I want to break that model, but I'm worried that I can't do it with EF.

EDIT: Okay nevermind, we just tested it with one of our staging sites and it seems to work great.

Bognar fucked around with this message at 22:43 on Oct 7, 2014

RICHUNCLEPENNYBAGS
Dec 21, 2010

Bognar posted:

The problem is that the user manager has its own DbContext and you are trying to add an item from that context onto the new one that you're creating. Using the Id instead is a good way of doing it, but you need to make sure you still have a foreign key set up. This model should tell EF Code First to make AddedByUserId the foreign key for the AddedByUser relationship.

C# code:
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ApplicationUser AddedByUser { get; set; }
    public int AddedByUserId { get; set; }
}

In my opinion "one context per request" is the most sensible way to use EF. Just share the context with the UserManager.

Bognar posted:

This is a question that I've had for a while, but haven't delved into deeply enough to figure out it. If anyone here has some insight before I do, that would be great.

Does Entity Framework Code First with migrations support interacting with a database if the database has *newer* migrations?

EF rightfully explodes if the database it's talking to doesn't have the latest migration. However, there are situations where I would still want EF to continue to interact with the database even if the database has been updated to newer migrations.

For example, I might have a web site running 5 replicated web servers. I want to add a feature that requires adding a table to the database, and I want to update the web servers without a gap in uptime. Without EF, I can modify the database, and update the web servers one by one. However, with EF and migrations, the web servers with old code might blow up when trying to talk to a newer DB.

Most of the sites I've worked on have had one web server that got updated when the DB updated, and for 15 minutes we just told the users to hold on. I want to break that model, but I'm worried that I can't do it with EF.

EDIT: Okay nevermind, we just tested it with one of our staging sites and it seems to work great.

Sure. You can also ask it to ignore missing migrations with one of the options or you could trick it by doing an empty migration.

Ochowie
Nov 9, 2007

gariig posted:

How would a fake DbContext know that your relationship should fail? It's just going to let your code call into it, return pre-recorded behavior (Setup/Returns), and to allow you to Verify calls. If you want to test what happens when your code gives a bad relation you can have Moq throw an exception.

What you want is an integration test where you aren't mocking your DbContext but using a MyContext against a real database.

The Art of Unit Testing is a great book that goes over unit testing and touches on integration testing.

I guess I assumed that if I mocked up the DbSets and passed them to the context that some of the context behaviors would carry over. I guess that that doesn't make a lot of sense. I guess I'm more familiar and comfortable with the integration testing concept over the unit testing one. Thanks for the reading recommendation.

Adbot
ADBOT LOVES YOU

RICHUNCLEPENNYBAGS
Dec 21, 2010

gariig posted:

How would a fake DbContext know that your relationship should fail? It's just going to let your code call into it, return pre-recorded behavior (Setup/Returns), and to allow you to Verify calls. If you want to test what happens when your code gives a bad relation you can have Moq throw an exception.

What you want is an integration test where you aren't mocking your DbContext but using a MyContext against a real database.

The Art of Unit Testing is a great book that goes over unit testing and touches on integration testing.

Do you? Frankly I think a mocked out DbContext is pretty useful in a lot of cases and with the integration test you run into consistency problems.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply