Search Results

Search found 1962 results on 79 pages for 'moose factory'.

Page 11/79 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • [[alloc] init] as a factory method

    - by iter
    I want to initialize an instance of one of the subclasses of a superclass depending on the arguments to init: [[Vehicle alloc] initWithItinerary: shortWay]; // returns a bicycle [[Vehicle alloc] initWithItinerary: longWay]; // returns a car I can't find examples of code like this. I wonder if this is not idiomatic in Objective C, or I simply am not looking in the right places.

    Read the article

  • An RMIPRoxyFactoryBean factory in Spring?

    - by Robert Munteanu
    I'm currently using a Spring RmiProxyFactoryBean to access remote services. Since requirements have changed, I need to specify at runtime a different host - there can be many of them - , but the remoteServiceInterface and the non-host components of the remoteServiceUrl remain the same. Conceptually speaking, I'd see a bean definition similar to: <bean class="org.springframework.remoting.rmi.RmiProxyFactoryBeanFactory"> <property name="serviceInterface" value="xxx"/> <property name="serviceUrl" value="rmi://#{HOST}:1099/ServiceUrl"/> </bean> which exposes a Object getServiceFor(String hostName); Is there such a service available with Spring? Alternatively, do you see another way of doing this? Please note that the host list will not be known at compile or startup time, so I can't generate it in the xml file.

    Read the article

  • ASP.NET MVC based CMS - dynamic generation of form helpers

    - by user252160
    I am working on an ASP.NET MVC based CMS that presents a rather extreme case. The system must allow the user to add custom content types based on different fields, and for every field, one can add options and validations. The thing is that everything is stored in a complex DB and extracted at runtime using LINQ. I am pretty fresh with ASPNET MVC so the following dilemma came to mind How should I make the content creation view so that form helpers are not predefined int he view code but are loaded based on the type of the field ? Do I have to create a factory class that checks the value of the type property of the field, and then returns a helper based on that or there's a better way to do it. This one seems pretty rigid to me , because anytime I make a change in the Fieldtypes table, I will have to make sure to create a check for that new type too.

    Read the article

  • How to generate tests with different names in testng, java?

    - by Ula Karzelek
    I'm using testng to run selenium based tests in java. I have a bunch of repeated tests. Generally they do all the same except of test name and one parameter. I want to automate generation of it. I was thinking about using factory. Is there a way to generate tests with different name? What would be the best approach to this? As for now I have something like below and I want to create 10 tests like LinkOfInterestIsActiveAfterClick @Test(dependsOnGroups="loggedin") public class SmokeTest extends BrowserStartingStoping{ public void LinkOfInterestIsActiveAfterClick(){ String link = "link_of_interest"; browser.click("*",link); Assert.assertTrue(browser.isLinkActive(link)); } } My xml suite is auto-generated from java code. test names are crucial for logging which link is active, and which one is not.

    Read the article

  • How do I get my dependenices inject using @Configurable in conjunction with readResolve()

    - by bmatthews68
    The framework I am developing for my application relies very heavily on dynamically generated domain objects. I recently started using Spring WebFlow and now need to be able to serialize my domain objects that will be kept in flow scope. I have done a bit of research and figured out that I can use writeReplace() and readResolve(). The only catch is that I need to look-up a factory in the Spring context. I tried to use @Configurable(preConstruction = true) in conjunction with the BeanFactoryAware marker interface. But beanFactory is always null when I try to use it in my createEntity() method. Neither the default constructor nor the setBeanFactory() injector are called. Has anybody tried this or something similar? I have included relevant class below. Thanks in advance, Brian /* * Copyright 2008 Brian Thomas Matthews Limited. * All rights reserved, worldwide. * * This software and all information contained herein is the property of * Brian Thomas Matthews Limited. Any dissemination, disclosure, use, or * reproduction of this material for any reason inconsistent with the * express purpose for which it has been disclosed is strictly forbidden. */ package com.btmatthews.dmf.domain.impl.cglib; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.util.StringUtils; import com.btmatthews.dmf.domain.IEntity; import com.btmatthews.dmf.domain.IEntityFactory; import com.btmatthews.dmf.domain.IEntityID; import com.btmatthews.dmf.spring.IEntityDefinitionBean; /** * This class represents the serialized form of a domain object implemented * using CGLib. The readResolve() method recreates the actual domain object * after it has been deserialized into Serializable. You must define * &lt;spring-configured/&gt; in the application context. * * @param <S> * The interface that defines the properties of the base domain * object. * @param <T> * The interface that defines the properties of the derived domain * object. * @author <a href="mailto:[email protected]">Brian Matthews</a> * @version 1.0 */ @Configurable(preConstruction = true) public final class SerializedCGLibEntity<S extends IEntity<S>, T extends S> implements Serializable, BeanFactoryAware { /** * Used for logging. */ private static final Logger LOG = LoggerFactory .getLogger(SerializedCGLibEntity.class); /** * The serialization version number. */ private static final long serialVersionUID = 3830830321957878319L; /** * The application context. Note this is not serialized. */ private transient BeanFactory beanFactory; /** * The domain object name. */ private String entityName; /** * The domain object identifier. */ private IEntityID<S> entityId; /** * The domain object version number. */ private long entityVersion; /** * The attributes of the domain object. */ private HashMap<?, ?> entityAttributes; /** * The default constructor. */ public SerializedCGLibEntity() { SerializedCGLibEntity.LOG .debug("Initializing with default constructor"); } /** * Initialise with the attributes to be serialised. * * @param name * The entity name. * @param id * The domain object identifier. * @param version * The entity version. * @param attributes * The entity attributes. */ public SerializedCGLibEntity(final String name, final IEntityID<S> id, final long version, final HashMap<?, ?> attributes) { SerializedCGLibEntity.LOG .debug("Initializing with parameterized constructor"); this.entityName = name; this.entityId = id; this.entityVersion = version; this.entityAttributes = attributes; } /** * Inject the bean factory. * * @param factory * The bean factory. */ public void setBeanFactory(final BeanFactory factory) { SerializedCGLibEntity.LOG.debug("Injected bean factory"); this.beanFactory = factory; } /** * Called after deserialisation. The corresponding entity factory is * retrieved from the bean application context and BeanUtils methods are * used to initialise the object. * * @return The initialised domain object. * @throws ObjectStreamException * If there was a problem creating or initialising the domain * object. */ public Object readResolve() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Transforming deserialized object"); final T entity = this.createEntity(); entity.setId(this.entityId); try { PropertyUtils.setSimpleProperty(entity, "version", this.entityVersion); for (Map.Entry<?, ?> entry : this.entityAttributes.entrySet()) { PropertyUtils.setSimpleProperty(entity, entry.getKey() .toString(), entry.getValue()); } } catch (IllegalAccessException e) { throw new InvalidObjectException(e.getMessage()); } catch (InvocationTargetException e) { throw new InvalidObjectException(e.getMessage()); } catch (NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } return entity; } /** * Lookup the entity factory in the application context and create an * instance of the entity. The entity factory is located by getting the * entity definition bean and using the factory registered with it or * getting the entity factory. The name used for the definition bean lookup * is ${entityName}Definition while ${entityName} is used for the factory * lookup. * * @return The domain object instance. * @throws ObjectStreamException * If the entity definition bean or entity factory were not * available. */ @SuppressWarnings("unchecked") private T createEntity() throws ObjectStreamException { SerializedCGLibEntity.LOG.debug("Getting domain object factory"); // Try to use the entity definition bean final IEntityDefinitionBean<S, T> entityDefinition = (IEntityDefinitionBean<S, T>)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Definition", IEntityDefinitionBean.class); if (entityDefinition != null) { final IEntityFactory<S, T> entityFactory = entityDefinition .getFactory(); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via enity definition bean"); return entityFactory.create(); } } // Try to use the entity factory final IEntityFactory<S, T> entityFactory = (IEntityFactory<S, T>)this.beanFactory .getBean(StringUtils.uncapitalize(this.entityName) + "Factory", IEntityFactory.class); if (entityFactory != null) { SerializedCGLibEntity.LOG .debug("Domain object factory obtained via direct look-up"); return entityFactory.create(); } // Neither worked! SerializedCGLibEntity.LOG.warn("Cannot find domain object factory"); throw new InvalidObjectException( "No entity definition or factory found for " + this.entityName); } }

    Read the article

  • Factories, or Dependency Injection for object instantiation in WCF, when coding against an interface

    - by Saajid Ismail
    Hi I am writing a client/server application, where the client is a Windows Forms app, and the server is a WCF service hosted in a Windows Service. Note that I control both sides of the application. I am trying to implement the practice of coding against an interface: i.e. I have a Shared assembly which is referenced by the client application. This project contains my WCF ServiceContracts and interfaces which will be exposed to clients. I am trying to only expose interfaces to the clients, so that they are only dependant on a contract, not any specific implementation. One of the reasons for doing this is so that I can have my service implementation, and domain change at any time without having to recompile and redeploy the clients. The interfaces/contracts will in this case not change. I only need to recompile and redeploy my WCF service. The design issue I am facing now, is: on the client, how do I create new instances of objects, e.g. ICustomer, if the client doesn't know about the Customer concrete implementation? I need to create a new customer to be saved to the DB. Do I use dependency injection, or a Factory class to instantiate new objects, or should I just allow the client to create new instances of concrete implementations? I am not doing TDD, and I will typically only have one implementation of ICustomer or any other exposed interface.

    Read the article

  • error: expected constructor, destructor, or type conversion before '(' token

    - by jonathanasdf
    include/TestBullet.h:12: error: expected constructor, destructor, or type conver sion before '(' token I hate C++ error messages... lol ^^ Basically, I'm following what was written in this post to try to create a factory class for bullets so they can be instantiated from a string, which will be parsed from an xml file, because I don't want to have a function with a switch for all of the classes because that looks ugly. Here is my TestBullet.h: #pragma once #include "Bullet.h" #include "BulletFactory.h" class TestBullet : public Bullet { public: void init(BulletData& bulletData); void update(); }; REGISTER_BULLET(TestBullet); <-- line 12 And my BulletFactory.h: #pragma once #include <string> #include <map> #include "Bullet.h" #define REGISTER_BULLET(NAME) BulletFactory::reg<NAME>(#NAME) #define REGISTER_BULLET_ALT(NAME, CLASS) BulletFactory::reg<CLASS>(NAME) template<typename T> Bullet * create() { return new T; } struct BulletFactory { typedef std::map<std::string, Bullet*(*)()> bulletMapType; static bulletMapType map; static Bullet * createInstance(char* s) { std::string str(s); bulletMapType::iterator it = map.find(str); if(it == map.end()) return 0; return it->second(); } template<typename T> static void reg(std::string& s) { map.insert(std::make_pair(s, &create<T>)); } }; Thanks in advance.

    Read the article

  • How to implement an ID field on a POCO representing an Identity field in MS SQL?

    - by Dr. Zim
    If I have a Domain Model that has an ID that maps to a SQL identity column, what does the POCO look like that contains that field? Candidate 1: Allows anyone to set and get the ID. I don't think we want anyone setting the ID except the Repository, from the SQL table. public class Thing { public int ID {get;set;} } Candidate 2: Allows someone to set the ID upon creation, but we won't know the ID until after we create the object (factory creates a blank Thing object where ID = 0 until we persist it). How would we set the ID after persisting? public class Thing { public Thing () : This (ID: 0) {} public Thing (int ID) { this.ID = ID } private int _ID; public int ID { get { return this.ID;}; } Candidate 3: Methods to set ID? Somehow we would need to allow the Repository to set the ID without allowing the consumer to change it. Any ideas? Is this barking up the wrong tree? Do we send the object to the Repository, save it, throw it away, then create a new object from the loaded version and return that as a new object?

    Read the article

  • How to implement an ID field on a POCO representing an Identity field in SQL Server?

    - by Dr. Zim
    If I have a Domain Model that has an ID that maps to a SQL Server identity column, what does the POCO look like that contains that field? Candidate 1: Allows anyone to set and get the ID. I don't think we want anyone setting the ID except the Repository, from the SQL table. public class Thing { public int ID {get;set;} } Candidate 2: Allows someone to set the ID upon creation, but we won't know the ID until after we create the object (factory creates a blank Thing object where ID = 0 until we persist it). How would we set the ID after persisting? public class Thing { public Thing () : This (ID: 0) {} public Thing (int ID) { this.ID = ID } private int _ID; public int ID { get { return this.ID;}; } Candidate 3: Methods to set ID? Somehow we would need to allow the Repository to set the ID without allowing the consumer to change it. Any ideas? Is this barking up the wrong tree? Do we send the object to the Repository, save it, throw it away, then create a new object from the loaded version and return that as a new object?

    Read the article

  • Is there a pattern that allows a constructor to be called only from a specific factory and from nowh

    - by willem
    We have a class, say LegacyUserSettingsService. LegacyUserSettingsService implements an interface, IUserSettingsService. You can get an instance of the IUserSettingsService by calling our ApplicationServicesFactory. The factory uses Spring.NET to construct the concrete LegacyUserSettingsService. The trouble is that new developers sometimes do their own thing and construct new instances of the LegacyUserSettingsService directly (instead of going via the factory). Is there a way to protect the constructor of the concrete class so it can only be called from the factory? A well-known pattern perhaps? Note that the concrete class resides in a different assembly (separate from the Factory's assembly, so the internal keyword is not a solution). The factory assembly references the other assembly that contains the concrete class. Any ideas?

    Read the article

  • junit test error - ClassCastException

    - by Josepth Vodary
    When trying to run a junit test I get the following error - java.lang.ClassCastException: business.Factory cannot be cast to services.itemservice.IItemsService at business.ItemManager.get(ItemManager.java:56) at business.ItemMgrTest.testGet(ItemMgrTest.java:49) The specific test that is causing the problem is @Test public void testGet() { Assert.assertTrue(itemmgr.get(items)); } The code it is testing is... public boolean get(Items item) { boolean gotItems = false; Factory factory = Factory.getInstance(); @SuppressWarnings("static-access") IItemsService getItem = (IItemsService)factory.getInstance(); try { getItem.getItems("pens", 15, "red", "gel"); gotItems = true; } catch (ItemNotFoundException e) { // catch e.printStackTrace(); System.out.println("Error - Item Not Found"); } return gotItems; } The test to store items, which is nearly identical, works just fine... The factory class is.. public class Factory { private Factory() {} private static Factory Factory = new Factory(); public static Factory getInstance() {return Factory;} public static IService getService(String serviceName) throws ServiceLoadException { try { Class<?> c = Class.forName(getImplName(serviceName)); return (IService)c.newInstance(); } catch (Exception e) { throw new ServiceLoadException(serviceName + "not loaded"); } } private static String getImplName (String serviceName) throws Exception { java.util.Properties props = new java.util.Properties(); java.io.FileInputStream fis = new java.io.FileInputStream("config\\application.properties"); props.load(fis); fis.close(); return props.getProperty(serviceName); } }

    Read the article

  • Psuedo-Backwards Builder Pattern?

    - by Avid Aardvark
    In a legacy codebase I have a very large class with far too many fields/responsibilities. Imagine this is a Pizza object. It has highly granular fields like: hasPepperoni hasSausage hasBellPeppers I know that when these three fields are true, we have a Supreme pizza. However, this class is not open for extension or change, so I can't add a PizzaType, or isSupreme(), etc. Folks throughout the codebase duplicate the same "if(a && b && c) then isSupreme)" logic all over place. This issue comes up for quite a few concepts, so I'm looking for a way to deconstruct this object into many subobjects, e.g. a pseudo-backwards Builder Pattern. PizzaType pizzaType = PizzaUnbuilder.buildPizzaType(Pizza); //PizzaType.SUPREME Dough dough = PizzaUnbuilder.buildDough(Pizza); Is this the right approach? Is there a pattern for this already? Thanks!

    Read the article

  • realloc() & ARC

    - by RynoB
    How would I be able to rewrite the the following utility class to get all the class string values for a specific type - using the objective-c runtime functions as shown below? The ARC documentation specifically states that realloc should be avoided and I also get the following compiler error on this this line: classList = realloc(classList, sizeof(Class) * numClasses); "Implicit conversion of a non-Objective-C pointer type 'void *' to '__unsafe_unretained Class *' is disallowed with ARC" The the below code is a reference to the original article which can be found here. + (NSArray *)classStringsForClassesOfType:(Class)filterType { int numClasses = 0, newNumClasses = objc_getClassList(NULL, 0); Class *classList = NULL; while (numClasses < newNumClasses) { numClasses = newNumClasses; classList = realloc(classList, sizeof(Class) * numClasses); newNumClasses = objc_getClassList(classList, numClasses); } NSMutableArray *classesArray = [NSMutableArray array]; for (int i = 0; i < numClasses; i++) { Class superClass = classList[i]; do { superClass = class_getSuperclass(superClass); if (superClass == filterType) { [classesArray addObject:NSStringFromClass(classList[i])]; break; } } while (superClass); } free(classList); return classesArray; } Your help will be much appreciated. Thanks

    Read the article

  • Spring: Using "Lookup method injection" for my ThreadFactory looks not scalable.

    - by Michael Bavin
    Hi, We're building a ThreadFactory so everytime a singleton controller needs a new thread, i get a new instance everytime. Looking at Lookup method injection looks good but what if we have multiple threads. like: public abstract class ThreadManager { public abstract Thread createThreadDoA(); public abstract Thread createThreadDoB(); } and config: <bean id="threadManager" class="bla.ThreadManager" singleton="true"> <lookup-method name="createThreadA" bean="threadA" /> <lookup-method name="createThreadB" bean="threadB"/> </bean> <bean id="threadA" class="bla.ThreadA"> <bean id="threadB" class="bla.ThreadB"> and usage: threadManager.createThreadA(); I don't want to create an abstract "create" method for every new threadclass. Is it possible to make this generich like: threadManager.createThread(ThreadA.class); Thank you

    Read the article

  • simple Java "service provider frameworks"?

    - by Jason S
    I refer to "service provider framework" as discussed in Chapter 2 of Effective Java, which seems like exactly the right way to handle a problem I am having, where I need to instantiate one of several classes at runtime, based on a String to select which service, and an Configuration object (essentially an XML snippet): But how do I get the individual service providers (e.g. a bunch of default providers + some custom providers) to register themselves? interface FooAlgorithm { /* methods particular to this class of algorithms */ } interface FooAlgorithmProvider { public FooAlgorithm getAlgorithm(Configuration c); } class FooAlgorithmRegistry { private FooAlgorithmRegistry() {} static private final Map<String, FooAlgorithmProvider> directory = new HashMap<String, FooAlgorithmProvider>(); static public FooAlgorithmProvider getProvider(String name) { return directory.get(serviceName); } static public boolean registerProvider(String name, FooAlgorithmProvider provider) { if (directory.containsKey(name)) return false; directory.put(name, provider); return true; } } e.g. if I write custom classes MyFooAlgorithm and MyFooAlgorithmProvider to implement FooAlgorithm, and I distribute them in a jar, is there any way to get registerProvider to be called automatically, or will my client programs that use the algorithm have to explicitly call FooAlgorithmRegistry.registerProvider() for each class they want to use?

    Read the article

  • Cap deploy doesn't work all the sudden; something to do with FactoryGirl and assets

    - by Jason Swett
    I've been cap deploying my app all throughout it development, and this last time I tried to deploy it, it didn't work. Here's what happened: * executing `deploy:assets:precompile' * executing "cd /var/www/oneteam/releases/20121006153136 && bundle exec rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile" servers: ["electricsasquatch.com"] [electricsasquatch.com] executing command ** [out :: electricsasquatch.com] rake aborted! ** [out :: electricsasquatch.com] uninitialized constant OneTeam::Application::FactoryGirl ** [out :: electricsasquatch.com] ** [out :: electricsasquatch.com] (See full trace by running task with --trace) It looks like it failed on the deploy:assets:precompile command. I don't get why that command would have tried to do anything with FactoryGirl, though. Any ideas?

    Read the article

  • ASP.NET exception gives irrelevant stack trace on YSOD, very challenging!

    - by pootow
    Here is the YSOD: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. 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.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. 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: [SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.] System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +428 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 ECommerce.PMethod.Sql.SqlConns.Open() +78 ECommerce.PMethod.Sql.SqlConns..ctor() +120 ECommerce.login.DatasInfo.Proc.UserCenter.IsLogin(String UserGUID, Int32 UserID) +49 ECommerce.login.Rules.Users.UserLogin.isLogin() +44 Config.isUserLogined() +5 Shopping_Shopping.Page_Load(Object sender, EventArgs e) +10 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +50 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627 [TypeInitializationException: The type initializer for 'ECommerce.ERP.DAL.DBConn' threw an exception.] ECommerce.ERP.DAL.DBConn.get_ConnString() +0 [ObjectDefinitionStoreException: Factory method 'System.String get_ConnString()' threw an Exception.] Spring.Objects.Factory.Support.SimpleInstantiationStrategy.Instantiate(RootObjectDefinition definition, String name, IObjectFactory factory, MethodInfo factoryMethod, Object[] arguments) +257 Spring.Objects.Factory.Support.ConstructorResolver.InstantiateUsingFactoryMethod(String name, RootObjectDefinition definition, Object[] arguments) +624 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateUsingFactoryMethod(String name, RootObjectDefinition definition, Object[] arguments) +60 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.CreateObjectInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +56 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +436 [ObjectCreationException: Error thrown by a dependency of object 'styleService' defined in 'assembly [ECommerce.Services.Impl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Services.Impl.AppContext.xml] line 56' : Initialization of object failed : Factory method 'System.String get_ConnString()' threw an Exception. while resolving 'constructor argument with name promotionservice' to 'promotionService' defined in 'assembly [ECommerce.Services.Impl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Services.Impl.AppContext.xml] line 31' while resolving 'constructor argument with name domainservice' to 'promotionDomainService' defined in 'assembly [ECommerce.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Domain.AppContext.xml] line 20' while resolving 'constructor argument with name promotionrepos' to 'promotionRepos' defined in 'assembly [ECommerce.Data.AdoNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Data.AdoNet.AppContext.xml] line 34' while resolving 'constructor argument with name connstr' to 'ECommerce.ERP.DAL.DBConn#389F399' defined in 'assembly [ECommerce.Data.AdoNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Data.AdoNet.AppContext.xml] line 34'] Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveReference(IObjectDefinition definition, String name, String argumentName, RuntimeObjectReference reference) +394 Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) +312 Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) +17 Spring.Objects.Factory.Support.ConstructorResolver.ResolveConstructorArguments(String objectName, RootObjectDefinition definition, ObjectWrapper wrapper, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) +993 Spring.Objects.Factory.Support.ConstructorResolver.AutowireConstructor(String objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, Object[] explicitArgs) +171 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.AutowireConstructor(String name, RootObjectDefinition definition, ConstructorInfo[] ctors, Object[] explicitArgs) +65 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.CreateObjectInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +161 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +636 Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +174 Spring.Objects.Factory.Support.WebObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +150 Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +990 Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name) +10 Spring.Context.Support.AbstractApplicationContext.GetObject(String name) +20 ECommerce.Common.ServiceLocator.GetService() +334 ECommerce.Mvc.Controllers.StylesController..ctor() +72 [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230 System.Activator.CreateInstance(Type type, Boolean nonPublic) +67 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80 [InvalidOperationException: An error occurred when trying to create a controller of type 'ECommerce.Mvc.Controllers.StylesController'. Make sure that the controller has a parameterless public constructor.] System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677954 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082 Question is: the first stack trace is irrelevant to others, what happened? Any ideas? Let me make this more clear: a MVC page uses the spring part trying to load a lazy-init service which constructor wants a connection string through a static property like this: <object id="promotionRepos" type="ECommerce.Data.AdoNet.Promotions.PromotionRepos, ECommerce.Data.AdoNet" lazy-init="true"> <constructor-arg name="provider"> <null /> </constructor-arg> <constructor-arg name="connStr"> <object type="ECommerce.ERP.DAL.DBConn, ECommerce.ERP.DAL" factory-method="get_ConnString" /> </constructor-arg> <property name="RefreshInterval" value="00:00:10" /> </object> the timeout part is some what irrelevent to all others. see this in the first exception: Shopping_Shopping.Page_Load(Object sender, EventArgs e) +10 it's another page at all. And also, ECommerce.PMethod.Sql.SqlConns.Open() uses its own connection string, not the one loaded by spring, it's different module from diffrent team. And I am sure the connection string is correct. And, this ysod cames up randomly. Sometimes nothing is wrong, and sometimes, it appears. I thought there could be something wrong with my database or the network/firewall, I will check it later, but now I want understand this tricky stack trace.

    Read the article

  • Dynamically register constructor methods in an AbstractFactory at compile time using C++ templates

    - by Horacio
    When implementing a MessageFactory class to instatiate Message objects I used something like: class MessageFactory { public: static Message *create(int type) { switch(type) { case PING_MSG: return new PingMessage(); case PONG_MSG: return new PongMessage(); .... } } This works ok but every time I add a new message I have to add a new XXX_MSG and modify the switch statement. After some research I found a way to dynamically update the MessageFactory at compile time so I can add as many messages as I want without need to modify the MessageFactory itself. This allows for cleaner and easier to maintain code as I do not need to modify three different places to add/remove message classes: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> class Message { protected: inline Message() {}; public: inline virtual ~Message() { } inline int getMessageType() const { return m_type; } virtual void say() = 0; protected: uint16_t m_type; }; template<int TYPE, typename IMPL> class MessageTmpl: public Message { enum { _MESSAGE_ID = TYPE }; public: static Message* Create() { return new IMPL(); } static const uint16_t MESSAGE_ID; // for registration protected: MessageTmpl() { m_type = MESSAGE_ID; } //use parameter to instanciate template }; typedef Message* (*t_pfFactory)(); class MessageFactory· { public: static uint16_t Register(uint16_t msgid, t_pfFactory factoryMethod) { printf("Registering constructor for msg id %d\n", msgid); m_List[msgid] = factoryMethod; return msgid; } static Message *Create(uint16_t msgid) { return m_List[msgid](); } static t_pfFactory m_List[65536]; }; template <int TYPE, typename IMPL> const uint16_t MessageTmpl<TYPE, IMPL >::MESSAGE_ID = MessageFactory::Register( MessageTmpl<TYPE, IMPL >::_MESSAGE_ID, &MessageTmpl<TYPE, IMPL >::Create); class PingMessage: public MessageTmpl < 10, PingMessage > {· public: PingMessage() {} virtual void say() { printf("Ping\n"); } }; class PongMessage: public MessageTmpl < 11, PongMessage > {· public: PongMessage() {} virtual void say() { printf("Pong\n"); } }; t_pfFactory MessageFactory::m_List[65536]; int main(int argc, char **argv) { Message *msg1; Message *msg2; msg1 = MessageFactory::Create(10); msg1->say(); msg2 = MessageFactory::Create(11); msg2->say(); delete msg1; delete msg2; return 0; } The template here does the magic by registering into the MessageFactory class, all new Message classes (e.g. PingMessage and PongMessage) that subclass from MessageTmpl. This works great and simplifies code maintenance but I still have some questions about this technique: Is this a known technique/pattern? what is the name? I want to search more info about it. I want to make the array for storing new constructors MessageFactory::m_List[65536] a std::map but doing so causes the program to segfault even before reaching main(). Creating an array of 65536 elements is overkill but I have not found a way to make this a dynamic container. For all message classes that are subclasses of MessageTmpl I have to implement the constructor. If not it won't register in the MessageFactory. For example commenting the constructor of the PongMessage: class PongMessage: public MessageTmpl < 11, PongMessage > { public: //PongMessage() {} /* HERE */ virtual void say() { printf("Pong\n"); } }; would result in the PongMessage class not being registered by the MessageFactory and the program would segfault in the MessageFactory::Create(11) line. The question is why the class won't register? Having to add the empty implementation of the 100+ messages I need feels inefficient and unnecessary.

    Read the article

  • Doubt about instance creation by using Spring framework ???

    - by Arthur Ronald F D Garcia
    Here goes a command object which needs to be populated from a Spring form public class Person { private String name; private Integer age; /** * on-demand initialized */ private Address address; // getter's and setter's } And Address public class Address { private String street; // getter's and setter's } Now suppose the following MultiActionController @Component public class PersonController extends MultiActionController { @Autowired @Qualifier("personRepository") private Repository<Person, Integer> personRepository; /** * mapped To /person/add */ public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Person person) throws Exception { personRepository.add(person); return new ModelAndView("redirect:/home.htm"); } } Because Address attribute of Person needs to be initialized on-demand, i need to override newCommandObject to create an instance of Person to initiaze address property. Otherwise, i will get NullPointerException @Component public class PersonController extends MultiActionController { /** * code as shown above */ @Override public Object newCommandObject(Class clazz) thorws Exception { if(clazz.isAssignableFrom(Person.class)) { Person person = new Person(); person.setAddress(new Address()); return person; } } } Ok, Expert Spring MVC and Web Flow says Options for alternate object creation include pulling an instance from a BeanFactory or using method injection to transparently return a new instance. First option pulling an instance from a BeanFactory can be written as @Override public Object newCommandObject(Class clazz) thorws Exception { /** * Will retrieve a prototype instance from ApplicationContext whose name matchs its clazz.getSimpleName() */ getApplicationContext().getBean(clazz.getSimpleName()); } But what does he want to say by using method injection to transparently return a new instance ??? Can you show how i implement what he said ??? ATT: I know this funcionality can be filled by a SimpleFormController instead of MultiActionController. But it is shown just as an example, nothing else

    Read the article

  • What's the benefit of calling new on an object instance?

    - by Geo
    I'm reading [Programming Perl][1], and I found this code snippet: sub new { my $invocant = shift; my $class = ref($invocant) || $invocant; my $self = { color => "bay", legs => 4, owner => undef, @_, # Override previous attributes }; return bless $self, $class; } With constructors like this one, what's the benefit of calling new on an object instance? I assume that it's what it's for, right? My guess is that if anyone would want to write such a constructor, he would have to add some more code that copies the attributes of the first object to the one about to be created.

    Read the article

  • Is there a design pattern for this ?

    - by ytrewq
    I have a component that needs to call a specific service depending on the input it receives. So my component has to look at the input and based on a configuration that says "for this input call this service with this data" needs to call the proper service. The services have a common signature method and a specific one (each). I thought about an abstract class that includes the signatures for all three methods. The implementation for the two services will override all three methods (throwing NotImplementedException for the methods that are not supported by current service). A component that could be initialized with a map (that for each input type will have the type of the service to be called) will also be defined. Do you have a better approach to cope this scenario ?

    Read the article

  • The ** idiom in C++ for object construction

    - by bobobobo
    In a lot of C++ API'S (COM-based ones spring to mind) that make something for you, the pointer to the object that is constructed is usually required as a ** pointer (and the function will construct and init it for you) You usually see signatures like: HRESULT createAnObject( int howbig, Object **objectYouWantMeToInitialize ) ; -- but you seldom see the new object being passed as a return value. Besides people wanting to see error codes, what is the reason for this? Is it better to use the ** pattern rather than a returned pointer for simpler operations such as: wchar_t* getUnicode( const char* src ) ; Or would this better be written as: void getUnicode( const char* src, wchar_t** dst ) ; The most important thing I can think of is to remember to free it, and the ** way, for some reason, tends to remind me that I have to deallocate it as well.

    Read the article

  • Can the Abstract Factory pattern be considered as a case of polymorphism?

    - by rogcg
    I was looking for a pattern/solution that allows me call a method as a runtime exception in a group of different methods without using Reflection. I've recently become aware of the Abstract Factory Pattern. To me, it looks so much like polymorphism, and I thought it could be a case of polymorphism but without the super class WidgetFactory, as you can see in the example of the link above. Am I correct in this assumption?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >