Search Results

Search found 597 results on 24 pages for 'constructors'.

Page 18/24 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Private Java class properties mysteriously reset between method calls....

    - by Michael Jones
    I have a very odd problem. A class property is mysteriously reset between method calls. The following code is executed so the constructor is called, then the parseConfiguration method is called. Finally, processData is called. The parseConfiguration method sets the "recursive" property to "true". However, as soon as it enters "processData", "recursive" becomes "false". This problem isn't isolated to a single class -- I have several examples of this in my code. How can this possibly be happening? I've tried initialising properties when they're declared outside any methods, I've tried initialising them in constructors... nothing works. The only complication I can think of here is that this class is invoked by an object that runs in a thread -- but here is one instance per thread, so surely no chance that threads are interfering. I've tried setting both methods to "synchronized", but this still happens. Please help! /** * This class or its superclasses are NOT threaded and don't extend Thread */ public class DirectoryAcquirer extends Manipulator { /** * @var Whether to recursively scan directories */ private boolean recursive = false; /** * Constructor */ public DirectoryAcquirer() { } /** * Constructor that initialises the configuration * * @param config * @throws InvalidConfigurationException */ public DirectoryAcquirer(HierarchicalConfiguration config) throws InvalidConfigurationException { super(config); } @Override protected void parseConfiguration() throws InvalidConfigurationException { // set whether to recurse into directories or not if (this.config.containsKey("recursive")) { // this.recursive gets set to "true" here this.recursive = this.config.getBoolean("recursive"); } } @Override public EntityCollection processData(EntityCollection data) { // here this.recursive is "false" this.logger.debug("processData: Entered method"); } }

    Read the article

  • Constructor and Destructors in C++ [Not a question] [closed]

    - by Jack
    I am using gcc. Please tell me if I am wrong - Lets say I have two classes A & B class A { public: A(){cout<<"A constructor"<<endl;} ~A(){cout<<"A destructor"<<endl;} }; class B:public A { public: B(){cout<<"B constructor"<<endl;} ~B(){cout<<"B destructor"<<endl;} }; 1) The first line in B's constructor should be a call to A's constructor ( I assume compiler automatically inserts it). Also the last line in B's destructor will be a call to A's destructor (compiler does it again). Why was it built this way? 2) When I say A * a = new B(); compiler creates a new B object and checks to see if A is a base class of B and if it is it allows 'a' to point to the newly created object. I guess that is why we don't need any virtual constructors. ( with help from @Tyler McHenry , @Konrad Rudolph) 3) When I write delete a compiler sees that a is an object of type A so it calls A's destructor leading to a problem which is solved by making A's destructor virtual. As user - Little Bobby Tables pointed out to me all destructors have the same name destroy() in memory so we can implement virtual destructors and now the call is made to B's destructor and all is well in C++ land. Please comment.

    Read the article

  • nhibernate : Repository Session Management

    - by frosty
    At the moment my repository has 2 constructors. When i call these from my mvc website i am alway calling first constructor and thus opening a new session. Should i been passing in the session. How should i be doing this. public CompanyRepository() { _session = NHibernateHelper.OpenSession(); } public CompanyRepository(ISession session) { _session = session; } public class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) { var configuration = new Configuration(); configuration.Configure(); configuration.AddAssembly(typeof(UserProfile).Assembly); configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName); _sessionFactory = configuration.BuildSessionFactory(); } return _sessionFactory; } } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } I'm using the Ninject IOC container ( very new to me ). I have the following container. How would i bind the ISession to the CompanyRepository. private class EStoreDependencies : NinjectModule { public override void Load() { Bind<ICompanyRepository>().To<CompanyRepository>(); Bind<IUserProfileRepository>().To<UserProfileRepository>(); Bind<IAddressRepository>().To<AddressRepository>(); Bind<IRolesService>().To<AspNetRoleProviderWrapper>(); Bind<IUserService>().To<AspNetMembershipProviderWrapper>(); Bind<ICurrentUserSerivce>().To<DefaultCurrentUserSerivce>(); Bind<IPasswordService>().To<AspNetMembershipProviderWrapper>(); Bind<IStatusResponseRepository>().To<StatusResponseRepository>(); Bind<ICategoryRepository>().To<CategoryRepository>(); Bind<IProductRepository>().To<ProductRepository>(); } }

    Read the article

  • Dynamic Method Creation

    - by TJMonk15
    So, I have been trying to research this all morning, and have had no luck. I am trying to find a way to dynamically create a method/delegate/lambda that returns a new instance of a certain class (not known until runtime) that inherits from a certain base class. I can guarantee the following about the unknown/dynamic class It will always inherit from one known Class (Row) It will have atleast 2 constructors (one accepting a long, and one accepting an IDataRecord) I plan on doign the following: Finding all classes that have a certain attribute on them Creating a delegate/method/lambda/whatever that creates a new instance of the class Storing the delegate/whatever along with some properties in a struct/class Insert the struct into a hashtable When needed, pull the info out of the hashtable and calling the delegate/whatever to get a new instance of the class and returning it/adding it to a list/etc. I need help only with #2 above!!! I have no idea where to start. I really just need some reference material to get me started, or some keywords to throw into google. This is for a compact/simple to use ORM for our office here. I understand the above is not simple, but once working, should make maintaining the code incredibly simple. Please let me know if you need any more info! And thanks in advance! :)

    Read the article

  • c++ function scope

    - by Myx
    I have a main function in A.cpp which has the following relevant two lines of code: B definition(input_file); definition.Print(); In B.h I have the following relevant lines of code: class B { public: // Constructors B(void); B(const char *filename); ~B(void); // File input int ParseLSFile(const char *filename); // Debugging void Print(void); // Data int var1; double var2; vector<char* > var3; map<char*, vector<char* > > var4; } In B.cpp, I have the following function signatures (sorry for being redundant): B::B(void) : var1(-1), var2(numeric_limits<double>::infinity()) { } B::B(const char *filename) { B *def = new B(); def->ParseLSFile(filename); } B::~B(void) { // Free memory for var3 and var 4 } int B::ParseLSFile(const char *filename) { // assign var1, var2, var3, and var4 values } void B::Print(void) { // print contents of var1, var2, var3, and var4 to stdout } So when I call Print() from within B::ParseLSFile(...), then the contents of my structures print correctly to stdout. However, when I call definition.Print() from A.cpp, my structures are empty or contain garbage. Can anyone recommend the correct way to initialize/pass my structures so that I can access them outside of the scope of my function definition? Thanks.

    Read the article

  • Generic FSM for game in C++ ?

    - by Mr.Gando
    Hello, I was wondering if there's a way I could code some kind of "generic" FSM for a game with C++?. My game has a component oriented design, so I use a FSM Component. my Finite State Machine (FSM) Component, looks more or less this way. class gecFSM : public gecBehaviour { public: //Constructors gecFSM() { state = kEntityState_walk; } gecFSM(kEntityState s) { state = s; } //Interface void setRule(kEntityState initialState, int inputAction, kEntityState resultingState); void performAction(int action); private: kEntityState fsmTable[MAX_STATES][MAX_ACTIONS]; }; I would love to hear your opinions/ideas or suggestions about how to make this FSM component, generic. With generic I mean: 1) Creating the fsmTable from an xml file is really easy, I mean it's just a bunch of integers that can be loaded to create an MAX_STATESxMAX_ACTION matrix. void gecFSM::setRule(kEntityState initialState, int inputAction, kEntityState resultingState) { fsmTable[initialState][inputAction] = resultingState; } 2) But what about the "perform Action" method ? void gecFSM::performAction(int action) { switch( smTable[ ownerEntity->getState() ][ action ] ) { case WALK: /*Walk action*/ break; case STAND: /*Stand action*/ break; case JUMP: /*Jump action*/ break; case RUN: /*Run action*/ break; } } What if I wanted to make the "actions" and the switch generic? This in order to avoid creating a different FSM component class for each GameEntity? (gecFSMZombie, gecFSMDryad, gecFSMBoss etc ?). That would allow me to go "Data Driven" and construct my generic FSM's from files for example. What do you people suggest?

    Read the article

  • Suggest the way to design several classes

    - by Oleg Tarasenko
    Hi, I'm building simple application on as3. Kind of starship game. What I want to do is to create several different star ships. Each one should have different images (different look), different sets of animation (e.g. when it's flying, burning, damaged), different kind of weapon and also different controllers (e.g. one can be managed by user, another one by computer, and I want to be able to reuse same ships for AI controller as well as for users controls). Each ship is created in the following way: Create entity Add spatial Add renderers Add other components.... ...... n. init the ship So what I am trying to do: 1) Create StarShip superclass, to store HP (as every ship has it), store spatial (same reason) 2) Create inherited class for any other ship... (It will contain renderer - (responsible for display part), weapon, set of animations), etc What do you think about such way of composition? Maybe it's better to place everything in super class, and then just create instances using long, long, long constructors like: StarShip(hp:HP, animations:DICT, weapon:Weapon, ....) Need advice

    Read the article

  • NullPointerException with static variables

    - by tomekK
    I just hit very strange (to me) behaviour of java. I have following classes: public abstract class Unit { public static final Unit KM = KMUnit.INSTANCE; public static final Unit METERS = MeterUnit.INSTANCE; protected Unit() { } public abstract double getValueInUnit(double value, Unit unit); protected abstract double getValueInMeters(double value); } And: public class KMUnit extends Unit { public static final Unit INSTANCE = new KMUnit(); private KMUnit() { } //here are abstract methods overriden } public class MeterUnit extends Unit { public static final Unit INSTANCE = new MeterUnit(); private MeterUnit() { } ///abstract methods overriden } And my test case: public class TestMetricUnits extends TestCase { @Test public void testConversion() { System.out.println("Unit.METERS: " + Unit.METERS); System.out.println("Unit.KM: " + Unit.KM); double meters = Unit.KM.getValueInUnit(102.11, Unit.METERS); assertEquals(0.10211, meters, 0.00001); } } 1) MKUnit and MeterUnit are both singletons initialized statically, so during class loading. Constructors are private, so they can't be initialized anywhere else. 2) Unit class contains static final references to MKUnit.INSTANCE and MeterUnit.INSTANCE I would expect that: KMUnit class is loaded and instance is created. MeterUnit class is loaded and instance is created. Unit class is loaded and both KM and METERS variable are initialized, they are final so they cant be changed. But when I run my test case in console with maven my result is: T E S T S Running de.audi.echargingstations.tests.TestMetricUnits Unit.METERS: m Unit.KM: null Tests run: 3, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.089 sec <<< FAILURE! - in de.audi.echargingstations.tests.TestMetricUnits testConversion(de.audi.echargingstations.tests.TestMetricUnits) Time elapsed: 0.011 sec <<< ERROR! java.lang.NullPointerException: null at de.audi.echargingstations.tests.TestMetricUnits.testConversion(TestMetricUnits.java:29) Results : Tests in error: TestMetricUnits.testConversion:29 NullPointer And the funny part is that, when I run this test from eclipse via JUnit runner everything is fine, I have no NullPointerException and in console I have: Unit.METERS: m Unit.KM: km So the question is: what can be the reason that KM variable in Unit is null (and in the same time METERS is not null)

    Read the article

  • With this generics code why am I getting "Argument 1: cannot convert from 'ToplogyLibrary.Relationsh

    - by Greg
    Hi, Any see why I'm getting a "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase' to 'TRelationship'" in the code below, in CreateRelationship() ? public class TopologyBase<TKey, TNode, TRelationship> where TNode : NodeBase<TKey>, new() where TRelationship : RelationshipBase<TKey>, new() { // Properties public Dictionary<TKey, TNode> Nodes { get; private set; } public List<TRelationship> Relationships { get; private set; } // Constructors protected TopologyBase() { Nodes = new Dictionary<TKey, TNode>(); Relationships = new List<TRelationship>(); } // Methods public TNode CreateNode(TKey key) { var node = new TNode {Key = key}; Nodes.Add(node.Key, node); return node; } public void CreateRelationship(TNode parent, TNode child) { // Validation if (!Nodes.ContainsKey(parent.Key) || !Nodes.ContainsKey(child.Key)) { throw new ApplicationException("Can not create relationship as either parent or child was not in the graph: Parent:" + parent.Key + ", Child:" + child.Key); } // Add Relationship var r = new RelationshipBase<TNode>(); r.Parent = parent; r.Child = child; Relationships.Add(r); // *** HERE *** "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase<TNode>' to 'TRelationship'" } } public class RelationshipBase<TNode> { public TNode Parent { get; set; } public TNode Child { get; set; } } public class NodeBase<T> { public T Key { get; set; } public NodeBase() { } public NodeBase(T key) { Key = key; } }

    Read the article

  • Is there any reason to use C instead of C++ for embedded development?

    - by Piotr Czapla
    Question I have two compilers on my hardware C++ and C89 I'm thinking about using C++ with classes but without polymorphism (to avoid vtables). The main reasons I’d like to use C++ are: I prefer to use “inline” functions instead of macro definitions. I’d like to use namespaces as I prefixes clutter the code. I see C++ a bit type safer mainly because of templates, and verbose casting. I really like overloaded functions and constructors (used for automatic casting). Do you see any reason to stick with C89 when developing for very limited hardware (4kb of RAM)? Conclusion Thank you for your answers, they were really helpful! I though the subject through and I will stick with C mainly because: It is easier to predict actual code in C and this is really important if you have only 4kb of ram. My team consists of C developers mainly so advance features of C++ won't be frequently used. I've found a way to inline functions in my C compiler (C89). It is hard to accept one answer as you provided so many good answers. Unfortunately I can't create a wiki and accept it so I will choose one answer that made me think most.

    Read the article

  • DataGridView with row-specific DataGridViewComboBoxColumn contents in C# Windows Forms 3.5

    - by XXXXX
    So I have something like the following data structure (constructors omitted) class Child { public string Name { get; set; } public int Age { get; set; } } class Parent { public string Name { get; set; } public List <Child> Children { get; private set; } // never null; list never empty public Child FavoriteChild { get; set; } // never null; always a reference to a Child in Children } List < Parent > Parents; What I want to do is show a DataGridView where each row is a Parent from Parent list. Each row should have two columns: a text box showing the parent's name and a DataGridViewComboBoxColumn containing that parent's children, from which the user can select the parent's favorite child. I suppose I could do the whole thing manually, but I'd like to do all this with more-or-less standard Data Binding. It's easy enough to bind the DataGridView to the list of parents, and easy enough to bind the selected child to the FavoriteChild property. The part that's giving me difficulty is that it looks like the Combo Box column wants to bind to one data source for all the combo-box's contents on all rows. I'd like each instance of the combo box to bind to the list of each parent's children. I'm fairly new to C#/Windows Forms, so I may well be missing something obvious. Or it could be that "you can't get there from here." It's not too tough to make a separate list of all the children and filter it by parent; I'm looking into that possibility right now. Is this feasible, or is there a better way?

    Read the article

  • Difficulty porting raw PCM output code from Java to Android AudioTrack API.

    - by IndigoParadox
    I'm attempting to port an application that plays chiptunes (NSF, SPC, etc) music files from Java SE to Android. The Android API seems to lack the javax multimedia classes that this application uses to output raw PCM audio. The closest analog I've found in the API is AudioTrack and so I've been wrestling with that. However, when I try to run one of my sample music files through my port-in-progress, all I get back is static. My suspicion is that it's the AudioTrack I've setup which is at fault. I've tried various different constructors but it all just outputs static in the end. The DataLine setup in the original code is something like: AudioFormat audioFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, true ); DataLine.Info lineInfo = new DataLine.Info( SourceDataLine.class, audioFormat ); DataLine line = (SourceDataLine)AudioSystem.getLine( lineInfo ); The constructor I'm using right now is: AudioTrack = new AudioTrack( AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, AudioTrack.getMinBufferSize( 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT ), AudioTrack.MODE_STREAM ); I've replaced constants and variables in those so they make sense as concisely as possible, but my basic question is if there are any obvious problems in the assumptions I made when going from one format to the other.

    Read the article

  • Is dependency injection only for service type objects and singletons? (and NOT for gui?)

    - by sensui
    I'm currently experimenting with the Google's guice inversion of control container. I previously had singletons for just about any service (database, active directory) my application used. Now I refactored the code: all the dependencies are given as parameters to constructors. So far, so good. Now the hardest part is with the graphical user interface. I face this problem: I have a table (JTable) of products wrapped in an ProductFrame. I give the dependencies as parameters (EditProductDialog). @Inject public ProductFrame(EditProductDialog editProductDialog) { // ... } // ... @Inject public EditProductDialog(DBProductController productController, Product product) { // ... } The problem is that guice can't know what Product I have selected in the table, so it can't know what to inject in the EditProductDialog. Dependency Injection is pretty viral (if I modify one class to use dependency injection I also need to modify all the other classes it interacts with) so my question is should I directly instantiate EditProductDialog? But then I would have to pass manually the DBProductController to the EditProductDialog and I will also need to pass it to the ProductFrame and all this boils down to not using dependency injection at all. Or is my design flawed and because of that I can't really adapt the project to dependecy injection? Give me some examples of how you used dependency injection with the graphical user interface. All the examples found on the Internet are really simple examples where you use some services (mostly databases) with dependency injection.

    Read the article

  • How do I add array indices to the XML produced by JAXB?

    - by oconnor0
    I have a Java bean ala @XmlRootElement public class Bean { @XmlElementWrapper(name = "ints") @XmlElement(name = "int") int[] values; // constructors, getters, setters, etc... } JAXB is producing XML like <bean> <ints> <int>12</int> <int>34</int> <int>56</int> </ints> </bean> I would like the array indices to be included on the <int> tags as array position conveys important value. Preferably as attributes like <bean> <ints> <int id='0'>12</int> <int id='1'>34</int> <int id='2'>56</int> </ints> </bean> Is there a way to do this?

    Read the article

  • Convert image color space and output separate channels in OpenCV

    - by Victor May
    I'm trying to reduce the runtime of a routine that converts an RGB image to a YCbCr image. My code looks like this: cv::Mat input(BGR->m_height, BGR->m_width, CV_8UC3, BGR->m_imageData); cv::Mat output(BGR->m_height, BGR->m_width, CV_8UC3); cv::cvtColor(input, output, CV_BGR2YCrCb); cv::Mat outputArr[3]; outputArr[0] = cv::Mat(BGR->m_height, BGR->m_width, CV_8UC1, Y->m_imageData); outputArr[1] = cv::Mat(BGR->m_height, BGR->m_width, CV_8UC1, Cr->m_imageData); outputArr[2] = cv::Mat(BGR->m_height, BGR->m_width, CV_8UC1, Cb->m_imageData); split(output,outputArr); But, this code is slow because there is a redundant split operation which copies the interleaved RGB image into the separate channel images. Is there a way to make the cvtColor function create an output that is already split into channel images? I tried to use constructors of the _OutputArray class that accepts a vector or array of matrices as an input, but it didn't work.

    Read the article

  • Would an immutable keyword in Java be a good idea?

    - by berry120
    Generally speaking, the more I use immutable objects in Java the more I'm thinking they're a great idea. They've got lots of advantages from automatically being thread-safe to not needing to worry about cloning or copy constructors. This has got me thinking, would an "immutable" keyword go amiss? Obviously there's the disadvantages with adding another reserved word to the language, and I doubt it will actually happen primarily for the above reason - but ignoring that I can't really see many disadvantages. At present great care has to be taken to make sure objects are immutable, and even then a dodgy javadoc comment claiming a component object is immutable when it's in fact not can wreck the whole thing. There's also the argument that even basic objects like string aren't truly immutable because they're easily vunerable to reflection attacks. If we had an immutable keyword the compiler could surely recursively check and give an iron clad guarantee that all instances of a class were immutable, something that can't presently be done. Especially with concurrency becoming more and more used, I personally think it'd be good to add a keyword to this effect. But are there any disadvantages or implementation details I'm missing that makes this a bad idea?

    Read the article

  • Change Address/Port of WSDL EndPointAddress at runtime?

    - by Pretzel
    So I currently have 3 WSDLs added as Service References in my solution. They look like this in my app.config file (I removed the "bindings" field, because it's uninteresting): <system.serviceModel> <client> <endpoint address="http://localhost:8080/query-service/jse" binding="basicHttpBinding" bindingConfiguration="QueryBinding" contract="QueryService.Query" name="QueryPort" /> <endpoint address="http://localhost:8080/platetype-service/jse" binding="basicHttpBinding" bindingConfiguration="PlateTypeBinding" contract="PlateTypeService.PlateType" name="PlateTypePort" /> <endpoint address="http://localhost:8080/dataimport-service/jse" binding="basicHttpBinding" bindingConfiguration="DataImportBinding" contract="DataImportService.DataImport" name="DataImportPort" /> </client> </system.serviceModel> When I utilize a WSDL, it looks something like this: using (DataService.DataClient dClient = new DataService.DataClient()) { DataService.importTask impt = new DataService.importTask(); impt.String_1 = "someData"; DataService.importResponse imptr = dClient.importTask(impt); } In the "using" statement, when instantiating the DataClient object, I have 5 constructors available to me. In this scenario, I use the default constructor: new DataService.DataClient() which uses the built-in Endpoint Address string, which is fine and good. But I want the user of the application to have the option to change this value. 1) What's the best/easiest way of programatically obtaining this string? 2) Then, once I've allowed the user to edit and test the value, where should I store it? I'd prefer having it be stored in a place (like app.config or equivalent) so that there is no need for checking whether the value exists or not and whether I should be using an alternate constructor. (Looking to keep my code tight, ya know?) Any ideas? Suggestions?

    Read the article

  • Appengine JDO dataclasses to python model

    - by M.A. Cape
    Does anyone have tried to implement an app in GAE having both java and python? I have an existing app and my front end is in java. Now I want to use the existing datastore to be interfaced by python. My problem is i don't know how to define the relationships and model that would be equivalent to the one in java. I have tried the one-to-many relationship in python but when stored in the datastore, the fields are different than the one-to-many of java. My data classes are as follows. //one-to-many owned Parent Class public class Parent{ @PrimaryKey @Persistent private String unitID; //some other fields... @Persistent @Order(extensions = @Extension(vendorName="datanucleus", key="list-ordering", value="dateCreated desc")) private List <Child> child; //methods & constructors were omitted } Child public class Child{ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key uId; @Persistent private String name; /* etc... */ }

    Read the article

  • Constructor Overload Problem in C++ Inheritance

    - by metdos
    Here my code snippet: class Request { public: Request(void); ……….. } Request::Request(void) { qDebug()<<"Request: "<<"Hello World"; } class LoginRequest :public Request { public: LoginRequest(void); LoginRequest(QDomDocument); …………… } LoginRequest::LoginRequest(void) { qDebug()<<"LoginRequest: "<<"Hello World"; requestType=LOGIN; requestId=-1; } LoginRequest::LoginRequest(QDomDocument doc){ qDebug()<<"LoginRequest: "<<"Hello World with QDomDocument"; LoginRequest::LoginRequest(); xmlDoc_=doc; } When call constructor of Overrided LoginRequest LoginRequest *test=new LoginRequest(doc); I came up with this result: Request: Hello World LoginRequest: Hello World with QDomDocument Request: Hello World LoginRequest: Hello World Obviously both constructor of LoginRequest called REquest constructor. Is there any way to cape with this situation? I can construct another function that does the job I want to do and have both constructors call that function. But I wonder is there any solution?

    Read the article

  • MEF Import Composition Issues

    - by Tim
    I've read all the questions I can find regarding the issues of composing imports without exporting the containing class but I can't find a solution to my problem. Does anybody know a way to achieve what I'm trying to do? My module assemblies have forms and classes which they use internally. These forms need access to some of the exported contracts but imports are not loaded as they are not in the MEF 'composition tree' Host assembly: public class Host { public Host() { /* Compose parts here... */ } [Export(typeof(Licence))] public Licence LoadedLicence { get; set; } [Export(typeof(IModule))] public List<IModule> LoadedModules { get; set; } } Module assembly: [Export(typeof(IModule))] public class Module : IModule { public Module() { } public void DoSomething() { SubForm sub = new SubForm(); sub.ShowDialog(); } [Import(typeof(Licence))] public Licence LoadedLicence { get; set; } // This works here } public class SubForm : Form { public SubForm () { } [Import(typeof(Licence))] public Licence LoadedLicence { get; set; } // This doesn't work in here } As far as I can see, my options are: Pass parameters to constructors (pain) Use a dummy export on the classes that need imports satisfying? Any others?

    Read the article

  • How do I add code automatically to a derived function in C++

    - by Ian
    I have code that's meant to manage operations on both a networked client and a server, since there is significant overlap between the two. However, there are a few functions here and there that are meant to be exclusively called by the client or server, and accidentally calling a client function on the server (or vice versa) is a significant source of bugs. To reduce these sorts of programming errors, I'm trying to tag functions so that they'll raise a ruckus if they're misused. My current solution is a simple macro at the start of each function that calls an assert if the client or server accesses members they shouldn't. However, this runs into problems when there are multiple derived instances of classes, in that I have to tag the implementation as client or server side in EVERY child class. What I'd like to be able to do is put a tag in the virtual member's signature in the base class, so that I only have to tag it once and not run into errors by forgetting to do it repeatedly. I've considered putting a check in a base class implementation and then referring to it with something like base::functionName, but that runs into the same issue as far as needing to manually add the function call to every implementation. Ideally, I'd be able to have parent versions of the function called automatically like default constructors do. Does anybody know how to achieve something like this in C++? Is there an alternate approach I should be considering? Thanks!

    Read the article

  • Semi-generic function

    - by Fredrik Ullner
    I have a bunch of overloaded functions that operate on certain data types such as int, double and strings. Most of these functions perform the same action, where only a specific set of data types are allowed. That means I cannot create a simple generic template function as I lose type safety (and potentially incurring a run-time problem for validation within the function). Is it possible to create a "semi-generic compile time type safe function"? If so, how? If not, is this something that will come up in C++0x? An (non-valid) idea; template <typename T, restrict: int, std::string > void foo(T bar); ... foo((int)0); // OK foo((std::string)"foobar"); // OK foo((double)0.0); // Compile Error Note: I realize I could create a class that has overloaded constructors and assignment operators and pass a variable of that class instead to the function.

    Read the article

  • DataGridView with row-specific DataGridViewComboBoxColumn contents

    - by XXXXX
    So I have something like the following data structure (constructors omitted) class Child { public string Name { get; set; } public int Age { get; set; } } class Parent { public string Name { get; set; } public List <Child> Children { get; private set; } // never null; list never empty public Child FavoriteChild { get; set; } // never null; always a reference to a Child in Children } List < Parent > Parents; What I want to do is show a DataGridView where each row is a Parent from Parent list. Each row should have two columns: a text box showing the parent's name and a DataGridViewComboBoxColumn containing that parent's children, from which the user can select the parent's favorite child. I suppose I could do the whole thing manually, but I'd like to do all this with more-or-less standard Data Binding. It's easy enough to bind the DataGridView to the list of parents, and easy enough to bind the selected child to the FavoriteChild property. The part that's giving me difficulty is that it looks like the Combo Box column wants to bind to one data source for all the combo-box's contents on all rows. I'd like each instance of the combo box to bind to the list of each parent's children. I'm fairly new to C#/Windows Forms, so I may well be missing something obvious. Or it could be that "you can't get there from here." It's not too tough to make a separate list of all the children and filter it by parent; I'm looking into that possibility right now. Is this feasible, or is there a better way?

    Read the article

  • Google App Engine datastore encoding?

    - by sernaferna
    I'm using the GAE datastore for a Java application, and storing some text that will be in numerous languages. In my servlet, I'm first checking to see if there's any data in the data store, and, if not, I'm creating some, similar to the following: ArrayList<Lang> list = new ArrayList<Lang>(); list.add(new Lang("EN", "English", 1)); list.add(new Lang("ES", "Español", 0)); //more languages here... PersistenceManager pm = PMF.get().getPersistenceManager(); for(Lang l : list) { pm.makePersistent(l); } Since this is using JDO, I guess I should include the relevent parts of the Lang class too: @PersistenceCapable public class Lang { @PrimaryKey private String code; @Persistent private String name; @Persistent private int popularity; // getters & setters & constructors... } However, the non-ASCII characters are giving me grief. I've set my Eclipse project to use the UTF-8 encoding instead of the default Cp1252, so I think I'm okay from that perspective, but when I use the App Engine Data Viewer to look at my data, that Español entry becomes Español, and when I click on it to view it, I get a 500 Server Error. (There are some other entries with right-to-left text that don't even show up in the Data Viewer at all, but one problem at a time...) Is there anything special I can do in my code to set the character encoding, or specify to GAE that the data I'm storing is UTF-8? Or is the problem on the Eclipse side, and is there something I should be doing with my Java code?

    Read the article

  • Improve this generic abstract class

    - by Keivan
    I have the following abstract class design, I was wondering if anyone can suggest any improvements in terms of stronger enforcement of our requirements or simplifying implementing of the ControllerBase. //Dependency Provider base public abstract class ControllerBase<TContract, TType> where TType : TContract, class { public static TContract Instance { get { return ComponentFactory.GetComponent<TContract, TType>(); } } public TContract GetComponent<TContract, TType>() where TType : TContract, class { component = (TType)Activator.CreateInstance(typeof(TType), true); RegisterComponentInstance<TContract>(component); } } //Contract public interface IController { void DoThing(); } //Actual Class Logic public class Controller: ControllerBase<IController,Controller> { public void DoThing(); //internal constructor internal Controller(){} } //Usage public static void Main() { Controller.Instance.DoThing(); } The following facts should always be true, TType should always implement TContract (Enforced using a generic constraint) TContract must be an interface (Can't find a way to enforce it) TType shouldn't have public constructor, just an internal one, is there any way to Enforce that using ControllerBase? TType must be an concrete class (Didn't include New() as a generic constrain since the constructors should be marked as Internal)

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24  | Next Page >