Search Results

Search found 43 results on 2 pages for 'servicelocator'.

Page 1/2 | 1 2  | Next Page >

  • Validation without ServiceLocator

    - by Dmitriy Nagirnyak
    Hi, I am getting back again and again to it thinking about the best way to perform validation on POCO objects that need access to some context (ISession in NH, IRepository for example). The only option I still can see is to use S*ervice Locator*, so my validation would look like: public User : ICanValidate { public User() {} // We need this constructor (so no context known) public virtual string Username { get; set; } public IEnumerable<ValidationError> Validate() { if (ServiceLocator.GetService<IUserRepository>().FindUserByUsername(Username) != null) yield return new ValidationError("Username", "User already exists.") } } I already use Inversion Of control and Dependency Injection and really don't like the ServiceLocator due to number of facts: Harder to maintain implicit dependencies. Harder to test the code. Potential threading issues. Explicit dependency only on the ServiceLocator. The code becomes harder to understand. Need to register the ServiceLocator interfaces during the testing. But on the other side, with plain POCO objects, I do not see any other way of performing the validation like above without ServiceLocator and only using IoC/DI. So the question would be: is there any way to use DI/IoC for the situation described above? Thanks, Dmitriy.

    Read the article

  • can ServiceLocator.Current.GetInstance return null?

    - by mauricio076
    I have this piece of code (or similar) in many of our views: private IEventAggregator eventAggregator; Constructor() { eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>(); ... } I read from this post that ServiceLocator.Current can throw NullReferenceException (bad thing on a constructor) but I was wondering if the GetInstance<() method can return null (or some other inconsistent object) making eventAggregator dangerous to use later in other methods. NOTE: I'm quite new to MVVM and WPF

    Read the article

  • ServiceLocator not initialized in Tests project

    - by Carl Bussema
    When attempting to write a test related to my new Tasks (MVC3, S#arp 2.0), I get this error when I try to run the test: MyProject.Tests.MyProject.Tasks.CategoryTasksTests.CanConfirmDeleteReadiness: SetUp : System.NullReferenceException : ServiceLocator has not been initialized; I was trying to retrieve SharpArch.NHibernate.ISessionFactoryKeyProvider ---- System.NullReferenceException : Object reference not set to an instance of an object. at SharpArch.Domain.SafeServiceLocator1.GetService() at SharpArch.NHibernate.SessionFactoryKeyHelper.GetKeyFrom(Object anObject) at SharpArch.NHibernate.NHibernateRepositoryWithTypedId2.get_Session() at SharpArch.NHibernate.NHibernateRepositoryWithTypedId2.Save(T entity) at MyProject.Tests.MyProject.Tasks.CategoryTasksTests.Setup() in C:\code\MyProject\Solutions\MyProject.Tests\MyProject.Tasks\CategoryTasksTests.cs:line 36 --NullReferenceException at Microsoft.Practices.ServiceLocation.ServiceLocator.get_Current() at SharpArch.Domain.SafeServiceLocator1.GetService() Other tests which do not involve the new class (e.g., generate/confirm database mappings) run correctly. My ServiceLocatorInitializer is as follows public class ServiceLocatorInitializer { public static void Init() { IWindsorContainer container = new WindsorContainer(); container.Register( Component .For(typeof(DefaultSessionFactoryKeyProvider)) .ImplementedBy(typeof(DefaultSessionFactoryKeyProvider)) .Named("sessionFactoryKeyProvider")); container.Register( Component .For(typeof(IEntityDuplicateChecker)) .ImplementedBy(typeof(EntityDuplicateChecker)) .Named("entityDuplicateChecker")); ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container)); } }

    Read the article

  • Howto set my IServiceLocator implementation as ServiceLocator.Current?

    - by stiank81
    I'm working on replacing Unity with Ninject in the Prism framework. This requires me to implement a Ninject specific IServiceLocator. From what I've understood I can inherit the ServiceLocatorImplBase instead, so that's what I do. Now how can I set this to be the Current ServiceLocator? I need this in order to have e.g. the RegionManager get it when it creates regions, and calls: IServiceLocator locator = ServiceLocator.Current; This is a static property, but it doesn't have a setter.. There is a function: void ServiceLocator.SetLocatorProvider(ServiceLocatorProvider newProvider); ..but the argument doesn't match my ServiceLocatorImplBase. Any ideas?

    Read the article

  • Weblogic 10 - JMS - This RJVM has already been shutdown

    - by Kumar225
    Any idea why the following errors comes up.This is happening when posting a JMS message to a queue deployed on Admin server from the application on managed server. 009-06-02 11:21:18,688 (com.xxx.util.servicelocator.ServiceLocator:612) ERROR - Error while loading Queue ProfilerNotify javax.naming.CommunicationException [Root exception is java.rmi.ConnectException: This RJVM has already been shutdown 3481854169479569584S:XX.XXX.X.XXX:[9200,9200,-1,-1,-1,-1,-1]:Production10:AdminServer] at weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:64) at weblogic.jndi.internal.WLContextImpl.translateException(WLContextImpl.java:426) at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:382) at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:367) at javax.naming.InitialContext.lookup(InitialContext.java:351) at com.xxx.util.servicelocator.ServiceLocator.loadQueue(ServiceLocator.java:607) at com.xxx.util.servicelocator.ServiceLocator.getQueue(ServiceLocator.java:285)

    Read the article

  • ServiceLocator has not been initialized; I was trying to retrieve SharpArch.Core.CommonValidator.IVa

    - by Chinmaya
    Server Error in '/' Application. ServiceLocator has not been initialized; I was trying to retrieve SharpArch.Core.CommonValidator.IValidator Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: ServiceLocator has not been initialized; I was trying to retrieve SharpArch.Core.CommonValidator.IValidator Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [NullReferenceException: ServiceLocator has not been initialized; I was trying to retrieve SharpArch.Core.CommonValidator.IValidator] SharpArch.Core.SafeServiceLocator`1.GetService() in C:\MyStuff\Projects\SharpArchGitHub\src\SharpArch\SharpArch.Core\SafeServiceLocator.cs:20 SharpArch.Core.DomainModel.ValidatableObject.get_Validator() in C:\MyStuff\Projects\SharpArchGitHub\src\SharpArch\SharpArch.Core\DomainModel\ValidatableObject.cs:20 SharpArch.Core.DomainModel.ValidatableObject.ValidationResults() in C:\MyStuff\Projects\SharpArchGitHub\src\SharpArch\SharpArch.Core\DomainModel\ValidatableObject.cs:15 SharpArch.Web.ModelBinder.SharpModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\MyStuff\Projects\SharpArchGitHub\src\SharpArch\SharpArch.Web\ModelBinder\SharpModelBinder.cs:40 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +304 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +772 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +345 SharpArch.Web.ModelBinder.SharpModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\MyStuff\Projects\SharpArchGitHub\src\SharpArch\SharpArch.Web\ModelBinder\SharpModelBinder.cs:241 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +219 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +109 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +399 System.Web.Mvc.Controller.ExecuteCore() +126 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +151 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57 System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

    Read the article

  • How to combine designable components with dependency injection

    - by Wim Coenen
    When creating a designable .NET component, you are required to provide a default constructor. From the IComponent documentation: To be a component, a class must implement the IComponent interface and provide a basic constructor that requires no parameters or a single parameter of type IContainer. This makes it impossible to do dependency injection via constructor arguments. (Extra constructors could be provided, but the designer would ignore them.) Some alternatives we're considering: Service Locator Don't use dependency injection, instead use the service locator pattern to acquire dependencies. This seems to be what IComponent.Site.GetService is for. I guess we could create a reusable ISite implementation (ConfigurableServiceLocator?) which can be configured with the necessary dependencies. But how does this work in a designer context? Dependency Injection via properties Inject dependencies via properties. Provide default instances if they are necessary to show the component in a designer. Document which properties need to be injected. Inject dependencies with an Initialize method This is much like injection via properties but it keeps the list of dependencies that need to be injected in one place. This way the list of required dependencies is documented implicitly, and the compiler will assists you with errors when the list changes. Any idea what the best practice is here? How do you do it? edit: I have removed "(e.g. a WinForms UserControl)" since I intended the question to be about components in general. Components are all about inversion of control (see section 8.3.1 of the UMLv2 specification) so I don't think that "you shouldn't inject any services" is a good answer. edit 2: It took some playing with WPF and the MVVM pattern to finally "get" Mark's answer. I see now that visual controls are indeed a special case. As for using non-visual components on designer surfaces, I think the .NET component model is fundamentally incompatible with dependency injection. It appears to be designed around the service locator pattern instead. Maybe this will start to change with the infrastructure that was added in .NET 4.0 in the System.ComponentModel.Composition namespace.

    Read the article

  • Service locator for generics

    - by vittore
    Hi everyone, I have say a dozen types T which inherit from EntityObject and IDataObject. I have generic the following interface IDataManager<T> where T : EntityObject, IDataObject ... I have also base class for data managers BaseDataManager<T> : IDataManager<T> where T : EntityObject, IDataObject .... And i have particular classes public class Result : EntityObject, IDataObject .... public class ResultDataManager : BaseDataManager<Result> ... I want to implement service locator, which will return instance of IDataManager<T> for T But I stucked how to implement it in a neat way without a lot of castings. Any ideas?

    Read the article

  • J2EE/EJB + service locator: is it safe to cache EJB Home lookup result ?

    - by Guillaume
    In a J2EE application, we are using EJB2 in weblogic. To avoid losing time building the initial context and looking up EJB Home interface, I'm considering the Service Locator Pattern. But after a few search on the web I found that event if this pattern is often recommended for the InitialContext caching, there are some negative opinion about the EJB Home caching. Questions: Is it safe to cache EJB Home lookup result ? What will happen if one my cluster node is no more working ? What will happen if I install a new version of the EJB without refreshing the service locator's cache ?

    Read the article

  • Not able to use spring Beans outside container . Always picking up WebSphere Context

    - by Abhijit
    We have the a whole lot of spring bean defined in our project which we deploy in Websphere ^. One example being the following: oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@oracle:1521:OASIS oasis_owner o3ngin33r Now we have a service locator class like following private static ServiceLocator serviceLocator = new ServiceLocator(); private static ApplicationContext beanFactory = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT_LOCATION); protected ServiceLocator() { } public ApplicationContext getBeanFactory() { return beanFactory; } public static ServiceLocator getInstance() { return serviceLocator; Now when I am trying to do this from my jUnit ServiceLocator.getInstance().getBean("oasJdbcData"; getting the following exception Caused by: javax.naming.ServiceUnavailableException: Could not obtain an initial context due to a communication failure. Since no provider URL was specified, the default provider URL of "corbaloc:iiop:[email protected]:2809/NameService" was used. Make sure that any bootstrap address information in the URL is correct and that the target name server is running. Possible causes other than an incorrect bootstrap address or unavailable name server include the network environment and workstation network configuration. [Root exception is org.omg.CORBA.TRANSIENT: java.net.ConnectException: Connection refused: connect:host=192.168.255.1,port=2809 vmcid: IBM minor code: E02 completed: No] at com.ibm.ws.naming.util.WsnInitCtxFactory.mapInitialReferenceFailure(WsnInitCtxFactory.java:1968) at com.ibm.ws.naming.util.WsnInitCtxFactory.mergeWsnNSProperties(WsnInitCtxFactory.java:1172) at com.ibm.ws.naming.util.WsnInitCtxFactory.getRootContextFromServer(WsnInitCtxFactory.java:720) at com.ibm.ws.naming.util.WsnInitCtxFactory.getRootJndiContext(WsnInitCtxFactory.java:643) at com.ibm.ws.naming.util.WsnInitCtxFactory.getInitialContextInternal(WsnInitCtxFactory.java:489) at com.ibm.ws.naming.util.WsnInitCtx.getContext(WsnInitCtx.java:113) at com.ibm.ws.naming.util.WsnInitCtx.getContextIfNull(WsnInitCtx.java:428) at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:144) at javax.naming.InitialContext.lookup(InitialContext.java:361) at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:155) at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:88) at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:153) at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178) at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:104) at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105) at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:200) at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:186) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334) ... 33 more which clearly shows it is looking for IntialContext of Websphere which I dont want Any body can tell me what I am doing wrong?

    Read the article

  • Avoiding circular project/assembly references in Visual Studio with statically typed dependency conf

    - by svnpttrssn
    First, I want to say that I am not interested in debating about any non-helpful "answers" to my question, with suggestions to putting everything in one assembly, i.e. there is no need for anyone to provide webpages such as the page titled with "Separate Assemblies != Loose Coupling". Now, my question is if it somehow (maybe with some Visual Studio configuration to allow for circular project dependencies?) is possible to use one project/assembly (I am here calling it the "ServiceLocator" assembly) for retrieving concrete implementation classes, (e.g. with StructureMap) which can be referred to from other projects, while it of course is also necessary for the the ServiceLocator itself to refer to other projects with the interfaces and the implementations ? Visual Studio project example, illustrating the kind of dependency structure I am talking about: http://img10.imageshack.us/img10/8838/testingdependencyinject.png Please note in the above picture, the problem is how to let the classes in "ApplicationLayerServiceImplementations" retrieve and instantiate classes that implement the interfaces in "DomainLayerServiceInterfaces". The goal is here to not refer directly to the classes in "DomainLayerServiceImplementations", but rather to try using the project "ServiceLocator" to retrieve such classes, but then the circular dependency problem occurrs... For example, a "UserInterfaceLayer" project/assembly might contain this kind of code: ContainerBootstrapper.BootstrapStructureMap(); // located in "ServiceLocator" project/assembly MyDomainLayerInterface myDomainLayerInterface = ObjectFactory.GetInstance<MyDomainLayerInterface>(); // refering to project/assembly "DomainLayerServiceInterfaces" myDomainLayerInterface.MyDomainLayerMethod(); MyApplicationLayerInterface myApplicationLayerInterface = ObjectFactory.GetInstance<MyApplicationLayerInterface>(); // refering to project/assembly "ApplicationLayerServiceInterfaces" myApplicationLayerInterface.MyApplicationLayerMethod(); The above code do not refer to the implementation projects/assemblies ApplicationLayerServiceImplementations and DomainLayerServiceImplementations, which contain this kind of code: public class MyApplicationLayerImplementation : MyApplicationLayerInterface and public class MyDomainLayerImplementation : MyDomainLayerInterface The "ServiceLocator" project/assembly might contain this code: using ApplicationLayerServiceImplementations; using ApplicationLayerServiceInterfaces; using DomainLayerServiceImplementations; using DomainLayerServiceInterfaces; using StructureMap; namespace ServiceLocator { public static class ContainerBootstrapper { public static void BootstrapStructureMap() { ObjectFactory.Initialize(x => { // The two interfaces and the two implementations below are located in four different Visual Studio projects x.ForRequestedType<MyDomainLayerInterface>().TheDefaultIsConcreteType<MyDomainLayerImplementation>(); x.ForRequestedType<MyApplicationLayerInterface>().TheDefaultIsConcreteType<MyApplicationLayerImplementation>(); }); } } } So far, no problem, but the problem occurs when I want to let the class "MyApplicationLayerImplementation" in the project/assembly "ApplicationLayerServiceImplementations" use the "ServiceLocator" project/assembly for retrieving an implementation of "MyDomainLayerInterface". When I try to do that, i.e. add a reference from "MyApplicationLayerImplementation" to "ServiceLocator", then Visual Studio complains about circular dependencies between projects. Is there any nice solution to this problem, which does not imply using refactoring-unfriendly string based xml-configuration which breaks whenever an interface or class or its namespace is renamed ? / Sven

    Read the article

  • MvcExtensions – Bootstrapping

    - by kazimanzurrashid
    When you create a new ASP.NET MVC application you will find that the global.asax contains the following lines: namespace MvcApplication1 { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } } As the application grows, there are quite a lot of plumbing code gets into the global.asax which quickly becomes a design smell. Lets take a quick look at the code of one of the open source project that I recently visited: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default","{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }); } protected override void OnApplicationStarted() { Error += OnError; EndRequest += OnEndRequest; var settings = new SparkSettings() .AddNamespace("System") .AddNamespace("System.Collections.Generic") .AddNamespace("System.Web.Mvc") .AddNamespace("System.Web.Mvc.Html") .AddNamespace("MvcContrib.FluentHtml") .AddNamespace("********") .AddNamespace("********.Web") .SetPageBaseType("ApplicationViewPage") .SetAutomaticEncoding(true); #if DEBUG settings.SetDebug(true); #endif var viewFactory = new SparkViewFactory(settings); ViewEngines.Engines.Add(viewFactory); #if !DEBUG PrecompileViews(viewFactory); #endif RegisterAllControllersIn("********.Web"); log4net.Config.XmlConfigurator.Configure(); RegisterRoutes(RouteTable.Routes); Factory.Load(new Components.WebDependencies()); ModelBinders.Binders.DefaultBinder = new Binders.GenericBinderResolver(Factory.TryGet<IModelBinder>); ValidatorConfiguration.Initialize("********"); HtmlValidationExtensions.Initialize(ValidatorConfiguration.Rules); } private void OnEndRequest(object sender, System.EventArgs e) { if (((HttpApplication)sender).Context.Handler is MvcHandler) { CreateKernel().Get<ISessionSource>().Close(); } } private void OnError(object sender, System.EventArgs e) { CreateKernel().Get<ISessionSource>().Close(); } protected override IKernel CreateKernel() { return Factory.Kernel; } private static void PrecompileViews(SparkViewFactory viewFactory) { var batch = new SparkBatchDescriptor(); batch.For<HomeController>().For<ManageController>(); viewFactory.Precompile(batch); } As you can see there are quite a few of things going on in the above code, Registering the ViewEngine, Compiling the Views, Registering the Routes/Controllers/Model Binders, Settings up Logger, Validations and as you can imagine the more it becomes complex the more things will get added in the application start. One of the goal of the MVCExtensions is to reduce the above design smell. Instead of writing all the plumbing code in the application start, it contains BootstrapperTask to register individual services. Out of the box, it contains BootstrapperTask to register Controllers, Controller Factory, Action Invoker, Action Filters, Model Binders, Model Metadata/Validation Providers, ValueProvideraFactory, ViewEngines etc and it is intelligent enough to automatically detect the above types and register into the ASP.NET MVC Framework. Other than the built-in tasks you can create your own custom task which will be automatically executed when the application starts. When the BootstrapperTasks are in action you will find the global.asax pretty much clean like the following: public class MvcApplication : UnityMvcApplication { public void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e) { Check.Argument.IsNotNull(e, "e"); HttpException exception = e.Exception.GetBaseException() as HttpException; if ((exception != null) && (exception.GetHttpCode() == (int)HttpStatusCode.NotFound)) { e.Dismiss(); } } } The above code is taken from my another open source project Shrinkr, as you can see the global.asax is longer cluttered with any plumbing code. One special thing you have noticed that it is inherited from the UnityMvcApplication rather than regular HttpApplication. There are separate version of this class for each IoC Container like NinjectMvcApplication, StructureMapMvcApplication etc. Other than executing the built-in tasks, the Shrinkr also has few custom tasks which gets executed when the application starts. For example, when the application starts, we want to ensure that the default users (which is specified in the web.config) are created. The following is the custom task that is used to create those default users: public class CreateDefaultUsers : BootstrapperTask { protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { IUserRepository userRepository = serviceLocator.GetInstance<IUserRepository>(); IUnitOfWork unitOfWork = serviceLocator.GetInstance<IUnitOfWork>(); IEnumerable<User> users = serviceLocator.GetInstance<Settings>().DefaultUsers; bool shouldCommit = false; foreach (User user in users) { if (userRepository.GetByName(user.Name) == null) { user.AllowApiAccess(ApiSetting.InfiniteLimit); userRepository.Add(user); shouldCommit = true; } } if (shouldCommit) { unitOfWork.Commit(); } return TaskContinuation.Continue; } } There are several other Tasks in the Shrinkr that we are also using which you will find in that project. To create a custom bootstrapping task you have create a new class which either implements the IBootstrapperTask interface or inherits from the abstract BootstrapperTask class, I would recommend to start with the BootstrapperTask as it already has the required code that you have to write in case if you choose the IBootstrapperTask interface. As you can see in the above code we are overriding the ExecuteCore to create the default users, the MVCExtensions is responsible for populating the  ServiceLocator prior calling this method and in this method we are using the service locator to get the dependencies that are required to create the users (I will cover the custom dependencies registration in the next post). Once the users are created, we are returning a special enum, TaskContinuation as the return value, the TaskContinuation can have three values Continue (default), Skip and Break. The reason behind of having this enum is, in some  special cases you might want to skip the next task in the chain or break the complete chain depending upon the currently running task, in those cases you will use the other two values instead of the Continue. The last thing I want to cover in the bootstrapping task is the Order. By default all the built-in tasks as well as newly created task order is set to the DefaultOrder(a static property), in some special cases you might want to execute it before/after all the other tasks, in those cases you will assign the Order in the Task constructor. For Example, in Shrinkr, we want to run few background services when the all the tasks are executed, so we assigned the order as DefaultOrder + 1. Here is the code of that Task: public class ConfigureBackgroundServices : BootstrapperTask { private IEnumerable<IBackgroundService> backgroundServices; public ConfigureBackgroundServices() { Order = DefaultOrder + 1; } protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { backgroundServices = serviceLocator.GetAllInstances<IBackgroundService>().ToList(); backgroundServices.Each(service => service.Start()); return TaskContinuation.Continue; } protected override void DisposeCore() { backgroundServices.Each(service => service.Stop()); } } That’s it for today, in the next post I will cover the custom service registration, so stay tuned.

    Read the article

  • Binding from View-Model to View-Model of a child User Control in Silverlight? 2 sources - 1 target..

    - by andrej351
    Hi there, So i have a UserControl for one of my Views and have another 'child' UserControl inside that. The outer 'parent' UserControl has a Collection on its View-Model and a Grid control on it to display a list of Items. I want to place another UserControl inside this UserControl to display a form representing the details of one Item. The outer / parent UserControl's View-Model already has a property on it to hold the currently selected Item and i would like to bind this to a DependancyProperty on the inner / child UserControl. I would then like to bind that DependancyProperty to a property on the child UserControl's View-Model. I can then set the DependancyProperty once in XAML with a binding expression and have the child UserControl do all its work in its View-Model like it should. The code i have looks like this.. Parent UserControl: <UserControl x:Class="ItemsListView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel}"> <!-- Grid Control here... --> <ItemDetailsView Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel.SelectedItem}" /> </UserControl> Child UserControl: <UserControl x:Class="ItemDetailsView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel}" ItemDetailsView.Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel.Item, Mode=TwoWay}"> <!-- Form controls here... --> </UserControl> The selected Item is bound to the DependancyProperty fine. However from the DependancyProperty to the child View-Model does not. It appears to be a situation where there are two concurrent bindings which need to work but with the same target for two sources. Why won't the second (in the child UserControl) binding work?? Is there a way to acheive the behaviour I'm after?? Cheers.

    Read the article

  • Binding a Value from a View-Model to the View-Model of a child User Control in Silverlight?

    - by andrej351
    Hi there, So i have a UserControl for one of my Views and have another 'child' UserControl inside that. The outer 'parent' UserControl has a Collection on its View-Model and a Grid control on it to display a list of Items. I want to place another UserControl inside this UserControl to display a form representing the details of one Item. The outer / parent UserControl's View-Model already has a property on it to hold the currently selected Item and i would like to bind this to a DependancyProperty on the inner / child UserControl. I would then like to bind that DependancyProperty to a property on the child UserControl's View-Model. I can then set the DependancyProperty once in XAML with a binding expression and have the child UserControl do all its work in its View-Model like it should. The code i have looks like this.. Parent UserControl: <UserControl x:Class="ItemsListView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel}"> <!-- Grid Control here... --> <ItemDetailsView Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel.SelectedItem}" /> </UserControl> Child UserControl: <UserControl x:Class="ItemDetailsView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel}" ItemDetailsView.Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel.Item, Mode=TwoWay}"> <!-- Form controls here... --> </UserControl> The selected Item is bound to the DependancyProperty fine. However from the DependancyProperty to the child View-Model does not. I've used this sort of apporach in a WPF app without problems. It appears to be a situation where there are two concurrent bindings which need to work but with the same target for two sources. Why won't the second (in the child UserControl) binding work?? Is there a way to acheive the behaviour I'm after?? Cheers.

    Read the article

  • Why do we (really) program to interfaces?

    - by Kyle Burns
    One of the earliest lessons I was taught in Enterprise development was "always program against an interface".  This was back in the VB6 days and I quickly learned that no code would be allowed to move to the QA server unless my business objects and data access objects each are defined as an interface and have a matching implementation class.  Why?  "It's more reusable" was one answer.  "It doesn't tie you to a specific implementation" a slightly more knowing answer.  And let's not forget the discussion ending "it's a standard".  The problem with these responses was that senior people didn't really understand the reason we were doing the things we were doing and because of that, we were entirely unable to realize the intent behind the practice - we simply used interfaces and had a bunch of extra code to maintain to show for it. It wasn't until a few years later that I finally heard the term "Inversion of Control".  Simply put, "Inversion of Control" takes the creation of objects that used to be within the control (and therefore a responsibility of) of your component and moves it to some outside force.  For example, consider the following code which follows the old "always program against an interface" rule in the manner of many corporate development shops: 1: ICatalog catalog = new Catalog(); 2: Category[] categories = catalog.GetCategories(); In this example, I met the requirement of the rule by declaring the variable as ICatalog, but I didn't hit "it doesn't tie you to a specific implementation" because I explicitly created an instance of the concrete Catalog object.  If I want to test the functionality of the code I just wrote I have to have an environment in which Catalog can be created along with any of the resources upon which it depends (e.g. configuration files, database connections, etc) in order to test my functionality.  That's a lot of setup work and one of the things that I think ultimately discourages real buy-in of unit testing in many development shops. So how do I test my code without needing Catalog to work?  A very primitive approach I've seen is to change the line the instantiates catalog to read: 1: ICatalog catalog = new FakeCatalog();   once the test is run and passes, the code is switched back to the real thing.  This obviously poses a huge risk for introducing test code into production and in my opinion is worse than just keeping the dependency and its associated setup work.  Another popular approach is to make use of Factory methods which use an object whose "job" is to know how to obtain a valid instance of the object.  Using this approach, the code may look something like this: 1: ICatalog catalog = CatalogFactory.GetCatalog();   The code inside the factory is responsible for deciding "what kind" of catalog is needed.  This is a far better approach than the previous one, but it does make projects grow considerably because now in addition to the interface, the real implementation, and the fake implementation(s) for testing you have added a minimum of one factory (or at least a factory method) for each of your interfaces.  Once again, developers say "that's too complicated and has me writing a bunch of useless code" and quietly slip back into just creating a new Catalog and chalking any test failures up to "it will probably work on the server". This is where software intended specifically to facilitate Inversion of Control comes into play.  There are many libraries that take on the Inversion of Control responsibilities in .Net and most of them have many pros and cons.  From this point forward I'll discuss concepts from the standpoint of the Unity framework produced by Microsoft's Patterns and Practices team.  I'm primarily focusing on this library because it questions about it inspired this posting. At Unity's core and that of most any IoC framework is a catalog or registry of components.  This registry can be configured either through code or using the application's configuration file and in the most simple terms says "interface X maps to concrete implementation Y".  It can get much more complicated, but I want to keep things at the "what does it do" level instead of "how does it do it".  The object that exposes most of the Unity functionality is the UnityContainer.  This object exposes methods to configure the catalog as well as the Resolve<T> method which is used to obtain an instance of the type represented by T.  When using the Resolve<T> method, Unity does not necessarily have to just "new up" the requested object, but also can track dependencies of that object and ensure that the entire dependency chain is satisfied. There are three basic ways that I have seen Unity used within projects.  Those are through classes directly using the Unity container, classes requiring injection of dependencies, and classes making use of the Service Locator pattern. The first usage of Unity is when classes are aware of the Unity container and directly call its Resolve method whenever they need the services advertised by an interface.  The up side of this approach is that IoC is utilized, but the down side is that every class has to be aware that Unity is being used and tied directly to that implementation. Many developers don't like the idea of as close a tie to specific IoC implementation as is represented by using Unity within all of your classes and for the most part I agree that this isn't a good idea.  As an alternative, classes can be designed for Dependency Injection.  Dependency Injection is where a force outside the class itself manipulates the object to provide implementations of the interfaces that the class needs to interact with the outside world.  This is typically done either through constructor injection where the object has a constructor that accepts an instance of each interface it requires or through property setters accepting the service providers.  When using dependency, I lean toward the use of constructor injection because I view the constructor as being a much better way to "discover" what is required for the instance to be ready for use.  During resolution, Unity looks for an injection constructor and will attempt to resolve instances of each interface required by the constructor, throwing an exception of unable to meet the advertised needs of the class.  The up side of this approach is that the needs of the class are very clearly advertised and the class is unaware of which IoC container (if any) is being used.  The down side of this approach is that you're required to maintain the objects passed to the constructor as instance variables throughout the life of your object and that objects which coordinate with many external services require a lot of additional constructor arguments (this gets ugly and may indicate a need for refactoring). The final way that I've seen and used Unity is to make use of the ServiceLocator pattern, of which the Patterns and Practices team has also provided a Unity-compatible implementation.  When using the ServiceLocator, your class calls ServiceLocator.Retrieve in places where it would have called Resolve on the Unity container.  Like using Unity directly, it does tie you directly to the ServiceLocator implementation and makes your code aware that dependency injection is taking place, but it does have the up side of giving you the freedom to swap out the underlying IoC container if necessary.  I'm not hugely concerned with hiding IoC entirely from the class (I view this as a "nice to have"), so the single biggest problem that I see with the ServiceLocator approach is that it provides no way to proactively advertise needs in the way that constructor injection does, allowing more opportunity for difficult to track runtime errors. This blog entry has not been intended in any way to be a definitive work on IoC, but rather as something to spur thought about why we program to interfaces and some ways to reach the intended value of the practice instead of having it just complicate your code.  I hope that it helps somebody begin or continue a journey away from being a "Cargo Cult Programmer".

    Read the article

  • Connecting to Magento Web Services with Java

    - by kerry
    I was in the unenviable position of needing to connect to Magento, a PHP ecommerce platform, web services using Java.  It was kind of difficult to get the classes generated from the WSDL so I figured I would throw the results up on my github account for any other poor sap in a similar position. First, pull down the project using git: git clone git://github.com/webdevwilson/magento-java.git and build it with maven: mvn install Here is a quick example of how to pull an order using the generated classes: MagentoServiceLocator serviceLocator = new MagentoServiceLocator(); String url = "http://domain.com/index.php/api/v2_soap"; Mage_Api_Model_Server_V2_HandlerPortType port = serviceLocator.getMage_Api_Model_Server_V2_HandlerPort(url); String sessionId = port.login("username", "key"); SalesOrderEntity salesOrder = port.salesOrderInfo(sessionId, orderId); I also have some wrapper code in there that makes it a little easier to call the API. Checkout the project at https://github.com/webdevwilson/magento-java There is another option. it’s called Magja and it is located at google code.

    Read the article

  • Prism - loading modules causes activation error

    - by Noich
    I've created a small Prism application (using MEF) with the following parts: - Infrastructure project, that contains a global file of region names. - Main project, that has 2 buttons to load other modules. - ModulesInterfaces project, where I've defined an IDataAccess interface for my DataAccess module. - DataAccess project, where there are several files but one main DataAccess class that implements both IDataAccess and IModule. When the user click a button, I want to show him a list of employees, so I need the DataAccess module. My code is as follows: var namesView = new EmployeesListView(); var namesViewModel = new EmployeesListViewModel(employeeRepository); namesView.DataContext = namesViewModel; namesViewModel.EmployeeSelected += EmployeeSelected; LocateManager(); manager.Regions["ContentRegion"].Add(new NoEmployeeView(), "noEmployee"); manager.Regions["NavigationRegion"].Add(namesView); I get an exception in my code when I'm trying to get DataAccess as a service (via ServiceLocator). I'm not sure if that's the right way to go, but trying to get it from the ModuleCatalog (as a type IDataAccess returns an empty enumeration). I'd appreciate some directions. Thanks. The problematic code line: object instance = ServiceLocator.Current.GetInstance(typeof(DataAccess.DataAccess)); The exact exception: Activation error occured while trying to get instance of type DataAccess, key "" The inner exception is null, the stack trace: at Microsoft.Practices.Prism.MefExtensions.MefServiceLocatorAdapter.DoGetInstance(Type serviceType, String key) in c:\release\WorkingDir\PrismLibraryBuild\PrismLibrary\Desktop\Prism.MefExtensions\MefServiceLocatorAdapter.cs:line 76 at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) Edit The same exception is thrown for: container = (CompositionContainer)ServiceLocator.Current.GetInstance(typeof(CompositionContainer));

    Read the article

  • Could not synchronize database state with session

    - by user359427
    Hello all, I'm having trouble trying to persist an entity which ID is a generated value. This entity (A), at persistence time, has to persist in cascade another entity(B). The relationship within A and B is OneToMany, and the property related in B is part of a composite key. I'm using Eclipse, JBOSS Runtime, JPA/Hibernate Here is my code: Entity A: @Entity public class Cambios implements Serializable { private static final long serialVersionUID = 1L; @SequenceGenerator(name="CAMBIOS_GEN",sequenceName="CAMBIOS_SEQ",allocationSize=1) @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CAMBIOS_GEN") @Column(name="ID_CAMBIO") private Long idCambio; //bi-directional many-to-one association to ObjetosCambio @OneToMany(cascade={CascadeType.PERSIST},mappedBy="cambios") private List<ObjetosCambio> objetosCambioList; public Cambios() { } ... } Entity B: @Entity @Table(name="OBJETOS_CAMBIO") public class ObjetosCambio implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private ObjetosCambioPK id; //bi-directional many-to-one association to Cambios @ManyToOne @JoinColumn(name="ID_CAMBIO", insertable=false, updatable=false) private Cambios cambios; //bi-directional many-to-one association to Objetos @ManyToOne @JoinColumn(name="ID_OBJETO", insertable=false, updatable=false) private Objetos objetos; public ObjetosCambio() { } ... Entity B PK: @Embeddable public class ObjetosCambioPK implements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; @Column(name="ID_OBJETO") private Long idObjeto; @Column(name="ID_CAMBIO") private Long idCambio; public ObjetosCambioPK() { } Client: public String generarCambio(){ ServiceLocator serviceLocator = null; try { serviceLocator = serviceLocator.getInstance(); FachadaLocal tcLocal; tcLocal = (FachadaLocal)serviceLocator.getFacadeService("java:comp/env/negocio/Fachada"); Cambios cambio = new Cambios(); Iterator it = objetosLocal.iterator(); //OBJETOSLOCAL IS ALREADY POPULATED OUTSIDE OF THIS METHOD List<ObjetosCambio> ocList = new ArrayList(); while (it.hasNext()){ Objetos objeto = (Objetos)it.next(); ObjetosCambio objetosCambio = new ObjetosCambio(); objetosCambio.setCambios(cambio); //AT THIS TIME THIS "CAMBIO" DOES NOT HAVE ITS ID, ITS SUPPOSED TO BE GENERATED AT PERSISTENCE TIME ObjetosCambioPK ocPK = new ObjetosCambioPK(); ocPK.setIdObjeto(objeto.getIdObjeto()); objetosCambio.setId(ocPK); ocList.add(objetosCambio); } cambio.setObjetosCambioList(ocList); tcLocal.persistEntity(cambio); return "exito"; } catch (NamingException e) { // TODO e.printStackTrace(); } return null; } ERROR: 15:23:25,717 WARN [JDBCExceptionReporter] SQL Error: 1400, SQLState: 23000 15:23:25,717 ERROR [JDBCExceptionReporter] ORA-01400: no se puede realizar una inserción NULL en ("CDC"."OBJETOS_CAMBIO"."ID_CAMBIO") 15:23:25,717 WARN [JDBCExceptionReporter] SQL Error: 1400, SQLState: 23000 15:23:25,717 ERROR [JDBCExceptionReporter] ORA-01400: no se puede realizar una inserción NULL en ("CDC"."OBJETOS_CAMBIO"."ID_CAMBIO") 15:23:25,717 ERROR [AbstractFlushingEventListener] Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365) at org.hibernate.ejb.AbstractEntityManagerImpl$1.beforeCompletion(AbstractEntityManagerImpl.java:504) at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:101) at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:269) at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:89) at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:177) at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1423) at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:137) at com.arjuna.ats.jbossatx.BaseTransactionManagerDelegate.commit(BaseTransactionManagerDelegate.java:75) at org.jboss.aspects.tx.TxPolicy.endTransaction(TxPolicy.java:170) at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:87) at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:190) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:76) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.tx.NullInterceptor.invoke(NullInterceptor.java:42) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.security.Ejb3AuthenticationInterceptorv2.invoke(Ejb3AuthenticationInterceptorv2.java:186) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:41) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.BlockContainerShutdownInterceptor.invoke(BlockContainerShutdownInterceptor.java:67) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.aspects.currentinvocation.CurrentInvocationInterceptor.invoke(CurrentInvocationInterceptor.java:67) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.ejb3.session.SessionSpecContainer.invoke(SessionSpecContainer.java:176) at org.jboss.ejb3.session.SessionSpecContainer.invoke(SessionSpecContainer.java:216) at org.jboss.ejb3.proxy.impl.handler.session.SessionProxyInvocationHandlerBase.invoke(SessionProxyInvocationHandlerBase.java:207) at org.jboss.ejb3.proxy.impl.handler.session.SessionProxyInvocationHandlerBase.invoke(SessionProxyInvocationHandlerBase.java:164) at $Proxy298.persistEntity(Unknown Source) at backing.SolicitudCambio.generarCambio(SolicitudCambio.java:521) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:146) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:92) at javax.faces.component.UICommand.broadcast(UICommand.java:332) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:287) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:401) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:95) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:245) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:110) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:213) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:301) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.BatchUpdateException: ORA-01400: no se puede realizar una inserción NULL en ("CDC"."OBJETOS_CAMBIO"."ID_CAMBIO") Thanks in advance! JM.-

    Read the article

  • MvcExtensions - PerRequestTask

    - by kazimanzurrashid
    In the previous post, we have seen the BootstrapperTask which executes when the application starts and ends, similarly there are times when we need to execute some custom logic when a request starts and ends. Usually, for this kind of scenario we create HttpModule and hook the begin and end request events. There is nothing wrong with this approach, except HttpModules are not at all IoC containers friendly, also defining the HttpModule execution order is bit cumbersome, you either have to modify the machine.config or clear the HttpModules and add it again in web.config. Instead, you can use the PerRequestTask which is very much container friendly as well as supports execution orders. Lets few examples where it can be used. Remove www Subdomain Lets say we want to remove the www subdomain, so that if anybody types http://www.mydomain.com it will automatically redirects to http://mydomain.com. public class RemoveWwwSubdomain : PerRequestTask { public RemoveWww() { Order = DefaultOrder - 1; } protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext) { const string Prefix = "http://www."; Check.Argument.IsNotNull(executionContext, "executionContext"); HttpContextBase httpContext = executionContext.HttpContext; string url = httpContext.Request.Url.ToString(); bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); bool shouldContinue = true; if (startsWith3W) { string newUrl = "http://" + url.Substring(Prefix.Length); HttpResponseBase response = httpContext.Response; response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.Status = "301 Moved Permanently"; response.RedirectLocation = newUrl; response.SuppressContent = true; shouldContinue = false; } return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break; } } As you can see, first, we are setting the order so that we do not have to execute the remaining tasks of the chain when we are redirecting, next in the ExecuteCore, we checking the whether www is present, if present we are sending a permanently moved http status code and breaking the task execution chain otherwise we are continuing with the chain. Blocking IP Address Lets take another scenario, your application is hosted in a shared hosting environment where you do not have the permission to change the IIS setting and you want to block certain IP addresses from visiting your application. Lets say, you maintain a list of IP address in database/xml files which you want to block, you have a IBannedIPAddressRepository service which is used to match banned IP Address. public class BlockRestrictedIPAddress : PerRequestTask { protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext) { bool shouldContinue = true; HttpContextBase httpContext = executionContext.HttpContext; if (!httpContext.Request.IsLocal) { string ipAddress = httpContext.Request.UserHostAddress; HttpResponseBase httpResponse = httpContext.Response; if (executionContext.ServiceLocator.GetInstance<IBannedIPAddressRepository>().IsMatching(ipAddress)) { httpResponse.StatusCode = (int)HttpStatusCode.Forbidden; httpResponse.StatusDescription = "IPAddress blocked."; shouldContinue = false; } } return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break; } } Managing Database Session Now, let see how it can be used to manage NHibernate session, assuming that ISessionFactory of NHibernate is already registered in our container. public class ManageNHibernateSession : PerRequestTask { private ISession session; protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext) { ISessionFactory factory = executionContext.ServiceLocator.GetInstance<ISessionFactory>(); session = factory.OpenSession(); return TaskContinuation.Continue; } protected override void DisposeCore() { session.Close(); session.Dispose(); } } As you can see PerRequestTask can be used to execute small and precise tasks in the begin/end request, certainly if you want to execute other than begin/end request there is no other alternate of HttpModule. That’s it for today, in the next post, we will discuss about the Action Filters, so stay tuned.

    Read the article

  • Multiple Zend application code organisation

    - by user966936
    For the past year I have been working on a series of applications all based on the Zend framework and centered on a complex business logic that all applications must have access to even if they don't use all (easier than having multiple library folders for each application as they are all linked together with a common center). Without going into much detail about what the project is specifically about, I am looking for some input (as I am working on the project alone) on how I have "grouped" my code. I have tried to split it all up in such a way that it removes dependencies as much as possible. I'm trying to keep it as decoupled as I logically can, so in 12 months time when my time is up anyone else coming in can have no problem extending on what I have produced. Example structure: applicationStorage\ (contains all applications and associated data) applicationStorage\Applications\ (contains the applications themselves) applicationStorage\Applications\external\ (application grouping folder) (contains all external customer access applications) applicationStorage\Applications\external\site\ (main external customer access application) applicationStorage\Applications\external\site\Modules\ applicationStorage\Applications\external\site\Config\ applicationStorage\Applications\external\site\Layouts\ applicationStorage\Applications\external\site\ZendExtended\ (contains extended Zend classes specific to this application example: ZendExtended_Controller_Action extends zend_controller_Action ) applicationStorage\Applications\external\mobile\ (mobile external customer access application different workflow limited capabilities compared to full site version) applicationStorage\Applications\internal\ (application grouping folder) (contains all internal company applications) applicationStorage\Applications\internal\site\ (main internal application) applicationStorage\Applications\internal\mobile\ (mobile access has different flow and limited abilities compared to main site version) applicationStorage\Tests\ (contains PHP unit tests) applicationStorage\Library\ applicationStorage\Library\Service\ (contains all business logic, services and servicelocator; these are completely decoupled from Zend framework and rely on models' interfaces) applicationStorage\Library\Zend\ (Zend framework) applicationStorage\Library\Models\ (doesn't know services but is linked to Zend framework for DB operations; contains model interfaces and model datamappers for all business objects; examples include Iorder/IorderMapper, Iworksheet/IWorksheetMapper, Icustomer/IcustomerMapper) (Note: the Modules, Config, Layouts and ZendExtended folders are duplicated in each application folder; but i have omitted them as they are not required for my purposes.) For the library this contains all "universal" code. The Zend framework is at the heart of all applications, but I wanted my business logic to be Zend-framework-independent. All model and mapper interfaces have no public references to Zend_Db but actually wrap around it in private. So my hope is that in the future I will be able to rewrite the mappers and dbtables (containing a Models_DbTable_Abstract that extends Zend_Db_Table_Abstract) in order to decouple my business logic from the Zend framework if I want to move my business logic (services) to a non-Zend framework environment (maybe some other PHP framework). Using a serviceLocator and registering the required services within the bootstrap of each application, I can use different versions of the same service depending on the request and which application is being accessed. Example: all external applications will have a service_auth_External implementing service_auth_Interface registered. Same with internal aplications with Service_Auth_Internal implementing service_auth_Interface Service_Locator::getService('Auth'). I'm concerned I may be missing some possible problems with this. One I'm half-thinking about is a config.ini file for all externals, then a separate application config.ini overriding or adding to the global external config.ini. If anyone has any suggestions I would be greatly appreciative. I have used contextswitching for AJAX functions within the individual applications, but there is a big chance both external and internal will get web services created for them. Again, these will be separated due to authorization and different available services. \applicationstorage\Applications\internal\webservice \applicationstorage\Applications\external\webservice

    Read the article

  • Using Prism with Ninject

    - by stiank81
    Is anyone out there using the Prism framework with Ninject instead of Unity? I need some functionality Unity isn't supporting yet, and I've decided to switch the IoC container to Ninject. I'm struggling a bit with the replace though.. What I need to use from Prism is the EventAggregator and the RegionManager. I have seen this sample that actually does the replace, but this is written for an older version of Prism, and several of the classes seems to have changed etc. So I ended up all confused after looking doing some effort in trying to rewrite it. So - my question is basically: How can I replace Unity with Ninject? What are the necessary steps? Initially I assumed I could write a simple bootstrapper that creates and configures a Ninject container and uses this to resolve all other objects. I bind IEventAggregator to EventAggregator and IRegionManager to RegionManager, but it fails when creating the Shell and the RegionManager.CreateRegion is called. Problem is that it seems like I need to set a ServiceLocator somewhere as it fails on this line: IServiceLocator locator = ServiceLocator.Current; Any ideas and tips along the way?

    Read the article

  • Getting Started with Prism (aka Composite Application Guidance for WPF and Silverlight)

    - by dotneteer
    Overview Prism is a framework from the Microsoft Patterns and Practice team that allow you to create WPF and Silverlight in a modular way. It is especially valuable for larger projects in which a large number of developers can develop in parallel. Prism achieves its goal by supplying several services: · Dependency Injection (DI) and Inversion of control (IoC): By using DI, Prism takes away the responsibility of instantiating and managing the life time of dependency objects from individual components to a container. Prism relies on containers to discover, manage and compose large number of objects. By varying the configuration, the container can also inject mock objects for unit testing. Out of the box, Prism supports Unity and MEF as container although it is possible to use other containers by subclassing the Bootstrapper class. · Modularity and Region: Prism supplies the framework to split application into modules from the application shell. Each module is a library project that contains both UI and code and is responsible to initialize itself when loaded by the shell. Each window can be further divided into regions. A region is a user control with associated model. · Model, view and view-model (MVVM) pattern: Prism promotes the user MVVM. The use of DI container makes it much easier to inject model into view. WPF already has excellent data binding and commanding mechanism. To be productive with Prism, it is important to understand WPF data binding and commanding well. · Event-aggregation: Prism promotes loosely coupled components. Prism discourages for components from different modules to communicate each other, thus leading to dependency. Instead, Prism supplies an event-aggregation mechanism that allows components to publish and subscribe events without knowing each other. Architecture In the following, I will go into a little more detail on the services provided by Prism. Bootstrapper In a typical WPF application, application start-up is controls by App.xaml and its code behind. The main window of the application is typically specified in the App.xaml file. In a Prism application, we start a bootstrapper in the App class and delegate the duty of main window to the bootstrapper. The bootstrapper will start a dependency-injection container so all future object instantiations are managed by the container. Out of box, Prism provides the UnityBootstrapper and MefUnityBootstrapper abstract classes. All application needs to either provide a concrete implementation of one of these bootstrappers, or alternatively, subclass the Bootstrapper class with another DI container. A concrete bootstrapper class must implement the CreateShell method. Its responsibility is to resolve and create the Shell object through the DI container to serve as the main window for the application. The other important method to override is ConfigureModuleCatalog. The bootstrapper can register modules for the application. In a more advance scenario, an application does not have to know all its modules at compile time. Modules can be discovered at run time. Readers to refer to one of the Open Modularity Quick Starts for more information. Modules Once modules are registered with or discovered by Prism, they are instantiated by the DI container and their Initialize method is called. The DI container can inject into a module a region registry that implements IRegionViewRegistry interface. The module, in its Initialize method, can then call RegisterViewWithRegion method of the registry to register its regions. Regions Regions, once registered, are managed by the RegionManager. The shell can then load regions either through the RegionManager.RegionName attached property or dynamically through code. When a view is created by the region manager, the DI container can inject view model and other services into the view. The view then has a reference to the view model through which it can interact with backend services. Service locator Although it is possible to inject services into dependent classes through a DI container, an alternative way is to use the ServiceLocator to retrieve a service on demard. Prism supplies a service locator implementation and it is possible to get an instance of the service by calling: ServiceLocator.Current.GetInstance<IServiceType>() Event aggregator Prism supplies an IEventAggregator interface and implementation that can be injected into any class that needs to communicate with each other in a loosely-coupled fashion. The event aggregator uses a publisher/subscriber model. A class can publishes an event by calling eventAggregator.GetEvent<EventType>().Publish(parameter) to raise an event. Other classes can subscribe the event by calling eventAggregator.GetEvent<EventType>().Subscribe(EventHandler, other options). Getting started The easiest way to get started with Prism is to go through the Prism Hands-On labs and look at the Hello World QuickStart. The Hello World QuickStart shows how bootstrapper, modules and region works. Next, I would recommend you to look at the Stock Trader Reference Implementation. It is a more in depth example that resemble we want to set up an application. Several other QuickStarts cover individual Prism services. Some scenarios, such as dynamic module discovery, are more advanced. Apart from the official prism document, you can get an overview by reading Glen Block’s MSDN Magazine article. I have found the best free training material is from the Boise Code Camp. To be effective with Prism, it is important to understands key concepts of WPF well first, such as the DependencyProperty system, data binding, resource, theme and ICommand. It is also important to know your DI container of choice well. I will try to explorer these subjects in depth in the future. Testimony Recently, I worked on a desktop WPF application using Prism. I had a wonderful experience with Prism. The Prism is flexible enough even in the presence of third party controls such as Telerik WPF controls. We have never encountered any significant obstacle.

    Read the article

  • ActionScript/Flex ArrayCollection of Number objects to Java Collection<Long> using BlazeDS

    - by Justin
    Hello, I am using Flex 3 and make a call through a RemoteObject to a Java 1.6 method and exposed with BlazeDS and Spring 2.5.5 Integration over a SecureAMFChannel. The ActionScript is as follows (this code is an example of the real thing which is on a separate dev network); import com.adobe.cairngorm.business.ServiceLocator; import mx.collections.ArrayCollection; import mx.rpc.remoting.RemoteObject; import mx.rpc.IResponder; public class MyClass implements IResponder { private var service:RemoteObject = ServiceLocator.getInstance().getRemoteOjbect("mySerivce"); public MyClass() { [ArrayElementType("Number")] private var myArray:ArrayCollection; var id1:Number = 1; var id2:Number = 2; var id3:Number = 3; myArray = new ArrayCollection([id1, id2, id3]); getData(myArray); } public function getData(myArrayParam:ArrayCollection):void { var token:AsyncToken = service.getData(myArrayParam); token.addResponder(this.responder); //Assume responder implementation method exists and works } } This will make a call, once created to the service Java class which is exposed through BlazeDS (assume the mechanics work because they do for all other calls not involving Collection parameters). My Java service class looks like this; public class MySerivce { public Collection<DataObjectPOJO> getData(Collection<Long> myArrayParam) { //The following line is never executed and throws an exception for (Long l : myArrayParam) { System.out.println(l); } } } The exception that is thrown is a ClassCastException saying that a java.lang.Integer cannot be cast to a java.lang.Long. I worked around this issue by looping through the collection using Object instead, checking to see if it is an Integer, cast it to one, then do a .longValue() on it then add it to a temp ArraList. Yuk. The big problem is my application is supposed to handle records in the billions from a DB and the id will overflow the 2.147 billion limit of an integer. I would love to have BlazeDS or the JavaAdapter in it, translate the ActionScript Number to a Long as specified in the method. I hate that even though I use the generic the underlying element type of the collection is an Integer. If this was straight Java, it wouldn't compile. Any ideas are appreciated. Solutions are even better! :)

    Read the article

  • How is this Quartz Cron Expression executed

    - by n002213f
    I have a the following; private String cronExpression = ""; private final String jobID = "MyJObID"; ... Scheduler scheduler = ServiceLocator.getInstance().getScheduler(); CronTrigger trigger = new CronTrigger(jobID , Scheduler.DEFAULT_GROUP, cronExpression); JobDetail jobDetail = new JobDetail(jobID , Scheduler.DEFAULT_GROUP, MyJob.class); scheduler.scheduleJob(jobDetail, trigger); My question is when is this job triggered for the empty cron expression?

    Read the article

  • Unity and Object Creation

    - by William
    I am using unity as my IoC container. I am trying to implement a type of IProviderRepository. The concrete implementation has a constructor that accepts a type of IRepository. When I remove the constructor parameter from the concrete implementation everything works fine. I am sure the container is wired correctly. When I try to create the concrete object with the constructor I receive the following error: "The current build operation (build key Build Key[EMRGen.Infrastructure.Data.IRepository1[EMRGen.Model.Provider.Provider], null]) failed: The current type, EMRGen.Infrastructure.Data.IRepository1[EMRGen.Model.Provider.Provider], is an interface and cannot be constructed. Are you missing a type mapping? (Strategy type BuildPlanStrategy, index 3)". Is it possible to achieve the above mention functionality with Unity? Namely have Unity infer a concrete type from the Interface and also inject the constructor of the concrete type with the appropriate concrete object based on constructor parameters. Below is sample of my types defined in Unity and a skeleton class listing for what I want to achieve. IProviderRepository is implemented by ProviderRepository which has a constructor that expects a type of IRepository. <typeAlias alias="ProviderRepositoryInterface" type="EMRGen.Model.Provider.IProviderRepository, EMRGen.Model" /> <typeAlias alias="ProviderRepositoryConcrete" type="EMRGen.Infrastructure.Repositories.Providers.ProviderRepository, EMRGen.Infrastructure.Repositories" /> <typeAlias alias="ProviderGenericRepositoryInterface" type="EMRGen.Infrastructure.Data.IRepository`1[[EMRGen.Model.Provider.IProvider, EMRGen.Model]], EMRGen.Infrastructure" /> <typeAlias alias="ProviderGenericRepositoryConcrete" type="EMRGen.Infrastructure.Repositories.EntityFramework.ApplicationRepository`1[[EMRGen.Model.Provider.Provider, EMRGen.Model]], EMRGen.Infrastructure.Repositories" /> <!-- Provider Mapping--> <typeAlias alias="ProviderInterface" type="EMRGen.Model.Provider.IProvider, EMRGen.Model" /> <typeAlias alias="ProviderConcrete" type="EMRGen.Model.Provider.Doctor, EMRGen.Model" /> //Illustrate the call being made inside my class public class PrescriptionService { PrescriptionService() { IUnityContainer uc = UnitySingleton.Instance.Container; UnityServiceLocator unityServiceLocator = new UnityServiceLocator(uc); ServiceLocator.SetLocatorProvider(() => unityServiceLocator); IProviderRepository pRepository = ServiceLocator.Current.GetInstance<IProviderRepository>(); } } public class GenericRepository<IProvider> : IRepository<IProvider> { } public class ProviderRepository : IProviderRepository { private IRepository<IProvider> _genericProviderRepository; //Explict public default constructor public ProviderRepository(IRepository<IProvider> genericProviderRepository) { _genericProviderRepository = genericProviderRepository; } }

    Read the article

1 2  | Next Page >