Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 22/50 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • OOP concept: is it possible to update the class of an instantiated object?

    - by Federico
    I am trying to write a simple program that should allow a user to save and display sets of heterogeneous, but somehow related data. For clarity sake, I will use a representative example of vehicles. The program flow is like this: The program creates a Garage object, which is basically a class that can contain a list of vehicles objects Then the users creates Vehicles objects, these Vehicles each have a property, lets say License Plate Nr. Once created, the Vehicle object get added to a list within the Garage object --Later on--, the user can specify that a given Vehicle object is in fact a Car object or a Truck object (thus giving access to some specific attributes such as Number of seats for the Car, or Cargo weight for the truck) At first sight, this might look like an OOP textbook question involving a base class and inheritance, but the problem is more subtle because at the object creation time (and until the user decides to give more info), the computer doesn't know the exact Vehicle type. Hence my question: how would you proceed to implement this program flow? Is OOP the way to go? Just to give an initial answer, here is what I've came up until now. There is only one Vehicle class and the various properties/values are handled by the main program (not the class) through a dictionary. However, I'm pretty sure that there must be a more elegant solution (I'm developing using VB.net): Public Class Garage Public GarageAdress As String Private _ListGarageVehicles As New List(Of Vehicles) Public Sub AddVehicle(Vehicle As Vehicles) _ListGarageVehicles.Add(Vehicle) End Sub End Class Public Class Vehicles Public LicensePlateNumber As String Public Enum VehicleTypes Generic = 0 Car = 1 Truck = 2 End Enum Public VehicleType As VehicleTypes Public DictVehicleProperties As New Dictionary(Of String, String) End Class NOTE that in the example above the public/private modifiers do not necessarily reflect the original code

    Read the article

  • Better way to generate enemies of different sub-classes

    - by KDiTraglia
    So lets pretend I have an enemy class that has some generic implementation and inheriting from it I have all the specific enemies of my game. There are points in my code that I need to check whether an enemy is a specific type, but in Java I have found no easier way than this monstrosity... //Must be a better way to do this if ( enemy.class.isAssignableFrom(Ninja.class) ) { ... } My partner on the project saw these and changed them to use an enum system instead public class Ninja extends Enemy { //EnemyType is an enum containing all our enemy types public EnemyType = EnemyTypes.NINJA; } if (enemy.EnemyType = EnemyTypes.NINJA) { ... } I also have found no way to generate enemies on varying probabilities besides this for (EnemyTypes types : enemyTypes) { if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) { enemy = createEnemy(types.getEnemyType()); break; } } private static Enemy createEnemy(EnemyType type) { switch (type) { case NINJA: return new Ninja(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed()); case GORILLA: return new Gorilla(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed()); case TREX: return new TRex(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed()); //etc } return null } I know java is a little weak at dynamic object creation, but is there a better way to implement this in a way such like this for (EnemyTypes types : enemyTypes) { if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) { //Change enemyTypes to hold the classes of the enemies I can spawn enemy = types.getEnemyType().class.newInstance() break; } } Is the above possible? How would I declare enemyTypes to hold the classes if so? Everything I have tried so far as generated compile errors and general frustration, but I figured I might ask here before I completely give up to the huge mass that is the createEveryEnemy() method. All the enemies do inherit from the Enemy class (which is what the enemy variable is declared as). Also is there a better way to check which type a particular enemy that is shorter than enemy.class.isAssignableFrom(Ninja.class)? I'd like to ditch the enums entirely if possible, since they seem repetitive when the class name itself holds that information.

    Read the article

  • Visual Studio Little Wonders: Box Selection

    - by James Michael Hare
    So this week I decided I’d do a Little Wonder of a different kind and focus on an underused IDE improvement: Visual Studio’s Box Selection capability. This is a handy feature that many people still don’t realize was made available in Visual Studio 2010 (and beyond).  True, there have been other editors in the past with this capability, but now that it’s fully part of Visual Studio we can enjoy it’s goodness from within our own IDE. So, for those of you who don’t know what box selection is and what it allows you to do, read on! Sometimes, we want to select beyond the horizontal… The problem with traditional text selection in many editors is that it is horizontally oriented.  Sure, you can select multiple rows, but if you do you will pull in the entire row (at least for the middle rows).  Under the old selection scheme, if you wanted to select a portion of text from each row (a “box” of text) you were out of luck.  Box selection rectifies this by allowing you to select a box of text that bounded by a selection rectangle that you can grow horizontally or vertically.  So let’s think a situation that could occur where this comes in handy. Let’s say, for instance, that we are defining an enum in our code that we want to be able to translate into some string values (possibly to be stored in a database, output to screen, etc.). Perhaps such an enum would look like this: 1: public enum OrderType 2: { 3: Buy, // buy shares of a commodity 4: Sell, // sell shares of a commodity 5: Exchange, // exchange one commodity for another 6: Cancel, // cancel an order for a commodity 7: } 8:  Now, let’s say we are in the process of creating a Dictionary<K,V> to translate our OrderType: 1: var translator = new Dictionary<OrderType, string> 2: { 3: // do I really want to retype all this??? 4: }; Yes the example above is contrived so that we will pull some garbage if we do a multi-line select. I could select the lines above using the traditional multi-line selection: And then paste them into the translator code, which would result in this: 1: var translator = new Dictionary<OrderType, string> 2: { 3: Buy, // buy shares of a commodity 4: Sell, // sell shares of a commodity 5: Exchange, // exchange one commodity for another 6: Cancel, // cancel an order for a commodity 7: }; But I have a lot of junk there, sure I can manually clear it out, or use some search and replace magic, but if this were hundreds of lines instead of just a few that would quickly become cumbersome. The Box Selection Now that we have the ability to create box selections, we can select the box of text to delete!  Most of us are familiar with the fact we can drag the mouse (or hold [Shift] and use the arrow keys) to create a selection that can span multiple rows: Box selection, however, actually allows us to select a box instead of the typical horizontal lines: Then we can press the [delete] key and the pesky comments are all gone! You can do this either by holding down [Alt] while you select with your mouse, or by holding down [Alt+Shift] and using the arrow keys on the keyboard to grow the box horizontally or vertically. So now we have: 1: var translator = new Dictionary<OrderType, string> 2: { 3: Buy, 4: Sell, 5: Exchange, 6: Cancel, 7: }; Which is closer, but we still need an opening curly, the string to translate to, and the closing curly and comma. Fortunately, again, this is easy with box selections due to the fact box selection can even work for a zero-width selection! That is, hold down [Alt] and either drag down with no width, or hold down [Alt+Shift] and arrow down and you will define a selection range with no width, essentially, a vertical line selection: Notice the faint selection line on the right? So why is this useful? Well, just like with any selected range, we can type and it will replace the selection. What does this mean for box selections? It means that we can insert the same text all the way down on each line! If we have the same selection above, and type a curly and a space, we’d get: Imagine doing this over hundreds of lines and think of what a time saver it could be! Now make a zero-width selection on the other side: And type a curly and a comma, and we’d get: So close! Now finally, imagine we’ve already defined these strings somewhere and want to paste them in: 1: const private string BuyText = "Buy Shares"; 2: const private string SellText = "Sell Shares"; 3: const private string ExchangeText = "Exchange"; 4: const private string CancelText = "Cancel"; We can, again, use our box selection to pull out the constant names: And clicking copy (or [CTRL+C]) and then selecting a range to paste into: And finally clicking paste (or [CTRL+V]) to get the final result: 1: var translator = new Dictionary<OrderType, string> 2: { 3: { Buy, BuyText }, 4: { Sell, SellText }, 5: { Exchange, ExchangeText }, 6: { Cancel, CancelText }, 7: };   Sure, this was a contrived example, but I’m sure you’ll agree that it adds myriad possibilities of new ways to copy and paste vertical selections, as well as inserting text across a vertical slice. Summary: While box selection has been around in other editors, we finally get to experience it in VS2010 and beyond. It is extremely handy for selecting columns of information for cutting, copying, and pasting. In addition, it allows you to create a zero-width vertical insertion point that can be used to enter the same text across multiple rows. Imagine the time you can save adding repetitive code across multiple lines!  Try it, the more you use it, the more you’ll love it! Technorati Tags: C#,CSharp,.NET,Visual Studio,Little Wonders,Box Selection

    Read the article

  • Memento with optional state?

    - by Korey Hinton
    EDIT: As pointed out by Steve Evers and pdr, I am not correctly implementing the Memento pattern, my design is actually State pattern. Menu Program I built a console-based menu program with multiple levels that selects a particular test to run. Each level more precisely describes the operation. At any level you can type back to go back one level (memento). Level 1: Server Type? [1] Server A [2] Server B Level 2: Server environment? [1] test [2] production Level 3: Test type? [1] load [2] unit Level 4: Data Collection? [1] Legal docs [2] Corporate docs Level 4.5 (optional): Load Test Type [2] Multi TIF [2] Single PDF Level 5: Command Type? [1] Move [2] Copy [3] Remove [4] Custom Level 6: Enter a keyword [setup, cleanup, run] Design States PROBLEM: Right now the STATES enum is the determining factor as to what state is BACK and what state is NEXT yet it knows nothing about what the current memento state is. Has anyone experienced a similar issue and found an effective way to handle mementos with optional state? static enum STATES { SERVER, ENVIRONMENT, TEST_TYPE, COLLECTION, COMMAND_TYPE, KEYWORD, FINISHED } Possible Solution (Not-flexible) In reference to my code below, every case statement in the Menu class could check the state of currentMemo and then set the STATE (enum) accordingly to pass to the Builder. However, this doesn't seem flexible very flexible to change and I'm struggling to see an effective way refactor the design. class Menu extends StateConscious { private State state; private Scanner reader; private ServerUtils utility; Menu() { state = new State(); reader = new Scanner(System.in); utility = new ServerUtils(); } // Recurring menu logic public void startPromptingLoop() { List<State> states = new ArrayList<>(); states.add(new State()); boolean redoInput = false; boolean userIsDone = false; while (true) { // get Memento from last loop Memento currentMemento = states.get(states.size() - 1) .saveMemento(); if (currentMemento == null) currentMemento = new Memento.Builder(0).build(); if (!redoInput) System.out.println(currentMemento.prompt); redoInput = false; // prepare Memento for next loop Memento nextMemento = null; STATES state = STATES.values()[states.size() - 1]; // get user input String selection = reader.nextLine(); switch (selection) { case "exit": reader.close(); return; // only escape case "quit": nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); states.clear(); break; case "back": nextMemento = new Memento.Builder(previous(state), currentMemento, selection).build(); if (states.size() <= 1) { states.remove(0); } else { states.remove(states.size() - 1); states.remove(states.size() - 1); } break; case "1": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "2": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "3": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "4": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; default: if (state.equals(STATES.CATEGORY)) { String command = selection; System.out.println("Executing " + command + " command on: " + currentMemento.type + " " + currentMemento.environment); utility.executeCommand(currentMemento.nickname, command); userIsDone = true; states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else if (state.equals(STATES.KEYWORD)) { nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else { redoInput = true; System.out.println("give it another try"); continue; } break; } if (userIsDone) { // start the recurring menu over from the beginning for (int i = 0; i < states.size(); i++) { if (i != 0) { states.remove(i); // remove all except first } } reader = new Scanner(System.in); this.state = new State(); userIsDone = false; } if (!redoInput) { this.state.restoreMemento(nextMemento); states.add(this.state); } } } }

    Read the article

  • Using ADO.net Entity Framework 4 with Enumerations? How do I do it ?

    - by Perpetualcoder
    Question 1: I am playing around with EF4 and I have a model class like : public class Candidate { public int Id {get;set;} public string FullName {get;set;} public Gender Sex {get;set;} public EducationLevel HighestDegreeType {get;set;} } Here Gender and EducationLevel are Enums like: public enum Gender {Male,Female,Undisclosed} public enum EducationLevel {HighSchool,Bachelors,Masters,Doctorate} How do I get the Candidate Class and Gender and EducationLevel working with EF4 if: I do model first development I do db first development Edit: Moved question related to object context to another question here.

    Read the article

  • Why Html.DropDownListFor requires extra cast?

    - by dcompiled
    In my controller I create a list of SelectListItems and store this in the ViewData. When I read the ViewData in my View it gives me an error about incorrect types. If I manually cast the types it works but seems like this should happen automatically. Can someone explain? Controller: enum TitleEnum { Mr, Ms, Mrs, Dr }; var titles = new List<SelectListItem>(); foreach(var t in Enum.GetValues(typeof(TitleEnum))) titles.Add(new SelectListItem() { Value = t.ToString(), Text = t.ToString() }); ViewData["TitleList"] = titles; View: // Doesn't work Html.DropDownListFor(x => x.Title, ViewData["TitleList"]) // This Works Html.DropDownListFor(x => x.Title, (List<SelectListItem>) ViewData["TitleList"])

    Read the article

  • Stop the screen saver and hibernation temporarily in VB.Net

    - by Tim Santeford
    I have a very long running syncronization task that cannot be interrupted by the screen saver or aggressive power saving modes. I want to make a single api call to stop power save mode and then restore it once the task is done. The following code is peaced together from various other posts but it has no effect on XP's power management settings. What am I doing wrong? TIA! Private Declare Function SetThreadExecutionState Lib "kernel32" (ByVal esFlags As Long) As Long Public Enum EXECUTION_STATE As Integer ES_CONTINUOUS = &H80000000 ES_DISPLAY_REQUIRED = &H2 ES_SYSTEM_REQUIRED = &H1 ES_AWAYMODE_REQUIRED = &H40 End Enum Public Shared Sub PowerSaveOff() SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED Or EXECUTION_STATE.ES_CONTINUOUS) End Sub Public Shared Sub PowerSaveOn() SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS) End Sub Here are the systems screensaver and powermode settings:

    Read the article

  • VB.NET 2008 - Anonymous Function

    - by James Brauman
    Hi, On Form Load I populate a menu with all possible colors so they user can pick a color. However when they pick a color the forecolor of my label is not changed. Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' When the form loads, we want to populate the color menu item with all the possible colors that we could change the label to. For Each currentColor As KnownColor In [Enum].GetValues(GetType(KnownColor)) ' Declare the knowColor again - we must do this to be able to do anonymous delegates in VB.NET Dim actualCurrentColor As KnownColor = currentColor ' Get the name for this color Dim colorName As String = [Enum].GetName(GetType(KnownColor), actualCurrentColor) ' Create a new menu item for this color Dim newMenuItem As ToolStripMenuItem = New ToolStripMenuItem(colorName) ' Add a handler to this menu item so when it is clicked, we change the heading color AddHandler newMenuItem.Click, Function(s As System.Object, events As System.EventArgs) (HeadingLabel.ForeColor = Color.FromKnownColor(actualCurrentColor)) ' Add the menu item to the colors menu ColorToolStripMenuItem.DropDownItems.Add(newMenuItem) Next End Sub What am I doing wrong? Thanks

    Read the article

  • Enumerations and String values in ASP.NET

    - by Jason
    I'm looking for some best practice advice on enumerations and retrieving an associated string value. Given this: public enum SerialKillers { TedBundy, EdGein, AlbertFish, GeorgeBush } What is the best way to get a related string value of the name? Eg. "Ted Bundy", given that the string value may not match the representation in the enumeration. eg "George W Bush" My current thinking is function accepting an enum and returning a string, but would that not mean hard coding the string values (which I prefer not to do)? Is using a resources file where the string can be retrieved via the enumeration too heavy handed? Should I accept the fact I am going to Hell for victimising Ted Bundy by associating him with George Bush?

    Read the article

  • ModalPopup CodeBehind Function Wait For User Response

    - by Snave
    I have set up a function which returns an enum of the button that the user clicked in the ModalPopup. I have a variable of type enum to store which button the user clicks in the button click event. In this function, I call the ModalPopupExtender's Show() method. My problem is, the function finishes out and returns the default enum (which is "none" since no button was clicked yet) before the ModalPopup can be shown and store which button the user clicks. So without changing the function to a method and using a different way to store the user's button click, how can I pause the function after the Show() method of the MPE has been called and wait for the user to click a button? Edit(11/20/2009): Clarification: On the aspx page, I include a ScriptManager, PlaceHolder, and an asp:Button with a codebehind click event. What I want is to click the button, then in the click event handler, I want to call a custom static class function that returns a variable. One of the arguments it takes is the PlaceHolder. The function creates all the necessary controls in the PlaceHolder needed to display a ModalPopup. It calls the created ModalPopupExtender's Show() method. What should happen: At this point is the ModalPopup gets displayed, the user clicks a button, that button's event handler fires, the button sets a variable indicating that it was clicked, it then calls the ModalPopupExtender's .Hide() method, and then the function returns the variable that indicates which button was clicked. We then return to the event handler from the original button that was clicked and the programmer can then perform some logic based on what variable was returned. Crux: When the ModalPopupExtender's .Show() method gets called, it does not display the ModalPopup until AFTER the function returns a default variable (because no button was clicked yet) and after the event handler from the original button that was clicked ends. What I need: After the ModalPopupExtender's .Show() method is called, I need the ModalPopup to get displayed immediately and I need the function to wait for a button click to be made from the ModalPopup. My thoughts: Some PostBack needs to be made to the page telling it to update and display the ModalPopup Panel. Then maybe a while loop can be run in the function that waits for a button to be clicked in the ModalPopup.

    Read the article

  • What is the right tool to detect VMT or heap corruption in Delphi ?

    - by Roland Bengtsson
    I'm a member in a team that use Delphi 2007 for a larger application and we suspect heap corruption because sometimes there are strange bugs that have no other explanation. I believe that the Rangechecking option for the compiler is only for arrays. I want a tool that give an exception or log when there is a write on a memory address that is not allocated by the application. Regards EDIT: The error is of type: Error: Access violation at address 00404E78 in module 'BoatLogisticsAMCAttracsServer.exe'. Read of address FFFFFFDD EDIT2: Thanks for all suggestions. Unfortunately I think that the solution is deeper than that. We use a patched version of Bold for Delphi as we own the source. Probably there are some errors introduced in the Bold framwork. Yes we have a log with callstacks that are handled by JCL and also trace messages. So a callstack with the exception can lock like this: 20091210 16:02:29 (2356) [EXCEPTION] Raised EBold: Failed to derive ServerSession.mayDropSession: Boolean OCL expression: not active and not idle and timeout and (ApplicationKernel.allinstances->first.CurrentSession <> self) Error: Access violation at address 00404E78 in module 'BoatLogisticsAMCAttracsServer.exe'. Read of address FFFFFFDD. At Location BoldSystem.TBoldMember.CalculateDerivedMemberWithExpression (BoldSystem.pas:4016) Inner Exception Raised EBold: Failed to derive ServerSession.mayDropSession: Boolean OCL expression: not active and not idle and timeout and (ApplicationKernel.allinstances->first.CurrentSession <> self) Error: Access violation at address 00404E78 in module 'BoatLogisticsAMCAttracsServer.exe'. Read of address FFFFFFDD. At Location BoldSystem.TBoldMember.CalculateDerivedMemberWithExpression (BoldSystem.pas:4016) Inner Exception Call Stack: [00] System.TObject.InheritsFrom (sys\system.pas:9237) Call Stack: [00] BoldSystem.TBoldMember.CalculateDerivedMemberWithExpression (BoldSystem.pas:4016) [01] BoldSystem.TBoldMember.DeriveMember (BoldSystem.pas:3846) [02] BoldSystem.TBoldMemberDeriver.DoDeriveAndSubscribe (BoldSystem.pas:7491) [03] BoldDeriver.TBoldAbstractDeriver.DeriveAndSubscribe (BoldDeriver.pas:180) [04] BoldDeriver.TBoldAbstractDeriver.SetDeriverState (BoldDeriver.pas:262) [05] BoldDeriver.TBoldAbstractDeriver.Derive (BoldDeriver.pas:117) [06] BoldDeriver.TBoldAbstractDeriver.EnsureCurrent (BoldDeriver.pas:196) [07] BoldSystem.TBoldMember.EnsureContentsCurrent (BoldSystem.pas:4245) [08] BoldSystem.TBoldAttribute.EnsureNotNull (BoldSystem.pas:4813) [09] BoldAttributes.TBABoolean.GetAsBoolean (BoldAttributes.pas:3069) [10] BusinessClasses.TLogonSession._GetMayDropSession (code\BusinessClasses.pas:31854) [11] DMAttracsTimers.TAttracsTimerDataModule.RemoveDanglingLogonSessions (code\DMAttracsTimers.pas:237) [12] DMAttracsTimers.TAttracsTimerDataModule.UpdateServerTimeOnTimerTrig (code\DMAttracsTimers.pas:482) [13] DMAttracsTimers.TAttracsTimerDataModule.TimerKernelWork (code\DMAttracsTimers.pas:551) [14] DMAttracsTimers.TAttracsTimerDataModule.AttracsTimerTimer (code\DMAttracsTimers.pas:600) [15] ExtCtrls.TTimer.Timer (ExtCtrls.pas:2281) [16] Classes.StdWndProc (common\Classes.pas:11583) The inner exception part is the callstack at the moment an exception is reraised. EDIT3: The theory right now is that the Virtual Memory Table (VMT) is somehow broken. When this happen there is no indication of it. Only when a method is called an exception is raised (ALWAYS on address FFFFFFDD, -35 decimal) but then it is too late. You don't know the real cause for the error. Any hint of how to catch a bug like this is really appreciated!!! We have tried with SafeMM, but the problem is that the memory consumption is too high even when the 3 GB flag is used. So now I try to give a bounty to the SO community :) EDIT4: One hint is that according the log there is often (or even always) another exception before this. It can be for example optimistic locking in the database. We have tried to raise exceptions by force but in test environment it just works fine. EDIT5: Story continues... I did a search on the logs for the last 30 days now. The result: "Read of address FFFFFFDB" 0 "Read of address FFFFFFDC" 24 "Read of address FFFFFFDD" 270 "Read of address FFFFFFDE" 22 "Read of address FFFFFFDF" 7 "Read of address FFFFFFE0" 20 "Read of address FFFFFFE1" 0 So the current theory is that an enum (there is a lots in Bold) overwrite a pointer. I got 5 hits with different address above. It could mean that the enum holds 5 values where the second one is most used. If there is an exception a rollback should occur for the database and Boldobjects should be destroyed. Maybe there is a chance that not everything is destroyed and a enum still can write to an address location. If this is true maybe it is possible to search the code by a regexpr for an enum with 5 values ? EDIT6: To summarize, no there is no solution to the problem yet. I realize that I may mislead you a bit with the callstack. Yes there are a timer in that but there are other callstacks without a timer. Sorry for that. But there are 2 common factors. An exception with Read of address FFFFFFxx. Top of callstack is System.TObject.InheritsFrom (sys\system.pas:9237) This convince me that VilleK best describe the problem. I'm also convinced that the problem is somewhere in the Bold framework. But the BIG question is, how can problems like this be solved ? It is not enough to have an Assert like VilleK suggest as the damage has already happened and the callstack is gone at that moment. So to describe my view of what may cause the error: Somewhere a pointer is assigned a bad value 1, but it can be also 0, 2, 3 etc. An object is assigned to that pointer. There is method call in the objects baseclass. This cause method TObject.InheritsForm to be called and an exception appear on address FFFFFFDD. Those 3 events can be together in the code but they may also be used much later. I think this is true for the last method call. EDIT7: We work closely with the the author of Bold Jan Norden and he recently found a bug in the OCL-evaluator in Bold framework. When this was fixed these kinds of exceptions decreased a lot but they still occasionally come. But it is a big relief that this is almost solved.

    Read the article

  • error C2784: Could not deduce template argument

    - by atch
    Hi guys, Still fighting with templates. In this example, despite the fact that is copied straight from a book I'm getting the following error message: Error 2 error C2784: 'IsClassT<T>::One IsClassT<T>::test(int C::* )' : could not deduce template argument for 'int C::* ' from 'int'. This is an example from a book Templates - The Complete Guide. (I work with Visual Studio 2010 RC). template<typename T> class IsClassT { private: typedef char One; typedef struct { char a[2]; } Two; template<typename C> static One test(int C::*); template<typename C> static Two test(…); public: enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; enum { No = !Yes }; }; class MyClass { }; struct MyStruct { }; union MyUnion { }; void myfunc() { } enum E {e1} e; // check by passing type as template argument template <typename T> void check() { if (IsClassT<T>::Yes) { std::cout << " IsClassT " << std::endl; } else { std::cout << " !IsClassT " << std::endl; } } // check by passing type as function call argument template <typename T> void checkT (T) { check<T>(); } int main() { /*std::cout << "int: "; check<int>(); */ std::cout << "MyClass: "; check<MyClass>(); } And although I know roughly what's going on in this example I cannot fix this error. Thanks for help.

    Read the article

  • Using embedded resources in Silverlight (4) - other cultures not being compiled

    - by Andrei Rinea
    I am having a bit of a hard time providing localized strings for the UI in a small Silverlight 4 application. Basically I've put a folder "Resources" and placed two resource files in it : Statuses.resx Statuses.ro.resx I do have an enum Statuses : public enum Statuses { None, Working } and a convertor : public class StatusToMessage : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!Enum.IsDefined(typeof(Status), value)) { throw new ArgumentOutOfRangeException("value"); } var x = Statuses.None; return Statuses.ResourceManager.GetString(((Status)value).ToString(), Thread.CurrentThread.CurrentUICulture); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } in the view I have a textblock : <TextBlock Grid.Column="3" Text="{Binding Status, Converter={StaticResource StatusToMessage}}" /> Upon view rendering the converter is called but no matter what the Thread.CurrentThread.CurrentUICulture is set it always returns the default culture value. Upon further inspection I took apart the XAP resulted file, taken the resulted DLL file to Reflector and inspected the embedded resources. It only contains the default resource!! Going back to the two resource files I am now inspecting their properties : Build action : Embedded Resource Copy to output directory : Do not copy Custom tool : ResXFileCodeGenerator Custom tool namespace : [empty] Both resource (.resx) files have these settings. The .Designer.cs resulted files are as follows : Statuses.Designer.cs : //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SilverlightApplication5.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Statuses { // ... yadda-yadda Statuses.ro.Designer.cs [empty] I've taken both files and put them in a console application and they behave as expected in it, not like in this silverlight application. What is wrong?

    Read the article

  • Is there a Maven plugin to generate AS3 classes from Java for BlazeDS ?

    - by Maskime
    Hi, I'm looking for a maven plugin that would generate ActionScript3 classes from Java classes in order to access them by object remoting. I've seen FlexMojo but it uses the GraniteDS generator wich create some problems when it comes to map Enum objects (wich can be fix through a workaround that is describe here : http://dev.c-ware.de/confluence/display/PUBLIC/Flexmojos+generated+AS3+model+with+Enum+support+using+BlazeDS?focusedCommentId=7634946&#comment-7634946 if you've googled your way here this might be useful) when working with BlazeDS. Everything that i found so far are people who explain how to generate VO classes on flex side using Flash Builder 4, but this solution can not be used in an industrial developpement environnement. Thanks in advance for any leads on this matter.

    Read the article

  • How to model "target day" in UML Classdiagrams

    - by Tobiask
    Hi there, I want to describe the following situation in an UML Classdiagram: A day, on which a newspaper is send to a customer. This day could be sth. like "every friday" or "every first day of a month". My idea to represent this in a UML Classdiagram: -targetDay:Integer -targetDayGrid:Enumeration targetDay would be sth. like "1" (for monday) oder "5" (for friday) or it could be "1" for the first day of the month or "10" for the 10th day of the month. targetDayGrid is an enum: weekly, monthly. So the enum sets the semantic meaning of the number in targetDay. I´m not happy with this, do you know any other solution to represent my problem? Or do you think my solution is okay?

    Read the article

  • Creating DescriptionAttribute on Enumeration Field using System.Reflection.Emit

    - by Manish Sinha
    I have a list of strings which are candidates for Enumerations values. They are Don't send diffs 500 lines 1000 lines 5000 lines Send entire diff The problem is that spaces, special characters are not a part of identifiers and even cannot start with a number, so I would be sanitizing these values to only chars, numbers and _ To keep the original values I thought of putting these strings in the DescriptionAttribute, such that the final Enum should look like public enum DiffBehvaiour { [Description("Don't send diffs")] Dont_send_diffs, [Description("500 lines")] Diff_500_lines, [Description("1000 lines")] Diff_1000_lines, [Description("5000 lines")] Diff_5000_lines, [Description("Send entire diff")] Send_entire_diff } Then later using code I will retrieve the real string associated with the enumeration value, so that the correct string can be sent back the web service to get the correct resource. I want to know how to create the DescriptionAttribute using System.Reflection.Emit Basically the question is where and how to store the original string so that when the Enumeration value is chosen, the corresponding value can be retrieved. I am also interested in knowing how to access DescriptionAttribute when needed.

    Read the article

  • How to represent different entities that have identical behavior?

    - by Dominik
    I have several different entities in my domain model (animal species, let's say), which have a few properties each. The entities are readonly (they do not change state during the application lifetime) and they have identical behavior (the differ only by the values of properties). How to implement such entities in code? Unsuccessful attempts: Enums I tried an enum like this: enum Animals { Frog, Duck, Otter, Fish } And other pieces of code would switch on the enum. However, this leads to ugly switching code, scattering the logic around and problems with comboboxes. There's no pretty way to list all possible Animals. Serialization works great though. Subclasses I also thought about where each animal type is a subclass of a common base abstract class. The implementation of Swim() is the same for all Animals, though, so it makes little sense and serializability is a big issue now. Since we represent an animal type (species, if you will), there should be one instance of the subclass per application, which is hard and weird to maintain when we use serialization. public abstract class AnimalBase { string Name { get; set; } // user-readable double Weight { get; set; } Habitat Habitat { get; set; } public void Swim(); { /* swim implementation; the same for all animals but depends uses the value of Weight */ } } public class Otter: AnimalBase{ public Otter() { Name = "Otter"; Weight = 10; Habitat = "North America"; } } // ... and so on Just plain awful. Static fields This blog post gave me and idea for a solution where each option is a statically defined field inside the type, like this: public class Animal { public static readonly Animal Otter = new Animal { Name="Otter", Weight = 10, Habitat = "North America"} // the rest of the animals... public string Name { get; set; } // user-readable public double Weight { get; set; } public Habitat Habitat { get; set; } public void Swim(); } That would be great: you can use it like enums (AnimalType = Animal.Otter), you can easily add a static list of all defined animals, you have a sensible place where to implement Swim(). Immutability can be achieved by making property setters protected. There is a major problem, though: it breaks serializability. A serialized Animal would have to save all its properties and upon deserialization it would create a new instance of Animal, which is something I'd like to avoid. Is there an easy way to make the third attempt work? Any more suggestions for implementing such a model?

    Read the article

  • About variadic templates

    - by chedi
    Hi, I'm currently experiencing with the new c++0x variadic templates, and it's quit fun, Although I have a question about the process of member instanciation. in this example, I'm trying to emulate the strongly typed enum with the possibility of choose a random valid strong enum (this is used for unit testing). #include<vector> #include<iostream> using namespace std; template<unsigned... values> struct sp_enum; /* this is the solution I found, declaring a globar var vector<unsigned> _data; and it work just fine */ template<> struct sp_enum<>{ static const unsigned _count = 0; static vector<unsigned> _data; }; vector<unsigned> sp_enum<>::_data; template<unsigned T, unsigned... values> struct sp_enum<T, values...> : private sp_enum<values...>{ static const unsigned _count = sp_enum<values...>::_count+1; static vector<unsigned> _data; sp_enum( ) : sp_enum<values...>(values...) {_data.push_back(T);} sp_enum(unsigned v ) {_data.push_back(v);} sp_enum(unsigned v, unsigned...) : sp_enum<values...>(values...) {_data.push_back(v);} }; template<unsigned T, unsigned... values> vector<unsigned> sp_enum<T, values...>::_data; int main(){ enum class t:unsigned{Default = 5, t1, t2}; sp_enum<t::Default, t::t1, t::t2> test; cout <<test._count << endl << test._data.size() << endl; for(auto i= test._data.rbegin();i != test._data.rend();++i){cout<< *i<< ":";} } the result I'm getting with this code is : 3 1 5: can someone point me what I'm messing here ??? Ps: using gcc 4.4.3

    Read the article

  • Using NHibernate to map a nChar column to an enumerated type

    - by Morrislgn
    Hello Folks, I am trying to map a table frp, a SQL Server 2005 DB to a class which contains an enum: public class MyClass{ private YesNoOptional addressSetting; public YesNoOptional AddressSetting{ {get; set;} } } public enum YesNoOptional { Yes, No, Optional } This will dictate that one of three values is inserted into the corresponding column - 'Y', 'N', 'O'. This column is of type nchar(1). My mapping file is like so (addressSetting is the property which is causing the problem): <class name="IncidentDefinition" table="IR_INCIDENT_DEF" lazy="false" > <id name="Guid" column="INT_GUID" > <generator class="guid"></generator> </id> <property name="Reference" column="INT_REF" ></property> <property name="Description" column="INT_DESCRIPTION" ></property> <property name="AddressSetting" column="INT_ADDRESS_REQ" ></property> <property name="Active" column="INT_ACTIVE" type="YesNo"></property> <property name="PinDocId" column="INT_PIN_DOC_ID"></property> </class> Using the config above I get the following error: NHibernate.ADOException: could not initialize a collection: System.FormatException: Input string was not in a correct format.. If I try to map the enum using a custom type like so: <property name="AddressSetting" column="INT_ADDRESS_REQ" type="ML.Types.YesNoOptional, ML.Types" ></property> Error: System.FormatException: Input string was not in a correct format. Next, if I try using a specific type like so: <property name="AddressSetting" column="INT_ADDRESS_REQ" type="String" ></property> This error is generated: NHibernate.PropertyAccessException: The type System.String can not be assigned to a property of type System.ArgumentException: Object of type 'System.String' cannot be converted to type 'ML.Types.YesNoOptional'.. As a last resort I tried to specify the type as a char like so: <property name="AddressSetting" column="INT_ADDRESS_REQ" type="Char" ></property> This works a bit better, as it in it doesnt throw an error, however instead of returning the character from the table and mapping it to the enumerated type the ASCII value of the character is returned instead - so Y is represented by 89! I am hoping someone can explain what I am doing wrong and\or how why this is happening please? Thanks Morris

    Read the article

  • Ways to save enums in database

    - by corgrath
    Hey guys. I am wondering what the best ways to save enums into a database is. I know there are name() and valueOf() methods to make it into a String back. But are there any other (flexible) options to store these values? Is there a smart way to make them into unique numbers (ordinal() is not safe to use)? Any comments and suggestions would be helpful :) Update: Thanks for all awesome and fast answers! It was as I suspected. However a note to 'toolkit'; That is one way. The problem is that I would have to add the same methods with each enum type i create. Thats a lot of duplicated code and, at the moment, Java does not support any solutions to this (You cannot let enum extend other classes). However, thanks for all answers!

    Read the article

  • wpf: design time error while writing Nested type in xaml

    - by viky
    I have created a usercontrol which accept type of enum and assign the values of that enum to a ComboBox control in that usercontrol. Very Simple. I am using this user control in DataTemplates. Problem comes when there comes nested type. I assign that using this notation EnumType="{x:Type myNamespace:ParentType + NestedType}" It works fine at runtime. but at design time it throws error saying Could not create an instance of type 'TypeExtension' Why? Due to this I am not able to see my window at design time. Any help?

    Read the article

  • Problem serializing complex data using WCF

    - by Gustavo Paulillo
    Scenario: WCF client app, calling a web-service (JAVA) operation, wich requires a complex object as parameter. Already got the metadata. Problem: The operation has some required fields. One of them is a enum. In the SOAP sent, isnt the field above (generated metadata) - Im using WCF diagnostics and Windows Service Trace Viewer: [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3082")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="Consult-Filter", Namespace="http://webserviceX.org/")] public partial class ConsFilter : object, System.ComponentModel.INotifyPropertyChanged { private PersonType customerTypeField; Property: [System.Xml.Serialization.XmlElementAttribute("customer-type", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public PersonType customerType { get { return this.customerTypeField; } set { this.customerTypeField = value; this.RaisePropertyChanged("customerType"); } } The enum: [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3082")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(TypeName="Person-Type", Namespace="http://webserviceX.org/")] public enum PersonType { /// <remarks/> F, /// <remarks/> J, } The trace log: <MessageLogTraceRecord> <HttpRequest xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace"> <Method>POST</Method> <QueryString></QueryString> <WebHeaders> <VsDebuggerCausalityData>data</VsDebuggerCausalityData> </WebHeaders> </HttpRequest> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none"></Action> <ActivityId CorrelationId="correlationId" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">activityId</ActivityId> </s:Header> <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <filter xmlns="http://webserviceX.org/"> <product-code xmlns="">116</product-code> <customer-doc xmlns="">777777777</customer-doc> </filter> </s:Body> </s:Envelope> </MessageLogTraceRecord>

    Read the article

  • Complex HashMap has different hashCode after serialization

    - by woezelmann
    I am parsing a xml file into a complex HashMap looking like this: Map<String, Map<String, EcmObject> EcmObject: public class EcmObject implements Comparable, Serializable { private final EcmObjectType type; private final String name; private final List<EcmField> fields; private final boolean pages; // getter, equals, hashCode } EcmObjectType: public enum EcmObjectType implements Serializable { FOLDER, REGISTER, DOCUMENT } EcmField public class EcmField implements Comparable, Serializable { private final EcmFieldDataType dataType; private final EcmFieldControlType controlType; private final String name; private final String dbname; private final String internalname; private final Integer length; // getter, equals, hashCode } EcmFieldDataType public enum EcmFieldDataType implements Serializable { TEXT, DATE, NUMBER, GROUP, DEC; } and EcmFieldControlType public enum EcmFieldControlType implements Serializable{ DEFAULT, CHECKBOX, LIST, DBLIST, TEXTAREA, HIERARCHY, TREE, GRID, RADIO, PAGECONTROL, STATIC; } I have overwritten all hashCode and equal methods by usind commons lang's EqualsBuilder and HashCodeBuilder. Now when I copy a A HashMap this way: Map<String, Map<String, EcmObject>> m = EcmUtil.convertXmlObjectDefsToEcmEntries(new File("e:\\objdef.xml")); Map<String, Map<String, EcmObject>> m2; System.out.println(m.hashCode()); ByteArrayOutputStream baos = new ByteArrayOutputStream(8 * 4096); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(m); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); m2 = (Map<String, Map<String, EcmObject>>) ois.readObject(); System.out.println(m.hashCode()); System.out.println(m2.hashCode()); m.hashCode() is not equal to m2.hashCode() here is my output: -1639352210 -2071553208 1679930154 Another strange thing is, that eg. 10 times m has the same hashcode and suddenly on the 11th time the hashcode is different... Any ideas what this is about?

    Read the article

  • Problem using FluentNHibernate, SQLite and Enums

    - by weenet
    I have a Sharp Architecture based app using Fluent NHibernate with Automapping. I have the following Enum: public enum Topics { AdditionSubtraction = 1, MultiplicationDivision = 2, DecimalsFractions = 3 } and the following Class: public class Strategy : BaseEntity { public virtual string Name { get; set; } public virtual Topics Topic { get; set; } public virtual IList Items { get; set; } } If I create an instance of the class thusly: Strategy s = new Strategy { Name = "Test", Topic = Topics.AdditionSubtraction }; it Saves correctly (thanks to this mapping convention: public class EnumConvention : IPropertyConvention, IPropertyConventionAcceptance { public void Apply(FluentNHibernate.Conventions.Instances.IPropertyInstance instance) { instance.CustomType(instance.Property.PropertyType); } public void Accept(FluentNHibernate.Conventions.AcceptanceCriteria.IAcceptanceCriteria criteria) { criteria.Expect(x = x.Property.PropertyType.IsEnum); } } However, upon retrieval, I get an error regarding an attempt to convert Int64 to Topics. This works fine in SQL Server. Any ideas for a workaround? Thanks.

    Read the article

  • Throwing exception vs returning null value with switch statement

    - by Greg
    So I have function that formats a date to coerce to given enum DateType{CURRENT, START, END} what would be the best way to handling return value with cases that use switch statement public static String format(Date date, DateType datetype) { ..validation checks switch(datetype){ case CURRENT:{ return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss"); } ... default:throw new ("Something strange happend"); } } OR throw excpetion at the end public static String format(Date date, DateType datetype) { ..validation checks switch(datetype){ case CURRENT:{ return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss"); } ... } //It will never reach here, just to make compiler happy throw new IllegalArgumentException("Something strange happend"); } OR return null public static String format(Date date, DateType datetype) { ..validation checks switch(datetype){ case CURRENT:{ return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss"); } ... } return null; } What would be the best practice here ? Also all the enum values will be handled in the case statement

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >