Search Results

Search found 4034 results on 162 pages for 'ioc container'.

Page 3/162 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • WPF TreeView MouseDown

    - by imekon
    I've got something like this in a TreeView: <DataTemplate x:Key="myTemplate"> <StackPanel MouseDown="OnItemMouseDown"> ... </StackPanel> </DataTemplate> Using this I get the mouse down events if I click on items in the stack panel. However... there seems to be another item behind the stack panel that is the TreeViewItem - it's very hard to hit, but not impossible, and that's when the problems start to occur. I had a go at handling PreviewMouseDown on TreeViewItem, however that seems to require e.Handled = false otherwise standard tree view behaviour stops working. Ok, Here's the source code... MainWindow.xaml <Window x:Class="WPFMultiSelectTree.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFMultiSelectTree" Title="Multiple Selection Tree" Height="300" Width="300"> <Window.Resources> <!-- Declare the classes that convert bool to Visibility --> <local:VisibilityConverter x:Key="visibilityConverter"/> <local:VisibilityInverter x:Key="visibilityInverter"/> <!-- Set the style for any tree view item --> <Style TargetType="TreeViewItem"> <Style.Triggers> <DataTrigger Binding="{Binding Selected}" Value="True"> <Setter Property="Background" Value="DarkBlue"/> <Setter Property="Foreground" Value="White"/> </DataTrigger> </Style.Triggers> <EventSetter Event="PreviewMouseDown" Handler="OnTreePreviewMouseDown"/> </Style> <!-- Declare a hierarchical data template for the tree view items --> <HierarchicalDataTemplate x:Key="RecursiveTemplate" ItemsSource="{Binding Children}"> <StackPanel Margin="2" Orientation="Horizontal" MouseDown="OnTreeMouseDown"> <Ellipse Width="12" Height="12" Fill="Green"/> <TextBlock Margin="2" Text="{Binding Name}" Visibility="{Binding Editing, Converter={StaticResource visibilityInverter}}"/> <TextBox Margin="2" Text="{Binding Name}" KeyDown="OnTextBoxKeyDown" IsVisibleChanged="OnTextBoxIsVisibleChanged" Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"/> <TextBlock Margin="2" Text="{Binding Index, StringFormat=({0})}"/> </StackPanel> </HierarchicalDataTemplate> <!-- Declare a simple template for a list box --> <DataTemplate x:Key="ListTemplate"> <TextBlock Text="{Binding Name}"/> </DataTemplate> </Window.Resources> <Grid> <!-- Declare the rows in this grid --> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <!-- The first header --> <TextBlock Grid.Row="0" Margin="5" Background="PowderBlue">Multiple selection tree view</TextBlock> <!-- The tree view --> <TreeView Name="m_tree" Margin="2" Grid.Row="1" ItemsSource="{Binding Children}" ItemTemplate="{StaticResource RecursiveTemplate}"/> <!-- The second header --> <TextBlock Grid.Row="2" Margin="5" Background="PowderBlue">The currently selected items in the tree</TextBlock> <!-- The list box --> <ListBox Name="m_list" Margin="2" Grid.Row="3" ItemsSource="{Binding .}" ItemTemplate="{StaticResource ListTemplate}"/> </Grid> </Window> MainWindow.xaml.cs /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Container m_root; private Container m_first; private ObservableCollection<Container> m_selection; private string m_current; /// <summary> /// Constructor /// </summary> public MainWindow() { InitializeComponent(); m_selection = new ObservableCollection<Container>(); m_root = new Container("root"); for (int parents = 0; parents < 50; parents++) { Container parent = new Container(String.Format("parent{0}", parents + 1)); for (int children = 0; children < 1000; children++) { parent.Add(new Container(String.Format("child{0}", children + 1))); } m_root.Add(parent); } m_tree.DataContext = m_root; m_list.DataContext = m_selection; m_first = null; } /// <summary> /// Has the shift key been pressed? /// </summary> private bool ShiftPressed { get { return Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift); } } /// <summary> /// Has the control key been pressed? /// </summary> private bool CtrlPressed { get { return Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); } } /// <summary> /// Clear down the selection list /// </summary> private void DeselectAndClear() { foreach(Container container in m_selection) { container.Selected = false; } m_selection.Clear(); } /// <summary> /// Add the container to the list (if not already present), /// mark as selected /// </summary> /// <param name="container"></param> private void AddToSelection(Container container) { if (container == null) { return; } foreach (Container child in m_selection) { if (child == container) { return; } } container.Selected = true; m_selection.Add(container); } /// <summary> /// Remove container from list, mark as not selected /// </summary> /// <param name="container"></param> private void RemoveFromSelection(Container container) { m_selection.Remove(container); container.Selected = false; } /// <summary> /// Process single click on a tree item /// /// Normally just select an item /// /// SHIFT-Click extends selection /// CTRL-Click toggles a selection /// </summary> /// <param name="sender"></param> private void OnTreeSingleClick(object sender) { FrameworkElement element = sender as FrameworkElement; if (element != null) { Container container = element.DataContext as Container; if (container != null) { if (CtrlPressed) { if (container.Selected) { RemoveFromSelection(container); } else { AddToSelection(container); } } else if (ShiftPressed) { if (container.Parent == m_first.Parent) { if (container.Index < m_first.Index) { Container item = container; for (int i = container.Index; i < m_first.Index; i++) { AddToSelection(item); item = item.Next; if (item == null) { break; } } } else if (container.Index > m_first.Index) { Container item = m_first; for (int i = m_first.Index; i <= container.Index; i++) { AddToSelection(item); item = item.Next; if (item == null) { break; } } } } } else { DeselectAndClear(); m_first = container; AddToSelection(container); } } } } /// <summary> /// Process double click on tree item /// </summary> /// <param name="sender"></param> private void OnTreeDoubleClick(object sender) { FrameworkElement element = sender as FrameworkElement; if (element != null) { Container container = element.DataContext as Container; if (container != null) { container.Editing = true; m_current = container.Name; } } } /// <summary> /// Clicked on the stack panel in the tree view /// /// Double left click: /// /// Switch to editing mode (flips visibility of textblock and textbox) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTreeMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("StackPanel mouse down"); switch(e.ChangedButton) { case MouseButton.Left: switch (e.ClickCount) { case 2: OnTreeDoubleClick(sender); e.Handled = true; break; } break; } } /// <summary> /// Clicked on tree view item in tree /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTreePreviewMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("TreeViewItem preview mouse down"); switch (e.ChangedButton) { case MouseButton.Left: switch (e.ClickCount) { case 1: { // We've had a single click on a tree view item // Unfortunately this is the WHOLE tree item, including the +/- // symbol to the left. The tree doesn't do a selection, so we // have to filter this out... MouseDevice device = e.Device as MouseDevice; Debug.WriteLine(String.Format("Tree item clicked on: {0}", device.DirectlyOver.GetType().ToString())); // This is bad. The whole point of WPF is for the code // not to know what the UI has - yet here we are testing for // it as a workaround. Sigh... if (device.DirectlyOver.GetType() != typeof(Path)) { OnTreeSingleClick(sender); } // Cannot say handled - if we do it stops the tree working! //e.Handled = true; } break; } break; } } /// <summary> /// Key press in text box /// /// Return key finishes editing /// Escape key finishes editing, restores original value (this doesn't work!) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTextBoxKeyDown(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Return: { TextBox box = sender as TextBox; if (box != null) { Container container = box.DataContext as Container; if (container != null) { container.Editing = false; e.Handled = true; } } } break; case Key.Escape: { TextBox box = sender as TextBox; if (box != null) { Container container = box.DataContext as Container; if (container != null) { container.Editing = false; container.Name = m_current; e.Handled = true; } } } break; } } /// <summary> /// When text box becomes visible, grab focus and select all text in it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTextBoxIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { bool visible = (bool)e.NewValue; if (visible) { TextBox box = sender as TextBox; if (box != null) { box.Focus(); box.SelectAll(); } } } } Here's the Container class public class Container : INotifyPropertyChanged { private string m_name; private ObservableCollection<Container> m_children; private Container m_parent; private bool m_selected; private bool m_editing; /// <summary> /// Constructor /// </summary> /// <param name="name">name of object</param> public Container(string name) { m_name = name; m_children = new ObservableCollection<Container>(); m_parent = null; m_selected = false; m_editing = false; } /// <summary> /// Name of object /// </summary> public string Name { get { return m_name; } set { if (m_name != value) { m_name = value; OnPropertyChanged("Name"); } } } /// <summary> /// Index of object in parent's children /// /// If there's no parent, the index is -1 /// </summary> public int Index { get { if (m_parent != null) { return m_parent.Children.IndexOf(this); } return -1; } } /// <summary> /// Get the next item, assuming this is parented /// /// Returns null if end of list reached, or no parent /// </summary> public Container Next { get { if (m_parent != null) { int index = Index + 1; if (index < m_parent.Children.Count) { return m_parent.Children[index]; } } return null; } } /// <summary> /// List of children /// </summary> public ObservableCollection<Container> Children { get { return m_children; } } /// <summary> /// Selected status /// </summary> public bool Selected { get { return m_selected; } set { if (m_selected != value) { m_selected = value; OnPropertyChanged("Selected"); } } } /// <summary> /// Editing status /// </summary> public bool Editing { get { return m_editing; } set { if (m_editing != value) { m_editing = value; OnPropertyChanged("Editing"); } } } /// <summary> /// Parent of this object /// </summary> public Container Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// WPF Property Changed event /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Handler to inform WPF that a property has changed /// </summary> /// <param name="name"></param> private void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } /// <summary> /// Add a child to this container /// </summary> /// <param name="child"></param> public void Add(Container child) { m_children.Add(child); child.m_parent = this; } /// <summary> /// Remove a child from this container /// </summary> /// <param name="child"></param> public void Remove(Container child) { m_children.Remove(child); child.m_parent = null; } } The two classes VisibilityConverter and VisibilityInverter are implementations of IValueConverter that translates bool to Visibility. They make sure the TextBlock is displayed when not editing, and the TextBox is displayed when editing.

    Read the article

  • IoC container configuration

    - by nivlam
    How should the configuration for an IoC container be organized? I know that registering by code should be placed at the highest level in an application, but what if an application had hundreds of dependencies that need to be registered? Same with XML configurations. I know that you can split up the XML configurations into multiple files, but that would seem like it would become a maintenance hassle if someone had to dig through multiple XML files. Are there any best practices for organizing the registration of dependencies? From all the videos and tutorials that I've seen, the code used in the demo were simple enough to place in a single location. I have yet to come across a sample application that utilizes a large number of dependencies.

    Read the article

  • IoC from start to finish

    - by Dave
    I'm quite sure that IoC is the way to go for my application. There are a ton of articles and even questions here on SO that discuss the different containers. I've read several blogs today with partial examples. I am personally leaning towards starting with the CommonServiceLocator and Unity as two way to solve the same problem -- I just need a bunch of assemblies to get data from a database, which I assume is what needs to be injected everywhere. I've yet to find any sites that really take a problem from beginning to end, with concrete code examples. For example, I've yet to find one that discusses an IServiceLocator and how to actually register it (or do whatever is required to make it known). What are your favorite posts / articles / SO questions that can take a noob from start to finish with the implementation?

    Read the article

  • Adding IoC Support to my WCF service hosted in a windows service (Autofac)

    - by user137348
    I'd like to setup my WCF services to use an IoC Container. There's an article in the Autofac wiki about WCF integration, but it's showing just an integration with a service hosted in IIS. But my services are hosted in a windows service. Here I got an advice to hook up the opening event http://groups.google.com/group/autofac/browse_thread/thread/23eb7ff07d8bfa03 I've followed the advice and this is what I got so far: private void RunService<T>() { var builder = new ContainerBuilder(); builder.Register(c => new DataAccessAdapter("1")).As<IDataAccessAdapter>(); ServiceHost serviceHost = new ServiceHost(typeof(T)); serviceHost.Opening += (sender, args) => serviceHost.Description.Behaviors.Add( new AutofacDependencyInjectionServiceBehavior(builder.Build(), typeof(T), ??? )); serviceHost.Open(); } The AutofacDependencyInjectionServiceBehavior has a ctor which takes 3 parameters. The third one is of type IComponentRegistration and I have no idea where can I get it from. Any ideas ? Thanks in advance.

    Read the article

  • Is this a problem typically solved with IOC?

    - by Dirk
    My current application allows users to define custom web forms through a set of admin screens. it's essentially an EAV type application. As such, I can't hard code HTML or ASP.NET markup to render a given page. Instead, the UI requests an instance of a Form object from the service layer, which in turn constructs one using a several RDMBS tables. Form contains the kind of classes you would expect to see in such a context: Form= IEnumerable<FormSections>=IEnumerable<FormFields> Here's what the service layer looks like: public class MyFormService: IFormService{ public Form OpenForm(int formId){ //construct and return a concrete implementation of Form } } Everything works splendidly (for a while). The UI is none the wiser about what sections/fields exist in a given form: It happily renders the Form object it receives into a functional ASP.NET page. A few weeks later, I get a new requirement from the business: When viewing a non-editable (i.e. read-only) versions of a form, certain field values should be merged together and other contrived/calculated fields should are added. No problem I say. Simply amend my service class so that its methods are more explicit: public class MyFormService: IFormService{ public Form OpenFormForEditing(int formId){ //construct and return a concrete implementation of Form } public Form OpenFormForViewing(int formId){ //construct and a concrete implementation of Form //apply additional transformations to the form } } Again everything works great and balance has been restored to the force. The UI continues to be agnostic as to what is in the Form, and our separation of concerns is achieved. Only a few short weeks later, however, the business puts out a new requirement: in certain scenarios, we should apply only some of the form transformations I referenced above. At this point, it feels like the "explicit method" approach has reached a dead end, unless I want to end up with an explosion of methods (OpenFormViewingScenario1, OpenFormViewingScenario2, etc). Instead, I introduce another level of indirection: public interface IFormViewCreator{ void CreateView(Form form); } public class MyFormService: IFormService{ public Form OpenFormForEditing(int formId){ //construct and return a concrete implementation of Form } public Form OpenFormForViewing(int formId, IFormViewCreator formViewCreator){ //construct a concrete implementation of Form //apply transformations to the dynamic field list return formViewCreator.CreateView(form); } } On the surface, this seems like acceptable approach and yet there is a certain smell. Namely, the UI, which had been living in ignorant bliss about the implementation details of OpenFormForViewing, must possess knowledge of and create an instance of IFormViewCreator. My questions are twofold: Is there a better way to achieve the composability I'm after? (perhaps by using an IoC container or a home rolled factory to create the concrete IFormViewCreator)? Did I fundamentally screw up the abstraction here?

    Read the article

  • C# Processing Enter Key on Custom Container

    - by tycobb
    I am currently building a custom container control. Everything was going along smoothly until I hit a snag during testing. I noticed that the Enter key is not getting processed to the control that has focus inside the container. Everything else works as expected though. I am able to click the button with either the mouse or space bar, but enter does not want to get processed. After doing endless searches on container controls and processing the enter key I have come up with no solution. I tried returning Enter as true in IsInputKey(Keys keyData) and that didn't work. Neither did setting KeyPreview on the form. I have tried it with my custom button and .NET's standard button. Like I mentioned earlier, spacebar will trigger the desired effect. Please tell me what I am missing. There has to be an easy / stupid simple way to get Enter to process over to the active child control.

    Read the article

  • MEF = may experience frustration?

    - by Dave
    Well, it's not THAT bad yet. :) But I do have questions after Reed has pointed me at MEF as a potential alternative to IoC (and so far it does look pretty good). Consider the following model: As you can see, I have an App, and this app uses Plugins (whoops, missed that association!). Both the App and Plugins require usage of an object of type CandySettings, which is found in yet another assembly. I first tried to use the ComposeParts method in MEF, but the only way I could get this to work was to do something like this in the plugin code. var container = new CompositionContainer(); container.ComposeParts(this, new CandySettings()); But this doesn't make any sense, because why would I want to create the instance of CandySettings in the plugin? It should be in the App. But if I put it in the App code, then the Plugin doesn't magically figure out how to get at ICandySettings, even though I am using [Import] in the plugin, and [Export] in CandySettings. The way I did it was to use MEF's DirectoryCatalog, because this allows the plugin, when constructed, to scan all of the assemblies in the current folder and automagically import everything that is marked with the [Import] attribute. So it looks like this, and potentially in every plugin: var catalog = new DirectoryCatalog( "."); var container = new CompositionContainer( catalog); container.ComposeParts( this); This totally works great, but I can't help but think that this is not how MEF was intended to be used?

    Read the article

  • WPF: How to autosize Path to its container?

    - by 742
    I have a Path that must resize to its StackPanel container. <StackPanel x:Name="TrackSurface"> <Path Fill="AliceBlue" Stroke="Black" StrokeThickness="1" Data="{StaticResource TranslateZ}"> </Path> </StackPanel> I think about using a transformation bound to the container but don't know how to it actually. Can someone give me hint?

    Read the article

  • Dependency Injection in ASP.NET MVC NerdDinner App using Unity 2.0

    - by shiju
    In my previous post Dependency Injection in ASP.NET MVC NerdDinner App using Ninject, we did dependency injection in NerdDinner application using Ninject. In this post, I demonstrate how to apply Dependency Injection in ASP.NET MVC NerdDinner App using Microsoft Unity Application Block (Unity) v 2.0.Unity 2.0Unity 2.0 is available on Codeplex at http://unity.codeplex.com . In earlier versions of Unity, the ObjectBuilder generic dependency injection mechanism, was distributed as a separate assembly, is now integrated with Unity core assembly. So you no longer need to reference the ObjectBuilder assembly in your applications. Two additional Built-In Lifetime Managers - HierarchicalifetimeManager and PerResolveLifetimeManager have been added to Unity 2.0.Dependency Injection in NerdDinner using UnityIn my Ninject post on NerdDinner, we have discussed the interfaces and concrete types of NerdDinner application and how to inject dependencies controller constructors. The following steps will configure Unity 2.0 to apply controller injection in NerdDinner application. Step 1 – Add reference for Unity Application BlockOpen the NerdDinner solution and add  reference to Microsoft.Practices.Unity.dll and Microsoft.Practices.Unity.Configuration.dllYou can download Unity from at http://unity.codeplex.com .Step 2 – Controller Factory for Unity The controller factory is responsible for creating controller instances.We extend the built in default controller factory with our own factory for working Unity with ASP.NET MVC. public class UnityControllerFactory : DefaultControllerFactory {     protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)     {         IController controller;         if (controllerType == null)             throw new HttpException(                     404, String.Format(                         "The controller for path '{0}' could not be found" +         "or it does not implement IController.",                     reqContext.HttpContext.Request.Path));           if (!typeof(IController).IsAssignableFrom(controllerType))             throw new ArgumentException(                     string.Format(                         "Type requested is not a controller: {0}",                         controllerType.Name),                         "controllerType");         try         {             controller = MvcUnityContainer.Container.Resolve(controllerType)                             as IController;         }         catch (Exception ex)         {             throw new InvalidOperationException(String.Format(                                     "Error resolving controller {0}",                                     controllerType.Name), ex);         }         return controller;     }   }   public static class MvcUnityContainer {     public static IUnityContainer Container { get; set; } }  Step 3 – Register Types and Set Controller Factory private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()     .RegisterType<IFormsAuthentication, FormsAuthenticationService>()     .RegisterType<IMembershipService, AccountMembershipService>()     .RegisterInstance<MembershipProvider>(Membership.Provider)     .RegisterType<IDinnerRepository, DinnerRepository>();     //Set container for Controller Factory     MvcUnityContainer.Container = container;     //Set Controller Factory as UnityControllerFactory     ControllerBuilder.Current.SetControllerFactory(                         typeof(UnityControllerFactory));            } Unity 2.0 provides a fluent interface for type configuration. Now you can call all the methods in a single statement.The above Unity configuration specified in the ConfigureUnity method tells that, to inject instance of DinnerRepositiry when there is a request for IDinnerRepositiry and  inject instance of FormsAuthenticationService when there is a request for IFormsAuthentication and inject instance of AccountMembershipService when there is a request for IMembershipService. The AccountMembershipService class has a dependency with ASP.NET Membership provider. So we configure that inject the instance of Membership Provider.After the registering the types, we set UnityControllerFactory as the current controller factory. //Set container for Controller Factory MvcUnityContainer.Container = container; //Set Controller Factory as UnityControllerFactory ControllerBuilder.Current.SetControllerFactory(                     typeof(UnityControllerFactory)); When you register a type  by using the RegisterType method, the default behavior is for the container to use a transient lifetime manager. It creates a new instance of the registered, mapped, or requested type each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. The following are the LifetimeManagers provided by Unity 2.0ContainerControlledLifetimeManager - Implements a singleton behavior for objects. The object is disposed of when you dispose of the container.ExternallyControlledLifetimeManager - Implements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope.HierarchicalifetimeManager - Implements a singleton behavior for objects. However, child containers don't share instances with parents.PerResolveLifetimeManager - Implements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph.PerThreadLifetimeManager - Implements a singleton behavior for objects but limited to the current thread.TransientLifetimeManager - Returns a new instance of the requested type for each call. (default behavior)We can also create custome lifetime manager for Unity container. The following code creating a custom lifetime manager to store container in the current HttpContext. public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName]             = newValue;     }     public void Dispose()     {         RemoveValue();     } }  Step 4 – Modify Global.asax.cs for configure Unity container In the Application_Start event, we call the ConfigureUnity method for configuring the Unity container and set controller factory as UnityControllerFactory void Application_Start() {     RegisterRoutes(RouteTable.Routes);       ViewEngines.Engines.Clear();     ViewEngines.Engines.Add(new MobileCapableWebFormViewEngine());     ConfigureUnity(); }Download CodeYou can download the modified NerdDinner code from http://nerddinneraddons.codeplex.com

    Read the article

  • Problem resolving a generic Repository with Entity Framework and Castle Windsor Container

    - by user368776
    Hi, im working in a generic repository implementarion with EF v4, the repository must be resolved by Windsor Container. First the interface public interface IRepository<T> { void Add(T entity); void Delete(T entity); T Find(int key) } Then a concrete class implements the interface public class Repository<T> : IRepository<T> where T: class { private IObjectSet<T> _objectSet; } So i need _objectSet to do stuff like this in the previous class public void Add(T entity) { _objectSet.AddObject(entity); } And now the problem, as you can see im using a EF interface like IObjectSet to do the work, but this type requires a constraint for the T generic type "where T: class". That constrait is causing an exception when Windsor tries to resolve its concrete type. Windsor configuration look like this. <castle> <components> <component id="LVRepository" service="Repository.Infraestructure.IRepository`1, Repository" type="Repository.Infraestructure.Repository`1, Repository" lifestyle="transient"> </component> </components> The container resolve code IRepository<Product> productsRep =_container.Resolve<IRepository<Product>>(); Now the exception im gettin System.ArgumentException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type 'T'. ---> System.TypeLoadException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type parameter 'T'. If i remove the constraint in the concrete class and the depedency on IObjectSet (if i dont do it get a compile error) everything works FINE, so i dont think is a container issue, but IObjectSet is a MUST in the implementation. Some help with this, please.

    Read the article

  • Calling DI Container directly in method code (MVC Actions)

    - by fearofawhackplanet
    I'm playing with DI (using Unity). I've learned how to do Constructor and Property injection. I have a static container exposed through a property in my Global.asax file (MvcApplication class). I have a need for a number of different objects in my Controller. It doesn't seem right to inject these throught the constructor, partly because of the high quantity of them, and partly because they are only needed in some Actions methods. The question is, is there anything wrong with just calling my container directly from within the Action methods? public ActionResult Foo() { IBar bar = (Bar)MvcApplication.Container.Resolve(IBar); // ... Bar uses a default constructor, I'm not actually doing any // injection here, I'm just telling my conatiner to give me Bar // when I ask for IBar so I can hide the existence of the concrete // Bar from my Controller. } This seems the simplest and most efficient way of doing things, but I've never seen an example used in this way. Is there anything wrong with this? Am I missing the concept in some way?

    Read the article

  • reuse div container to load images

    - by user295927
    Hi All; What I would like to do: use a single container to load images. As it is now: I have eleven (11) containers in HTML mark-up each with its own div. each container holds 4 images (2 images side by side top and bottom) when link in anchor tag is clicked div with images fades in. /*-- Jquery accordion is used for navigation typical example is below --*/ <li> <a class="head" href="#">commercial/hospitality</a> <ul> <li><a href="#" projectName="project1" projectType="hospitality1" image1="images/testImage1.jpg" image2="images/testImage2.jpg" image3="images/testImage3.jpg" image4="images/testImage4.jpg">hospitality project number 1</a> </li> <li><a href="#" projectName="project2" projectType="hospitality2" image1="images/testImage1.jpg" image2="images/testImage2.jpg" image3="images/testImage3.jpg" image4="images/testImage4.jpg">hospitality project number 2</a> </li> <li><a href="#" projectName="project3" projectType="hospitality3" image1="images/testImage1.jpg" image2="images/testImage2.jpg" image3="images/testImage3.jpg" image4="images/testImage4.jpg">hospitality project number 3</a> </li> </ul> </li> Typical <div> container used for image insertion currently there are 11 of them: <div id="hospitality1" class="current"> <div id="image1"><img src="images/testImage.jpg"/></div> <div id="image2"><img src="images/testImage.jpg"/></div> <div id="image3"><img src="images/testImage.jpg"/></div> <div id="image4"><img src="images/testImage.jpg"/></div> </div> Here is the code I am using at this point, it does work, but is there a better way to do this that will only re-use a single div container for loading the images? $(document).ready(function(){ $('#navigation a').click(function (selected) { var projectType = $(this).attr("projectType"); //projectType var projectName = $(this).attr("projectName"); //projectName var image1 = $(this).attr("image1"); //anchor tag for image number 1 var image2 = $(this).attr("image2"); //anchor tag for image number 2 var image3 = $(this).attr("image3"); //anchor tag for image number 3 var image4 = $(this).attr("image4"); //anchor tag for image number 4 console.log(projectType); //returns type of project console.log(projectName); //returns name of project console.log(image1); //returns 1st image console.log(image2); //returns 2nd image console.log(image3); //returns 3rd image console.log(image4); //returns 4th image $(function() { $(".current").hide(); // hides previous selected image $("#" + projectType ).fadeIn("normal").addClass("current"); }); }); As you can, see the mark up getting quite large. Any help is appreciated. ussteele

    Read the article

  • StructureMap IoC problem getting the instance in runtime

    - by user274269
    i have 2 concrete types "CategoryFilter" & "StopWordsFilter" that implements "IWordTokensFilter". Below is my setup: ForRequestedType<IWordTokensFilter>().TheDefaultIsConcreteType<CategoryFilter>() .AddInstances(x => { x.OfConcreteType<StopWordsFilter>(); } ); The problem is the run-time when structure map auto inject it on my class, bec. i have arguments with same plugin-type: public ClassA(IWordTokensFilter stopWordsFilter, IWordTokensFilter categoryFilter) i'm always getting CategoryFilter in my first argument but it should be stopWordsFilter. How can i setup this in a right way? thanks in advance

    Read the article

  • Scalable stl set like container for C++

    - by Pqr
    Hi, I need to store large number of integers. There can be duplicates in the input stream of integers, I just need to store distinct amongst them. I was using stl set initially but It went OutOfMem when input number of integers went too high. I am looking for some C++ container library which would allow me to store numbers with the said requirement possibly backed by file i.e container should not try to keep all numbers in-mem. I don't need to store this data persistently, I just need to find unique values amongst it.

    Read the article

  • python: how to design a container with elements that must reference their container

    - by Luke404
    (the title is admittedly not that great. Please forgive my English, this is the best I could think of) I'm writing a python script that will manage email domains and their accounts, and I'm also a newby at OOP design. My two (related?) issues are: the Domain class must do special work to add and remove accounts, like adding/removing them to the underlying implementation how to manage operations on accounts that must go through their container To solve the former issue I'd add a factory method to the Domain class that'll build an Account instance in that domain, and a 'remove' (anti-factory?) method to handle deletions. For the latter this seems to me "anti-oop" since what would logically be an operation on an Account (eg, change password) must always reference the containing Domain. Seems to me that I must add to the Account a reference back to the Domain and use that to get data (like the domain name) or call methods on the Domain class. Code example (element uses data from the container) that manages an underlying Vpopmail system: class Account: def __init__(self, name, password, domain): self.name = name self.password = password self.domain = domain def set_password(self, password): os.system('vpasswd %s@%s %s' % (self.name, self.domain.name, password) self.password = password class Domain: def __init__(self, domain_name): self.name = domain_name self.accounts = {} def create_account(self, name, password): os.system('vadduser %s@%s %s' % (name, self.name, password)) account = Account(name, password, self) self.accounts[name] = account def delete_account(self, name): os.system('vdeluser %s@%s' % (name, self.name)) del self.accounts[name] another option would be for Account.set_password to call a Domain method that would do the actual work - sounds equally ugly to me. Also note the duplication of data (account name also as dict key), it sounds logical (account names are "primary key" inside a domain) but accounts need to know their own name.

    Read the article

  • CSS: 100% of container height without modifying the container

    - by Rena
    Yeah, this ugly question again. I'm writing some HTML that gets inserted into a page. I have no control over the rest of the page. The structure is something like: <table <tr <td rowspan="2"left column</td <td height="1"top row above content</td </tr <tr<td height="220"my content here</td</tr </table I can write whatever I want into that table cell (including style tags to pack in my CSS), but I can't touch anything outside of it, which means I can't set the height of any parent element (including html and body), add a doctype (it has none), etc - that already kills just about every solution I can find (all seem to be "add a doctype" and/or "give the parent container a fixed height"). What I want to do is simply have a <div fill the entire cell. Width is no problem but unsurprisingly height is being a massive pain. Writing "height: 100%" doesn't do anything unless the container has a fixed height (the height="220" attribute apparently doesn't count) or the div uses absolute positioning - and then it seems to want to use 100% of the window's height (and width even) instead of the cell's. The root of the problem is the left column varies in height, as does the content, and when the left column cell is larger than the content, it won't expand to fill the cell it's in. If I set a fixed height for the content, it'll be much larger than necessary most of the time, and if I don't, it doesn't take up all of the cell and leaves an ugly gap at the bottom.

    Read the article

  • Cannot resolve Dictionary in Unity container

    - by IanR
    Hi, I've just stumbled upon this: within a Unity container, I want to register IDictionary<TK, TV>; assume that it's IDictionary<string, int> _unityContainer = new UnityContainer() .RegisterType<IDictionary<string, int>, Dictionary<string, int>>(); but if I try var d = _unityContainer.Resolve<IDictionary<string, int>>(); it fails to resolve... I get... Microsoft.Practices.Unity.ResolutionFailedException: Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "System.Collections.Generic.IDictionary`2[System.String,System.Int32]", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The type Dictionary`2 has multiple constructors of length 2. Unable to disambiguate. At the time of the exception, the container was: Resolving System.Collections.Generic.Dictionary2[System.String,System.Int32],(none) (mapped from System.Collections.Generic.IDictionary2[System.String,System.Int32], (none)) --- System.InvalidOperationException: The type Dictionary`2 has multiple constructors of length 2. Unable to disambiguate.. So it looks like it has found the Type to resolve (being Dictionary<string, int>) but failed to new it up... How come unity can't resolve this type? If I type IDictionary<string, int> d = new Dictionary<string, int>() that works... any ideas? thanks!

    Read the article

  • forcing a child component to resize itself larger than its container

    - by Josh
    I am creating a component that displays a variable amount of "gauges" (square tiles of content if you will), that is laid out like so: <HDividedBox id="container"> <VBox id="myComponent"> <HBox id="header"> ...header content... </HBox> <Tile id="body"> ...gauges are added to the body... </Tile> </Vbox> </HDividedBox> The body Tile has a horizontal direction. When I drag the HDividedBox to make myComponent smaller, the body component will get smaller as well, and eventually if there are too many gauges to fit horizontally, they will be bumped to the next row, and thus the smaller I make myComponent, the number of vertically stacked gauges grows. This is all well and good. The problem is, no matter what combination of settings I use, I absolutely cannot get the body (a Tile) to size itself beyond the size of myComponent, which would ideally cause myComponent to scroll vertically. Even setting the maxHeight of the body to some huge value, it will never size itself larger than it's container. Any ideas on how to accomplish this? Thanks

    Read the article

  • Singleton design pattern vs Singleton beans in Spring container

    - by Peeyush
    As we all know we have beans as singleton by default in Spring container and if we have a web application based on Spring framework then in that case do we really need to implement Singleton design pattern to hold global data rather than just creating a bean through spring. Please bear with me if I'm not able to explain what I actually meant to ask.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >