EF in a UserControl can't see the app.config? - c#

I just created a user control.
This control also makes use of my static Entity Framework class to load two comboboxes.
All is well and runs without a problem. Design and runtime are working.
Then when I stop the application all the forms that contain my UserControl don't work any more in design time. I just see two errors:
Error1:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
Error 2:
The variable ccArtikelVelden is either undeclared or was never assigned.
(ccArtikelVelde is my UserControl)
Runtime everything is still working
My static EF Repositoy class:
public class BSManagerData
{
private static BSManagerEntities _entities;
public static BSManagerEntities Entities
{
get
{
if (_entities == null)
_entities = new BSManagerEntities();
return _entities;
}
set
{
_entities = value;
}
}
}
Some logic happening in my UserControl to load the data in the comboboxes:
private void LaadCbx()
{
cbxCategorie.DataSource = (from c in BSManagerData.Entities.Categories
select c).ToList();
cbxCategorie.DisplayMember = "Naam";
cbxCategorie.ValueMember = "Id";
}
private void cbxCategorie_SelectedIndexChanged(object sender, EventArgs e)
{
cbxFabrikant.DataSource = from f in BSManagerData.Entities.Fabrikants
where f.Categorie.Id == ((Categorie)cbxCategorie.SelectedItem).Id
select f;
cbxFabrikant.DisplayMember = "Naam";
cbxFabrikant.ValueMember = "Id";
}
The only way to make my forms work again, design time, is to comment out the EF part in the UserControl (see above) and rebuild.
It's very strange, everything is in the same assembly, same namespace (for the sake of simplicity).
Anyone an idea?

Looks like you're somehow executing database code in design mode. To prevent this, hunt down the control and method causing this, and use:
if (DesignMode)
return
Also, it's a very bad idea to cache the database context statically. It will cause problems with multithreading, and also when you're doing inserts and deletes. The database context is meant to be used for a single "unit of work", is adding 2, and removing 3 other objects and calling SaveChanges once.

I faced the same problem,
In my case , I have added some database codes in user control loading event which were using some libraries, which weren't loaded till runtime.
Hence it is advisable, not to write any database code in user control load event.
Hope , this helps you !

this error show if you call the function "LaadCbx()" on constructor of userControl.
because the initialization on entity framework exist into this function.
the solution is to call this function "LaadCbx()" in the constructor of the parent form.

Related

DevExpress XAF - Test if an object is registred before executing code in ViewController

I'm developing using DevExpress XAF, my problem is a little bit tricky, in short, when I save my class I make changes in other classes based on the data provided, I realized this with a controller that executes code when I close the detail view, the problem is that there is a scenario that does not meet my needs, here is it:
When I open a detail view already existing and that I modify some data, when I close the window, the program displays a window of confirmation ("do you want to register?) when I click on no, normally my view controller will not do anything because I refused to change my class data
Finally here is my question: How to test in my view controller if the object was registered or not before proceeding to the change and execute my code?
When you say register, I think you mean save.
You can use the ObjectSpace.GetObjectsToSave() method to obtain a list of objects which will be saved when ObjectSpace.CommitChanges() is called. You can then determine whether View.CurrentObject is in this list.
Alternatively you could use the ObjectSpace_ObjectChanged event. Something like this.
public class MyViewController : ObjectViewController<DetailView, Contact> {
protected override void OnActivated() {
base.OnActivated();
ObjectSpace.ObjectChanged += ObjectSpace_ObjectChanged;
}
void ObjectSpace_ObjectChanged(object sender, ObjectChangedEventArgs e) {
if (e.Object == View.CurrentObject) {
// execute your business logic
}
}
protected override void OnDeactivated() {
base.OnDeactivated();
ObjectSpace.ObjectChanged -= ObjectSpace_ObjectChanged;
}
}
See here for a Support Center discussion of a similar request.

Nhibernate sessionPerThread

I am creating entities in with multiple thread at the same time.
When i do this in sequence order (with one thread) everything is fine, but when i introduce concurrency there are pretty much always new exception.
i call this method asynchronously:
public void SaveNewData(){
....DO SOME HARD WORK....
var data = new Data
{
LastKnownName = workResult.LastKnownName
MappedProperty = new MappedProperty
{
PropertyName = "SomePropertyName"
}
};
m_repository.Save(data);
}
I already got this exception:
a different object with the same identifier value was already
associated with the session: 3, of
entity:TestConcurrency.MappedProperty
and also this one:
Flushing during cascade is dangerous
and of course my favourite one:
Session is closed!Object name: 'ISession'.
What i think is going on is: Everythread got same session (nhibernateSession) and then it... go wrong cos everything try to send queries with same session.
For nhibernate configuration i use NhibernateIntegration with windsor castle.
m_repository.Save(data) looks like:
public virtual void Save(object instance)
{
using (ISession session = m_sessionManager.OpenSession())
{
Save(instance, session);
}
}
where m_sessionManager is injected in constructor from Castle and it is ISessionManager. Is there any way how to force this ISessionManager to give me SessionPerThread or any other concurrent session handling ?
So i researched and it seems that NHibernateIntengrationFacility doesnt support this transaction management out of the box.
I solved it when i changed to new Castle.NHibernate.Facility which supersede Castle.NHibernateIntegration - please note that this is only beta version currently.
Castle.Nhibernate.Facility supports session-per-transaction management, so it solved my problem completely.

Entity Framework - Effect of MultipleActiveResultSets on Caching

So I have a Class that looks something like the following. There is a thread that does some work using an Entity Framework Code First DbContext.
The problem I'm having is that it seems like m_DB context is caching data even though it should be disposed and recreated for every processing loop.
What I've seen is that some data in a relationship isn't present in the models loaded. If I kill and restart the process suddenly the data is found just like it should.
The only thing I can think of is this app is using the MultipleActiveResultSets=true in the database connection string, but I can't find anything stating clearly that this would cause the behavior I'm seeing.
Any insight would be appreciated.
public class ProcessingService
{
private MyContext m_DB = null
private bool m_Run = true;
private void ThreadLoop()
{
while(m_Run)
{
try
{
if(m_DB == null)
m_DB = new MyContext();
}
catch(Exception ex)
{
//Log Error
}
finally
{
if(m_DB != null)
{
m_DB.Dispose();
m_DB = null;
}
}
}
}
private void ProcessingStepOne()
{
// Do some work with m_DB
}
private void ProcessingStepTwo()
{
// Do some work with m_DB
}
}
Multiple Active Result Sets or MARS is a feature of SQL 2005/2008 and ADO.NET where one connection can be used by multiple active result sets (Just as the name implies). try switching this off on the connection string and observe the behaviour of the app, i am guessing that this could be the likely cause of your problem. read the following MSDN link for more on MARS
MSDN - Multiple Active Result Sets
Edit:
Try:
var results = context.SomeEntitiy.AsNoTracking() where this = that select s;
AsNoTracking() switches off internal change tracking of entities and it should also force Entity Framework to reload entities every time.
Whatever said and done you will require some amount of re-factoring since there's obviously a design flaw in your code.
I hate answering my own question, especially when I don't have a good explanation of why it fixes the problem.
I ended up removing MARS and it did resolve my issue. The best explanation I have is this:
Always read to the end of results for procedural requests regardless of whether they return results or not, and for batches that return multiple results. (http://technet.microsoft.com/en-us/library/ms131686.aspx)
My application doesn't always read through all the results returned, so its my theory that this some how caused data to get cached and reused the new DbContext.

How to avoid a "object reference not set to an instance of an object" exception in XAML code at design time?

I have a problem with a wpf usercontrol which is of my own devising.
The problem is that I get a object reference not set to an instance of an object exception in XAML code at design time, when I implement the usercontrol in my program.
The designer showed me the following information:
at
Microsoft.Expression.Platform.InstanceBuilders.InstanceBuilderOperations.InstantiateType(Type
type, Boolean supportInternal) at
Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.InstantiateTargetType(IInstanceBuilderContext
context, ViewNode viewNode) at
Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.Instantiate(IInstanceBuilderContext
context, ViewNode viewNode) at
Microsoft.Expression.WpfPlatform.InstanceBuilders.FrameworkElementInstanceBuilder.Instantiate(IInstanceBuilderContext
context, ViewNode viewNode) at
Microsoft.Expression.WpfPlatform.InstanceBuilders.UserControlInstanceBuilder.Instantiate(IInstanceBuilderContext
context, ViewNode viewNode) at
Microsoft.Expression.Platform.InstanceBuilders.ViewNodeManager.CreateInstance(IInstanceBuilder
builder, ViewNode viewNode)
but I think these messages are not really helpful...
How can I fix or suppress this exception?
If you have 'Object reference not set to an instance of an object' in XAML, but your application compiles and runs fine, you will usually find out that its cause is something in a constructor that can't be resolved at design time.
You can just click the "Disable project code" button located on the bottom of your designer view and Visual Studio designer will stop trying to construct an instance to provide design time data view.
See here for detailed information and screenshots.
Whatever is happening in your constructor is throwing an exception during design time. I had same problem - I just put a try catch around the problematic code - in my case I was calling ServiceLocator.Current as I am using an IoC container. But there is no container during design time. So I wrapped in a try catch to suppress the error and it worked. Not the best solution... but its a solution.
I tend to use the LicenseManager class in System.ComponentModel to avoid my ViewModels throwing nasty errors at designtime. For example:
public MyViewModel()
{
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
// Do runtime stuff
}
}
Tweaking #BobHorn's example, I got this to work for me:
public class ViewModel
{
public ViewModel()
{
if (!IsInDesignMode)
{
//Constructor code here...
}
}
public bool IsInDesignMode
{
get
{
var prop = DesignerProperties.IsInDesignModeProperty;
return (bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
}
}
Though using his exact suggestion for the constructor
public Main()
{
if (IsInDesignMode) { return; }
//Constructor code here...
}
Did also work for me, I just prefer not short-circuiting my methods with extra return statements. I would have up-voted his answer, don't have the rep yet.
You could do something like this:
using System.ComponentModel;
using System.Windows;
/// <summary>
/// WPF Design Mode helper class.
/// </summary>
public static class DesignMode
{
private static bool? _isInDesignMode;
/// <summary>
/// Gets a value indicating whether the control is in design mode (running in Blend
/// or Visual Studio).
/// </summary>
public static bool IsInDesignMode
{
get
{
if (!_isInDesignMode.HasValue)
{
var prop = DesignerProperties.IsInDesignModeProperty;
_isInDesignMode
= (bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
return _isInDesignMode.Value;
}
}
}
Then, as the first line in the constructor of your view (or view model), you can do something like this:
if (DesignMode.IsInDesignMode) { return; }
That way your code will only run when you're actually running it.
I had the similar problem. You just need to go to Tools> Options> XAML Designer and enable the option
"Run project code in XAML designer".
Finally restart Visual Studio. I hope this will help.
When you work on a WIndow/UserControl in the designer it "runs" the parameterless constructor.
If you have code in there which is reliant on something usually provided by some other piece of code then this often causes a problem.
The designer doesn't run any other code first so dependencies usually provided elsewhere can be missing and cause errors.
Suppressing these is a matter of detecting whether that code is running in the designer or not.
It's often most convenient to just return out the constructor:
public MainWindow()
{
InitializeComponent();
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return;
//code
}
More in detail https://social.technet.microsoft.com/wiki/contents/articles/29874.aspx?Redirected=true
VS 2017 UWP:
if (false == Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
// Anything in here need not be OK at Design time in Visual Studio
}
In you "partial class" of XAML, if you can see " [XamlCompilation(XamlCompilationOptions.Compile)]",
just remove the line, and then try build again.
If someone else comes here, I had inadvertently dragged my MainWindow.xaml file to a sub folder. Dragging it back fixed the problem.
Change the "Build only" option to "Intellisense only" in the error list window
During refactoring the C# namespace changed for certain classes. The xmlns name was also changed accordingly.
In one place however the xmlns was changed where it should not have been. e.g., code like this:
<OldNS:SomeControl ... />
was incorrectly changed to
<NewNS:SomeControl ... />
The control SomeControl therefore did not exist in the namespace indicated by the NewNS mapping.
Instead of flagging this as a specific error, for whatever reason I got the "object reference not set to an instance of an object" exception instead, with no clue as to the source.
Ultimately finding and fixing this mistake cleared the problem.

Custom User Control Not Initialized in Auto-Generated Code

This has happened many times before, but I never bothered to figure out why, and now I am tired of it:
For instance, I derive a class from RichTextBox or Panel, I rebuild my project to have the class added to the VS designer toolbox, and then I drag & drop the custom user control to a Form. Everything works fine, and I can run my project...
The problem comes when I edit properties of the Form or the custom user control through the designer. Sometimes, the designer removes the initialization line from its code-behind, causing an exception in the designer and the executable because the control remains uninitialized.
In other words, the following line is removed from say, Form1.Designer.cs:
this.customRichTextBox1=new CustomRichTextBox();
No other line is removed from the code-behind, so the attributes of the custom control are still set, although the variable stays uninitialized.
My solution has always been to manually initialize my user control in the designer code-behind, but the designer eventually removes it again.
I believe that this does not happen when I build a Custom UserControl through the designer (but I am not completely sure of this). It only happens when I define something like the following manually:
class CustomRichTextBox:RichTextBox{}
This is so annoying. What am I doing wrong?
As #Cody requested, here are the steps to reproduce the problem. I am using VS2010, but I've had this problem since 2005, I think.
Step 1. Create new Windows Forms Application, any Framework
Step 2. Add the following class below your main Form class: (It just happens that this is the control that is causing me this problem this time.)
class CustomRichTextBox : RichTextBox
{
Timer tt = new Timer();
internal CustomRichTextBox()
{
tt.Tick += new EventHandler(tt_Tick);
tt.Interval = 200;
}
protected override void OnTextChanged(EventArgs e)
{
tt.Stop();
tt.Start();
}
void tt_Tick(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Hello world!");
}
}
Step 3. Press F6 to rebuild.
Step 4. Add the CustomRichTextBox control to your Form by dragging and dropping from the Toolbox.
Step 5. If you wish, you may press F5 to test the application, but it should work. Close the running application.
Step 6. Press F6 to rebuild, and at this point, the designer should crash with the following message: "The variable 'customRichTextBox1' is either undeclared or was never assigned." (In one case, the whole VS completely crashed, but the error is usually contained within the designer.)
Step 7. To correct the issue, go into the code-behind and initialize the variable, but next time you rebuild, the initialization line will be gone.
Thanks to everyone who tried answering my question and who posted comments that helped me diagnose and solve the problem.
The problem occurs when using an "internal" keyword with the control's constructor. Changing it to "public" fixes the problem. The reason for this behavior might be that the Designer's own classes cannot see the constructor because they are not within the namespace of my class unless it is marked public. This all makes sense, and I will use the public keyword from now on.
The class does not need to be in its own individual file or be the first declared class in the file as other answers suggested.
The following class works well because the constructor's keyword was changed to public.
class CustomRichTextBox : RichTextBox
{
Timer tt = new Timer();
public CustomRichTextBox()
{
tt.Tick += new EventHandler(tt_Tick);
tt.Interval = 200;
}
protected override void OnTextChanged(EventArgs e)
{
tt.Stop();
tt.Start();
}
void tt_Tick(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Hello world!");
}
}
Is your build set to Debug or it is Release?
I suppose that it is release as I think compiler optimizes the code and remove designer generated line.
Have you tried putting the control code in its own file? I've had problems even with the form designer in the past when the designer code was not int he first class in the file.
I had a similar problem that this posted helped me solve. I have a CustomControl that extends ComboBox, that class contained an internal private class YearItem. I've tried to highlight only the code needed to understand the problem and the solution.
public class YearsCbo : ComboBox //Inherits ComboBox
{
public YearsCbo() {
fill();
}
private void fill() { // <<<=== THIS METHOD ADDED ITEMS TO THE COMBOBOX
for(int idx = 0; idx < 25; idx++) {
this.Items.Add(new YearItem());
}
}
// Other code not shown
private class YearItem {} // <<<=== The VS designer can't access this class and yet
// it generated code to try to do so. That code then fails to compile.
// The compiler error rightfully says it is unable to access
// the private class YearItem
}
I could drag/drop that control YearsCbo onto a form and it worked correctly, but after I returned and edited the form the VS designer generated code that would not compile. The offending code something like this:
Dim YearItem1 As my.ns.YearsCbo.YearItem = New my.ns.YearsCbo.YearItem()
Dim YearItem2 As my.ns.YearsCbo.YearItem = New my.ns.YearsCbo.YearItem()
// This was repeated 25 times because in my constructor I created 25 of these
Me.YearsCbo1.Items.AddRange(New Object() {YearItem1, 2, 3, ..., YearItem25 });
Notice that the designer generated code which tried to access the private class. It didn't need to do that but for some reason it did.
Through trial and error, and this post: How to tell if .NET code is being run by Visual Studio designer came up with a solution:
I added a property to tell if I am running in the designer.
public bool HostedDesignMode
{
get
{
if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
return true;
else
return false;
}
}
I also changed the constructor so that it doesn't call fill() so when the designer runs, there are no items in the ComboBox so the designer doesn't feel the need to manually create those items.
The "fixed" code is shown below:
public class YearsCbo : ComboBox //Inherits ComboBox
{
public YearsCbo() {
if ( ! HostedDesignMode ) {
fill();
}
}
private class YearItem {} // <<<=== Now the VS Designer does not try to access this
}
This code was written using VS2012 Premium on Win7x64 OS (in case it matters).

Categories

Resources