Search Results

Search found 187 results on 8 pages for 'ev'.

Page 3/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • How to add objects to association in OnPreInsert, OnPreUpdate

    - by Dmitriy Nagirnyak
    Hi, I have an event listener (for Audit Logs) which needs to append audit log entries to the association of the object: public Company : IAuditable { // Other stuff removed for bravety IAuditLog IAuditable.CreateEntry() { var entry = new CompanyAudit(); this.auditLogs.Add(entry); return entry; } public virtual IEnumerable<CompanyAudit> AuditLogs { get { return this.auditLogs } } } The AuditLogs collection is mapped with cascading: public class CompanyMap : ClassMap<Company> { public CompanyMap() { // Id and others removed fro bravety HasMany(x => x.AuditLogs).AsSet() .LazyLoad() .Access.ReadOnlyPropertyThroughCamelCaseField() .Cascade.All(); } } And the listener just asks the auditable object to create log entries so it can update them: internal class AuditEventListener : IPreInsertEventListener, IPreUpdateEventListener { public bool OnPreUpdate(PreUpdateEvent ev) { var audit = ev.Entity as IAuditable; if (audit == null) return false; Log(audit); return false; } public bool OnPreInsert(PreInsertEvent ev) { var audit = ev.Entity as IAuditable; if (audit == null) return false; Log(audit); return false; } private static void LogProperty(IAuditable auditable) { var entry = auditable.CreateAuditEntry(); entry.CreatedAt = DateTime.Now; entry.Who = GetCurrentUser(); // Might potentially execute a query. // Also other information is set for entry here } } The problem with it though is that it throws TransientObjectException when commiting the transaction: NHibernate.TransientObjectException : object references an unsaved transient instance - save the transient instance before flushing. Type: PropConnect.Model.UserAuditLog, Entity: PropConnect.Model.UserAuditLog at NHibernate.Engine.ForeignKeys.GetEntityIdentifierIfNotUnsaved(String entityName, Object entity, ISessionImplementor session) at NHibernate.Type.EntityType.GetIdentifier(Object value, ISessionImplementor session) at NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.WriteElement(IDbCommand st, Object elt, Int32 i, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.PerformInsert(Object ownerId, IPersistentCollection collection, IExpectation expectation, Object entry, Int32 index, Boolean useBatch, Boolean callable, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.Recreate(IPersistentCollection collection, Object id, ISessionImplementor session) at NHibernate.Action.CollectionRecreateAction.Execute() at NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at NHibernate.Engine.ActionQueue.ExecuteActions() at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) at NHibernate.Impl.SessionImpl.Flush() at NHibernate.Transaction.AdoTransaction.Commit() As the cascading is set to All I expected NH to handle this. I also tried to modify the collection using state but pretty much the same happens. So the question is what is the last chance to modify object's associations before it gets saved? Thanks, Dmitriy.

    Read the article

  • Load local file in place of remote file (HTTP) address in Windows

    - by ev
    Hi there, I am trying to achieve something that you might typically use a hosts file for, but that isn't suitable here. I want a Windows PC to refer to a local file (I can serve it from a web server at localhost if needed) when it attempts to fetch a certain remote file via HTTP. However, I need other files from that particular remote web server to be fetched as usual. Any help appreciated.

    Read the article

  • How do I fix this Django error "Exception Type: OperationalError Exception Value: no such table?"

    - by user319045
    I've finally installed all the requirements (so i think!) of a Django project, and I'm trying to get a local install running on my Mac (OSX 10.4). I'm getting the following error: Blockquote OperationalError at / no such table: django_content_type Request Method: GET Request URL: http://127.0.0.1:8000/ Exception Type: OperationalError Exception Value: no such table: django_content_type Exception Location: /Users/Diesel/Desktop/DjangoWork/pinax-ev/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py in execute, line 170 Python Executable: /Users/Diesel/Desktop/DjangoWork/pinax-ev/bin/python Python Version: 2.5.1

    Read the article

  • decltype, result_of, or typeof?

    - by Neil G
    I have: class A { public: B toCPD() const; And: template<typename T> class Ev { public: typedef result_of(T::toCPD()) D; After instantiating Ev<A>, the compiler says: meta.h:12: error: 'T::toCPD' is not a type neither decltype nor typeof work either.

    Read the article

  • Superclass Sensitive Actions

    - by Geertjan
    I've created a small piece of functionality that enables you to create actions for Java classes in the IDE. When the user right-clicks on a Java class, they will see one or more actions depending on the superclass of the selected class. To explain this visually, here I have "BlaTopComponent.java". I right-click on its node in the Projects window and I see "This is a TopComponent": Indeed, when you look at the source code of "BlaTopComponent.java", you'll see that it implements the TopComponent class. Next, in the screenshot below, you see that I have right-click a different class. In this case, there's an action available because the selected class implements the ActionListener class. Then, take a look at this one. Here both TopComponent and ActionListener are superclasses of the current class, hence both the actions are available to be invoked: Finally, here's a class that subclasses neither TopComponent nor ActionListener, hence neither of the actions that I created for doing something that relates to TopComponents or ActionListeners is available, since those actions are irrelevant in this context: How does this work? Well, it's a combination of my blog entries "Generic Node Popup Registration Solution" and "Showing an Action on a TopComponent Node". The cool part is that the definition of the two actions that you see above is remarkably trivial: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import org.openide.loaders.DataObject; import org.openide.util.Utilities; public class TopComponentSensitiveAction implements ActionListener { private final DataObject context; public TopComponentSensitiveAction() { context = Utilities.actionsGlobalContext().lookup(DataObject.class); } @Override public void actionPerformed(ActionEvent ev) { //Do something with the context: JOptionPane.showMessageDialog(null, "TopComponent: " + context.getNodeDelegate().getDisplayName()); } } The above is the action that will be available if you right-click a Java class that extends TopComponent. This, in turn, is the action that will be available if you right-click a Java class that implements ActionListener: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import org.openide.loaders.DataObject; import org.openide.util.Utilities; public class ActionListenerSensitiveAction implements ActionListener { private final DataObject context; public ActionListenerSensitiveAction() { context = Utilities.actionsGlobalContext().lookup(DataObject.class); } @Override public void actionPerformed(ActionEvent ev) { //Do something with the context: JOptionPane.showMessageDialog(null, "ActionListener: " + context.getNodeDelegate().getDisplayName()); } } Indeed, the classes, at this stage are the same. But, depending on what I want to do with TopComponents or ActionListeners, I now have a starting point, which includes access to the DataObject, from where I can get down into the source code, as shown here. This is how the two ActionListeners that you see defined above are registered in the layer, which could ultimately be done via annotations on the ActionListeners, of course: <folder name="Actions"> <folder name="Tools"> <file name="org-netbeans-sbas-impl-TopComponentSensitiveAction.instance"> <attr stringvalue="This is a TopComponent" name="displayName"/> <attr name="instanceCreate" methodvalue="org.netbeans.sbas.SuperclassSensitiveAction.create"/> <attr name="type" stringvalue="org.openide.windows.TopComponent"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.TopComponentSensitiveAction"/> </file> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"> <attr stringvalue="This is an ActionListener" name="displayName"/> <attr name="instanceCreate" methodvalue="org.netbeans.sbas.SuperclassSensitiveAction.create"/> <attr name="type" stringvalue="java.awt.event.ActionListener"/> <attr name="delegate" newvalue="org.netbeans.sbas.impl.ActionListenerSensitiveAction"/> </file> </folder> </folder> <folder name="Loaders"> <folder name="text"> <folder name="x-java"> <folder name="Actions"> <file name="org-netbeans-sbas-impl-TopComponentSensitiveAction.shadow"> <attr name="originalFile" stringvalue="Actions/Tools/org-netbeans-sbas-impl-TopComponentSensitiveAction.instance"/> <attr intvalue="150" name="position"/> </file> <file name="org-netbeans-sbas-impl-ActionListenerSensitiveAction.shadow"> <attr name="originalFile" stringvalue="Actions/Tools/org-netbeans-sbas-impl-ActionListenerSensitiveAction.instance"/> <attr intvalue="160" name="position"/> </file> </folder> </folder> </folder> </folder> The most important parts of the layer registration are the lines that are highlighted above. Those lines connect the layer to the generic action that delegates back to the action listeners defined above, as follows: public final class SuperclassSensitiveAction extends AbstractAction implements ContextAwareAction { private final Map map; //This method is called from the layer, via "instanceCreate", //magically receiving a map, which contains all the attributes //that are defined in the layer for the file: static SuperclassSensitiveAction create(Map map) { return new SuperclassSensitiveAction(Utilities.actionsGlobalContext(), map); } public SuperclassSensitiveAction(Lookup context, Map m) { super(m.get("displayName").toString()); this.map = m; String superclass = m.get("type").toString(); //Enable the menu item only if //we're dealing with a class of type superclass: JavaSource javaSource = JavaSource.forFileObject( context.lookup(DataObject.class).getPrimaryFile()); try { javaSource.runUserActionTask(new ScanTask(this, superclass), true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } //Hide the menu item if it isn't enabled: putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true); } @Override public void actionPerformed(ActionEvent ev) { ActionListener delegatedAction = (ActionListener)map.get("delegate"); delegatedAction.actionPerformed(ev); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new SuperclassSensitiveAction(actionContext, map); } private class ScanTask implements Task<CompilationController> { private SuperclassSensitiveAction action = null; private String superclass; private ScanTask(SuperclassSensitiveAction action, String superclass) { this.action = action; this.superclass = superclass; } @Override public void run(final CompilationController info) throws Exception { info.toPhase(Phase.ELEMENTS_RESOLVED); new EnableIfGivenSuperclassMatches(info, action, superclass).scan( info.getCompilationUnit(), null); } } private static class EnableIfGivenSuperclassMatches extends TreePathScanner<Void, Void> { private CompilationInfo info; private final AbstractAction action; private final String superclassName; public EnableIfGivenSuperclassMatches(CompilationInfo info, AbstractAction action, String superclassName) { this.info = info; this.action = action; this.superclassName = superclassName; } @Override public Void visitClass(ClassTree t, Void v) { Element el = info.getTrees().getElement(getCurrentPath()); if (el != null) { TypeElement te = (TypeElement) el; List<? extends TypeMirror> interfaces = te.getInterfaces(); if (te.getSuperclass().toString().equals(superclassName)) { action.setEnabled(true); } else { action.setEnabled(false); } for (TypeMirror typeMirror : interfaces) { if (typeMirror.toString().equals(superclassName)){ action.setEnabled(true); } } } return null; } } } This is a pretty cool solution and, as you can see, very generic. Create a new ActionListener, register it in the layer so that it maps to the generic class above, and make sure to set the type attribute, which defines the superclass to which the action should be sensitive.

    Read the article

  • Help getting frame rate (fps) up in Python + Pygame

    - by Jordan Magnuson
    I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game for Intel's March developer competition, which is squarely aimed at netbooks packing underpowered Atom processors. Here's a screen from the game: ![www.necessarygames.com/my_games/betraveled/betraveled-fps.png][1] I am very new to Python and Pygame (this is the first thing I've used them for), and am sadly lacking in formal CS training... which is to say that I think there are probably A LOT of bad practices going on in my code, and A LOT that could be optimized. If some of you older Python hands wouldn't mind taking a look at my code and seeing if you can't find any obvious areas for optimization, I would be extremely grateful. You can download the full source code here: http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip Compiled exe here: www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip One thing I am concerned about is my event manager, which I feel may have some performance wholes in it, and another thing is my rendering... I'm pretty much just blitting everything to the screen all the time (see the render routines in my game_components.py below); I recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue? Any thoughts are much appreciated! As usual, I'm happy to "tip" you for your time and energy via PayPal. Jordan Here are some bits of the source: Main.py #Remote imports import pygame from pygame.locals import * #Local imports import config import rooms from event_manager import * from events import * class RoomController(object): """Controls which room is currently active (eg Title Screen)""" def __init__(self, screen, ev_manager): self.room = None self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.room = self.set_room(config.room) def set_room(self, room_const): #Unregister old room from ev_manager if self.room: self.room.ev_manager.unregister_listener(self.room) self.room = None #Set new room based on const if room_const == config.TITLE_SCREEN: return rooms.TitleScreen(self.screen, self.ev_manager) elif room_const == config.GAME_MODE_ROOM: return rooms.GameModeRoom(self.screen, self.ev_manager) elif room_const == config.GAME_ROOM: return rooms.GameRoom(self.screen, self.ev_manager) elif room_const == config.HIGH_SCORES_ROOM: return rooms.HighScoresRoom(self.screen, self.ev_manager) def notify(self, event): if isinstance(event, ChangeRoomRequest): if event.game_mode: config.game_mode = event.game_mode self.room = self.set_room(event.new_room) def render(self, surface): self.room.render(surface) #Run game def main(): pygame.init() screen = pygame.display.set_mode(config.screen_size) ev_manager = EventManager() spinner = CPUSpinnerController(ev_manager) room_controller = RoomController(screen, ev_manager) pygame_event_controller = PyGameEventController(ev_manager) spinner.run() # this runs the main function if this script is called to run. # If it is imported as a module, we don't run the main function. if __name__ == "__main__": main() event_manager.py #Remote imports import pygame from pygame.locals import * #Local imports import config from events import * def debug( msg ): print "Debug Message: " + str(msg) class EventManager: #This object is responsible for coordinating most communication #between the Model, View, and Controller. def __init__(self): from weakref import WeakKeyDictionary self.listeners = WeakKeyDictionary() self.eventQueue= [] self.gui_app = None #---------------------------------------------------------------------- def register_listener(self, listener): self.listeners[listener] = 1 #---------------------------------------------------------------------- def unregister_listener(self, listener): if listener in self.listeners: del self.listeners[listener] #---------------------------------------------------------------------- def post(self, event): if isinstance(event, MouseButtonLeftEvent): debug(event.name) #NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient, #but currently has to be done because of how new listeners are added to the queue while it is running #(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html #and search for "Watch the iteration" for listener in list(self.listeners): #NOTE: If the weakref has died, it will be #automatically removed, so we don't have #to worry about it. listener.notify(event) #------------------------------------------------------------------------------ class PyGameEventController: """...""" def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.input_freeze = False #---------------------------------------------------------------------- def notify(self, incoming_event): if isinstance(incoming_event, UserInputFreeze): self.input_freeze = True elif isinstance(incoming_event, UserInputUnFreeze): self.input_freeze = False elif isinstance(incoming_event, TickEvent): #Share some time with other processes, so we don't hog the cpu pygame.time.wait(5) #Handle Pygame Events for event in pygame.event.get(): #If this event manager has an associated PGU GUI app, notify it of the event if self.ev_manager.gui_app: self.ev_manager.gui_app.event(event) #Standard event handling for everything else ev = None if event.type == QUIT: ev = QuitEvent() elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze: if event.button == 1: #Button 1 pos = pygame.mouse.get_pos() ev = MouseButtonLeftEvent(pos) elif event.type == pygame.MOUSEMOTION: pos = pygame.mouse.get_pos() ev = MouseMoveEvent(pos) #Post event to event manager if ev: self.ev_manager.post(ev) #------------------------------------------------------------------------------ class CPUSpinnerController: def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.clock = pygame.time.Clock() self.cumu_time = 0 self.keep_going = True #---------------------------------------------------------------------- def run(self): if not self.keep_going: raise Exception('dead spinner') while self.keep_going: time_passed = self.clock.tick() fps = self.clock.get_fps() self.cumu_time += time_passed self.ev_manager.post(TickEvent(time_passed, fps)) if self.cumu_time >= 1000: self.cumu_time = 0 self.ev_manager.post(SecondEvent()) pygame.quit() #---------------------------------------------------------------------- def notify(self, event): if isinstance(event, QuitEvent): #this will stop the while loop from running self.keep_going = False rooms.py #Remote imports import pygame #Local imports import config import continents from game_components import * from my_gui import * from pgu import high class Room(object): def __init__(self, screen, ev_manager): self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) def notify(self, event): if isinstance(event, TickEvent): pygame.display.set_caption('FPS: ' + str(int(event.fps))) self.render(self.screen) pygame.display.update() def get_highs_table(self): fname = 'high_scores.txt' highs_table = None config.all_highs = high.Highs(fname) if config.game_mode == config.TIME_CHALLENGE: if config.difficulty == config.EASY: highs_table = config.all_highs['time_challenge_easy'] if config.difficulty == config.MED_DIF: highs_table = config.all_highs['time_challenge_med'] if config.difficulty == config.HARD: highs_table = config.all_highs['time_challenge_hard'] if config.difficulty == config.SUPER: highs_table = config.all_highs['time_challenge_super'] elif config.game_mode == config.PLAN_AHEAD: pass return highs_table class TitleScreen(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() #Initialize #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=0) #Quit Button #--------------------------------------- b = StartGameButton(ev_manager=self.ev_manager) c.add(b, 0, 0) self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) class GameModeRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() self.create_gui() #Create pgu gui elements def create_gui(self): #Setup #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=-1) #Mode Relaxed Button #--------------------------------------- b = GameModeRelaxedButton(ev_manager=self.ev_manager) self.b = b print b.rect c.add(b, 0, 200) #Mode Time Challenge Button #--------------------------------------- b = TimeChallengeButton(ev_manager=self.ev_manager) self.b = b print b.rect c.add(b, 0, 250) #Mode Think Ahead Button #--------------------------------------- # b = PlanAheadButton(ev_manager=self.ev_manager) # self.b = b # print b.rect # c.add(b, 0, 300) #Initialize #--------------------------------------- self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) class GameRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) #Game mode #--------------------------------------- self.new_board_timer = None self.game_mode = config.game_mode config.current_highs = self.get_highs_table() self.highs_dialog = None self.game_over = False #Images #--------------------------------------- self.background = pygame.image.load('assets/images/interface/game screen2-1.jpg').convert() self.logo = pygame.image.load('assets/images/interface/logo_small.png').convert_alpha() self.game_over_text = pygame.image.load('assets/images/interface/text_game_over.png').convert_alpha() self.trip_complete_text = pygame.image.load('assets/images/interface/text_trip_complete.png').convert_alpha() self.zoom_game_over = None self.zoom_trip_complete = None self.fade_out = None #Text #--------------------------------------- self.font = pygame.font.Font(config.font_sans, config.interface_font_size) #Create game components #--------------------------------------- self.continent = self.set_continent(config.continent) self.board = Board(config.board_size, self.ev_manager) self.deck = Deck(self.ev_manager, self.continent) self.map = Map(self.continent) self.longest_trip = 0 #Set pos of game components #--------------------------------------- board_pos = (SCREEN_MARGIN[0], 109) self.board.set_pos(board_pos) map_pos = (config.screen_size[0] - self.map.size[0] - SCREEN_MARGIN[0], 57); self.map.set_pos(map_pos) #Trackers #--------------------------------------- self.game_clock = Chrono(self.ev_manager) self.swap_counter = 0 self.level = 0 #Create gui #--------------------------------------- self.create_gui() #Create initial board #--------------------------------------- self.new_board = self.deck.deal_new_board(self.board) self.ev_manager.post(NewBoardComplete(self.new_board)) def set_continent(self, continent_const): #Set continent based on const if continent_const == config.EUROPE: return continents.Europe() if continent_const == config.AFRICA: return continents.Africa() else: raise Exception('Continent constant not recognized') #Create pgu gui elements def create_gui(self): #Setup #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=-1,valign=-1) #Timer Progress bar #--------------------------------------- self.timer_bar = None self.time_increase = None self.minutes_left = None self.seconds_left = None self.timer_text = None if self.game_mode == config.TIME_CHALLENGE: self.time_increase = config.time_challenge_start_time self.timer_bar = gui.ProgressBar(config.time_challenge_start_time,0,config.max_time_bank,width=306) c.add(self.timer_bar, 172, 57) #Connections Progress bar #--------------------------------------- self.connections_bar = None self.connections_bar = gui.ProgressBar(0,0,config.longest_trip_needed,width=306) c.add(self.connections_bar, 172, 83) #Quit Button #--------------------------------------- b = QuitButton(ev_manager=self.ev_manager) c.add(b, 950, 20) #Generate Board Button #--------------------------------------- b = GenerateBoardButton(ev_manager=self.ev_manager, room=self) c.add(b, 500, 20) #Board Size? #--------------------------------------- bs = SetBoardSizeContainer(config.BOARD_LARGE, ev_manager=self.ev_manager, board=self.board) c.add(bs, 640, 20) #Fill Board? #--------------------------------------- t = FillBoardCheckbox(config.fill_board, ev_manager=self.ev_manager) c.add(t, 740, 20) #Darkness? #--------------------------------------- t = UseDarknessCheckbox(config.use_darkness, ev_manager=self.ev_manager) c.add(t, 840, 20) #Initialize #--------------------------------------- self.gui_app.init(c) def advance_level(self): self.level += 1 print 'Advancing to next level' print 'New level: ' + str(self.level) if self.timer_bar: print 'Time increase: ' + str(self.time_increase) self.timer_bar.value += self.time_increase self.time_increase = max(config.min_advance_time, int(self.time_increase * 0.9)) self.board = self.new_board self.new_board = None self.zoom_trip_complete = None self.game_clock.unpause() def notify(self, event): #Tick event if isinstance(event, TickEvent): pygame.display.set_caption('FPS: ' + str(int(event.fps))) self.render(self.screen) pygame.display.update() #Wait to deal new board when advancing levels if self.zoom_trip_complete and self.zoom_trip_complete.finished: self.zoom_trip_complete = None self.ev_manager.post(UnfreezeCards()) self.new_board = self.deck.deal_new_board(self.board) self.ev_manager.post(NewBoardComplete(self.new_board)) #New high score? if self.zoom_game_over and self.zoom_game_over.finished and not self.highs_dialog: if config.current_highs.check(self.level) != None: self.zoom_game_over.visible = False data = 'time:' + str(self.game_clock.time) + ',swaps:' + str(self.swap_counter) self.highs_dialog = HighScoreDialog(score=self.level, data=data, ev_manager=self.ev_manager) self.highs_dialog.open() elif not self.fade_out: self.fade_out = FadeOut(self.ev_manager, config.TITLE_SCREEN) #Second event elif isinstance(event, SecondEvent): if self.timer_bar: if not self.game_clock.paused: self.timer_bar.value -= 1 if self.timer_bar.value <= 0 and not self.game_over: self.ev_manager.post(GameOver()) self.minutes_left = self.timer_bar.value / 60 self.seconds_left = self.timer_bar.value % 60 if self.seconds_left < 10: leading_zero = '0' else: leading_zero = '' self.timer_text = ''.join(['Time Left: ', str(self.minutes_left), ':', leading_zero, str(self.seconds_left)]) #Game over elif isinstance(event, GameOver): self.game_over = True self.zoom_game_over = ZoomImage(self.ev_manager, self.game_over_text) #Trip complete event elif isinstance(event, TripComplete): print 'You did it!' self.game_clock.pause() self.zoom_trip_complete = ZoomImage(self.ev_manager, self.trip_complete_text) self.new_board_timer = Timer(self.ev_manager, 2) self.ev_manager.post(FreezeCards()) print 'Room posted newboardcomplete' #Board Refresh Complete elif isinstance(event, BoardRefreshComplete): if event.board == self.board: print 'Longest trip needed: ' + str(config.longest_trip_needed) print 'Your longest trip: ' + str(self.board.longest_trip) if self.board.longest_trip >= config.longest_trip_needed: self.ev_manager.post(TripComplete()) elif event.board == self.new_board: self.advance_level() self.connections_bar.value = self.board.longest_trip self.connection_text = ' '.join(['Connections:', str(self.board.longest_trip), '/', str(config.longest_trip_needed)]) #CardSwapComplete elif isinstance(event, CardSwapComplete): self.swap_counter += 1 elif isinstance(event, ConfigChangeBoardSize): config.board_size = event.new_size elif isinstance(event, ConfigChangeCardSize): config.card_size = event.new_size elif isinstance(event, ConfigChangeFillBoard): config.fill_board = event.new_value elif isinstance(event, ConfigChangeDarkness): config.use_darkness = event.new_value def render(self, surface): #Background surface.blit(self.background, (0, 0)) #Map self.map.render(surface) #Board self.board.render(surface) #Logo surface.blit(self.logo, (10,10)) #Text connection_text = self.font.render(self.connection_text, True, BLACK) surface.blit(connection_text, (25, 84)) if self.timer_text: timer_text = self.font.render(self.timer_text, True, BLACK) surface.blit(timer_text, (25, 64)) #GUI self.gui_app.paint(surface) if self.zoom_trip_complete: self.zoom_trip_complete.render(surface) if self.zoom_game_over: self.zoom_game_over.render(surface) if self.fade_out: self.fade_out.render(surface) class HighScoresRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() #Initialize #--------------------------------------- self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=0) #High Scores Table #--------------------------------------- hst = HighScoresTable() c.add(hst, 0, 0) self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) game_components.py #Remote imports import pygame from pygame.locals import * import random import operator from copy import copy from math import sqrt, floor #Local imports import config from events import * from matrix import Matrix from textrect import render_textrect, TextRectException from hyphen import hyphenator from textwrap2 import TextWrapper ############################## #CONSTANTS ############################## SCREEN_MARGIN = (10, 10) #Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) YELLOW = (255, 200, 0) #Directions LEFT = -1 RIGHT = 1 UP = 2 DOWN = -2 #Cards CARD_MARGIN = (10, 10) CARD_PADDING = (2, 2) #Card types BLANK = 0 COUNTRY = 1 TRANSPORT = 2 #Transport types PLANE = 0 TRAIN = 1 CAR = 2 SHIP = 3 class Timer(object): def __init__(self, ev_manager, time_left): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time_left = time_left self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time_left -= 1 class Chrono(object): def __init__(self, ev_manager, start_time=0): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time = start_time self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time += 1 class Map(object): def __init__(self, continent): self.map_image = pygame.image.load(continent.map).convert_alpha() self.map_text = pygame.image.load(continent.map_text).convert_alpha() self.pos = (0, 0) self.set_color() self.map_image = pygame.transform.smoothscale(self.map_image, config.map_size) self.size = self.map_image.get_size() def set_pos(self, pos): self.pos = pos def set_color(self): image_pixel_array = pygame.PixelArray(self.map_image) image_pixel_array.replace(config.GRAY1, config.COLOR1) image_pixel_array.replace(config.GRAY2, config.COLOR2) image_pixel_array.replace(config.GRAY3, config.COLOR3) image_pixel_array.replace(config.GRAY4, config.COLOR4) image_pixel_array.replace(config.GRAY5, config.COLOR5)

    Read the article

  • Reloading an external element (via jQuery's .load) without impact on same-named host elements on sam

    - by Martin Pescador
    Hello together! [First, I'm an absolute beginner. I tried to express myself as good as I could - please correct me on any issue... Now: I have the following problem:] I am loading a div element, which class always is ".gallery" from a couple of pages (in this example "the page index.php?page=orange") into another page's div (in this case with the ID "orange") using the following code: $("#orange").load("http://example.com/index.php?page=orange .gallery"); Each div.gallery I load in, is a set of a few images. Between them, you can switch (there are "previous"- and "next"-links in ".imgnavi"). $(".imgnavi a").live("click", function(ev) { ev.preventDefault(); ev.stopPropagation(); $(".gallery").load($(this).attr("href")); return false; }) What happens now: Loading the different div.gallery into the new page is no problem, but as soon as I start to navigate inside those divs (each div is a little gallery, where you can switch between images), the div.gallery I am switching in is suddenly loaded into EVERY other div.gallery in the document! How do I prevent that?

    Read the article

  • gdb: Cannot find new threads: generic error

    - by Alexander Gladysh
    When I run GDB against a program which loads a .so which is linked to pthreads, GDB reports error "Cannot find new threads: generic error". I probably miss something in my Ubuntu configuration (as it was installed from minimal install). Any clues? $ gdb --args lua -lluarocks.require GNU gdb (GDB) 7.0-ubuntu Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /usr/bin/lua...(no debugging symbols found)...done. (gdb) run Starting program: /usr/bin/lua -lluarocks.require Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio require 'ev' [Thread debugging using libthread_db enabled] Cannot find new threads: generic error (gdb) q A debugging session is active. Inferior 1 [process 4986] will be killed. Quit anyway? (y or n) y This function gets called on require 'ev': http://github.com/brimworks/lua-ev/blob/master/lua_ev.c#L25-65 Additional information about my system: $ uname -a Linux localhost 2.6.31-20-generic #58-Ubuntu SMP Fri Mar 12 04:38:19 UTC 2010 x86_64 GNU/Linux $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 9.10 Release: 9.10 Codename: karmic

    Read the article

  • WPF & Linq To SQL binding ComboBox to foreign key

    - by ZeroDelta
    I'm having trouble binding a ComboBox to a foreign key in WPF using Linq To SQL. It works fine when displaying records, but if I change the selection on the ComboBox, that change does not seem to affect the property to which it is bound. My SQL Server Compact file has three tables: Players (PK is PlayerID), Events (PK is EventID), and Matches (PK is MatchID). Matches has FKs for the the other two, so that a match is associated with a player and an event. My window for editing a match uses a ComboBox to select the Event, and the ItemsSource is set to the result of a LINQ query to pull all of the Events. And of course the user should be able to select the Event based on EventName, not EventID. Here's the XAML: <ComboBox x:Name="cboEvent" DisplayMemberPath="EventName" SelectedValuePath="EventID" SelectedValue="{Binding Path=EventID, UpdateSourceTrigger=PropertyChanged}" /> And some code-behind from the Loaded event handler: var evt = from ev in db.Events orderby ev.EventName select ev; cboEvent.ItemsSource = evt.ToList(); var mtch = from m in db.Matches where m.PlayerID == ((Player)playerView.CurrentItem).PlayerID select m; matchView = (CollectionView)CollectionViewSource.GetDefaultView(mtch); this.DataContext = matchView; When displaying matches, this works fine--I can navigate from one match to the next and the EventName is shown correctly. However, if I select a new Event via this ComboBox, the CurrentItem of the CollectionView doesn't seem to change. I feel like I'm missing something stupid! Note: the Player is selected via a ListBox, and that selection filters the matches displayed--this seems to be working fine, so I didn't include that code. That is the reason for the "PlayerID" reference in the LINQ query

    Read the article

  • Is there a way to log every gui event in Delphi?

    - by awmross
    The Delphi debugger is great for debugging linear code, where one function calls other functions in a predictable, linear manner, and we can step through the program line by line. I find the debugger less useful when dealing with event driven gui code, where a single line of code can cause new events to be trigerred, which may in turn trigger other events. In this situation, the 'step through the code' approach doesn't let me see everything that is going on. The way I usually solve this is to 1) guess which events might be part of the problem, then 2) add breakpoints or logging to each of those events. The problem is that this approach is haphazard and time consuming. Is there a switch I can flick in the debugger to say 'log all gui events'? Or is there some code I can add to trap events, something like procedure GuiEventCalled(ev:Event) begin log(ev); ev.call(); end The end result I'm looking for is something like this (for example): FieldA.KeyDown FieldA.KeyPress FieldA.OnChange FieldA.OnExit FieldB.OnEnter This would take all the guesswork out of Delphi gui debugging. I am using Delphi 2010

    Read the article

  • Timing issues with playback of the HTML5 Audio API

    - by pat
    I'm using the following code to try to play a sound clip with the HTML5 Audio API: HTMLAudioElement.prototype.playClip = function(startTime, stopTime) { this.stopTime = stopTime; this.currentTime = startTime; this.play(); $(this).bind('timeupdate', function(){ if (this.ended || this.currentTime >= stopTime) { this.pause(); $(this).unbind('timeupdate'); } }); } I utilize this new playClip method as follows. First I have a link with some data attributes: <a href=# data-stop=1.051 data-start=0.000>And then I was thinking,</a> And finally this bit of jQuery which runs on $(document).ready to hook up a click on the link with the playback: $('a').click(function(ev){ $('a').click(function(ev){ var start = $(this).data('start'), stop = $(this).data('stop'), audio = $('audio').get(0), $audio = $(audio); ev.preventDefault(); audio.playClip(start,stop); }) This approach seems to work, but there's a frustrating bug: sometimes, the playback of a given clip plays beyond the correct data-stop time. I suspect it could have something to do with the timing of the timeupdate event, but I'm no JS guru and I don't know how to begin debugging the problem. Here are a few clues I've gathered: The same behavior appears to come up in both FF and Chrome. The playback of a given clip actually seems to vary a bit -- if I play the same clip a couple times in a row, it may over-play a different amount of time on each playing. Is the problem here the inherent accuracy of the Audio API? My app needs milliseconds. Is there a problem with the way I'm using jQuery to bind and unbind the timeupdate event? I tried using the jQuery-less approach with addEventListener but I couldn't get it to work. Thanks in advance, I would really love to know what's going wrong.

    Read the article

  • Trouble with jQuery Form Validation

    - by Sennheiser
    I'm making a form that has the following validation rules: no fields are "required", but if you enter an email, it must be valid, and if you enter a password, it must be at least 6 characters and match the confirm password field value. The form works flawlessly with no validation so I know it's not a PHP or HTML problem. Here's the jQuery code handling the form: $('#success').hide(); $('#pwerror').hide(); $('#emailError').hide(); $('#subSet').live('click',function() { //if any of the fields have a value if($("#chfn").val() != "" || $("#chln").val() != "" || $("#chpw").val() != "" || $("#chpw2").val() != "" || $("#chem").val() != "") { $ev = 1; $pv = 1; //validates an email if there is one, trips the valid variable flag if($("#chem").val() != "") { $("#profSet").validate({ rules: { chem: { email: true }, chpw: { required: false, minlength: 6 }, chpw2: { required: false, minlength: 6, equalTo: $("#chpw").val() } }, messages:{ chpw2: { equalTo: "Passwords must be the same." }, chpw: { minlength: "Password must be at least 6 characters." } } }); if(!($("#profSet").valid())) { $ev = 0; } } //if either password field is filled, start trying to validate it if($("#chpw").val() != "" || $("#chpw2").val() != "") { if(!($("#profSet").valid())) { $pv = 0; } } //if those two were valid if($pv == 1 && $ev == 1) { $.post('php/profSet.php', $('#profSet').serialize(), function(){ $('#profSet').hide(); $('#success').show(); }); } //if either was invalid, the error was already tripped, and this code exits here } }); The problem I'm having now is that the "passwords must be the same" error keeps getting triggered even if both fields are blank, or if they actually are the same. Therefore, the form cannot submit. Any help?

    Read the article

  • Top 5 reasons for using ASP.NET MVC 2 rather than ASP.NET MVC 1

    - by Richard Ev
    I've been using ASP.NET MVC 1 for a while now, and am keen to take advantage of the improvements in MVC 2. Things like validation seem greatly improved, and strongly-typed HTML helper methods look great. So, for those of you who have real-world practical experience of using ASP.NET MVC 1 and are now using MVC 2, what are your top 5 reasons for using MVC 2?

    Read the article

  • WPF: Master - detail view with two datagrids and in MVVM

    - by EV
    Hi, I'm trying to write a master - detail control that consists of a master datagrid and the detail datagrid. My scenario was following - I used the SelectedItem and bound it to a property in ModelView. The problem is - the SelectedItem in ViewModel is never used, so I can't get the information which item is selected in a master datagrid and cannot fetch the data for thos selection. The code is below: <toolkit:DataGrid ItemsSource="{Binding}" RowDetailsVisibilityMode="VisibleWhenSelected" SelectedItem="{Binding SelectedItemHandler, Mode=TwoWay}"></toolkit:DataGrid> And in ViewModel private CustomerObjects _selectedItem; public CustomerObjects SelectedItemHandler { get { return _selectedItem; } set { OnPropertyChanged("SelectedItem"); } } The code in SelectedItemHandler is never used. What could be the problem? Should I use another approach to create master - detail in MVVM?

    Read the article

  • WPF: how to find an element in a datatemplate from an itemscontrol

    - by EV
    Hi, I have the following problem: the application is using the custom itemscontrol called ToolBox. The elements of a toolbox are called toolboxitems and are custom contentcontrol. Now, the toolbox stores a number of images that are retrieved from a database and displayed. For that I use a datatemplate inside the toolbox control. However, when I try to drag and drop the elements, I don't get the image object but the database component. I thought that I should then traverse the structure to find the Image element. here's the code: Toolbox: public class Toolbox : ItemsControl { private Size defaultItemSize = new Size(65, 65); public Size DefaultItemSize { get { return this.defaultItemSize; } set { this.defaultItemSize = value; } } protected override DependencyObject GetContainerForItemOverride() { return new ToolboxItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return (item is ToolboxItem); } } ToolBoxItem: public class ToolboxItem : ContentControl { private Point? dragStartPoint = null; static ToolboxItem() { FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem), new FrameworkPropertyMetadata(typeof(ToolboxItem))); } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { base.OnPreviewMouseDown(e); this.dragStartPoint = new Point?(e.GetPosition(this)); } public String url { get; private set; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton != MouseButtonState.Pressed) { this.dragStartPoint = null; } if (this.dragStartPoint.HasValue) { Point position = e.GetPosition(this); if ((SystemParameters.MinimumHorizontalDragDistance <= Math.Abs((double)(position.X - this.dragStartPoint.Value.X))) || (SystemParameters.MinimumVerticalDragDistance <= Math.Abs((double)(position.Y - this.dragStartPoint.Value.Y)))) { string xamlString = XamlWriter.Save(this.Content); MessageBoxResult result = MessageBox.Show(xamlString); DataObject dataObject = new DataObject("DESIGNER_ITEM", xamlString); if (dataObject != null) { DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); } } e.Handled = true; } } private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild<childItem>(child); if (childOfChild != null) return childOfChild; } } return null; } } here is the xaml file for ToolBox and toolbox item: <Style TargetType="{x:Type s:ToolboxItem}"> <Setter Property="Control.Padding" Value="5" /> <Setter Property="ContentControl.HorizontalContentAlignment" Value="Stretch" /> <Setter Property="ContentControl.VerticalContentAlignment" Value="Stretch" /> <Setter Property="ToolTip" Value="{Binding ToolTip}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type s:ToolboxItem}"> <Grid> <Rectangle Name="Border" StrokeThickness="1" StrokeDashArray="2" Fill="Transparent" SnapsToDevicePixels="true" /> <ContentPresenter Content="{TemplateBinding ContentControl.Content}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" ContentTemplate="{TemplateBinding ContentTemplate}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Stroke" Value="Gray" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type s:Toolbox}"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="Focusable" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Border BorderThickness="{TemplateBinding Border.BorderThickness}" Padding="{TemplateBinding Control.Padding}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" SnapsToDevicePixels="True"> <ScrollViewer VerticalScrollBarVisibility="Auto"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel Margin="0,5,0,5" ItemHeight="{Binding Path=DefaultItemSize.Height, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" ItemWidth="{Binding Path=DefaultItemSize.Width, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" /> </ItemsPanelTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> Example usage: <Toolbox x:Name="NewLibrary" DefaultItemSize="55,55" ItemsSource="{Binding}" > <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <Image Source="{Binding Path=url}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </Toolbox> The object that I get is a database object. When using a static resource I get the Image object. How to retrieve this Image object from a datatemplate? I though that I could use this tutorial: http://msdn.microsoft.com/en-us/library/bb613579.aspx But it does not seem to solve the problem. Could anyone suggest a solution? Thanks!

    Read the article

  • Creating an Ajax.ActionLink that avoids all caching issues

    - by Richard Ev
    I am using an Ajax.ActionLink to display a partial view that shows a settings dialog (the modality of which is arranged using jQuery UI dialog). The issue I am running into is around browser caching. It is important that the user is never shown a cached settings dialog. In an attempt to achieve this I have written the following extension method that has the same method signature as the ActionLink method overload that I am using. /// <summary> /// Defines an AJAX ActionLink that effectively bypasses browser caching issues /// by adding an additional route value that contains a unique (actually DateTime.Now.Ticks) value. /// </summary> public static MvcHtmlString NonCachingActionLink(this AjaxHelper helper, string linkText, string actionName, string controllerName, System.Web.Routing.RouteValueDictionary routeValues, AjaxOptions ajaxOptions) { routeValues.Add("rnd", DateTime.Now.Ticks); return helper.ActionLink(linkText, actionName, controllerName, routeValues, ajaxOptions); } This works well between browser sessions (as the rnd route value gets re-calculated on page load), but not if the user is on the page, makes settings changes, saves them (which is done with another ajax call) and then re-displays the settings dialog. My next step is to look into creating my own ActionLink equivalent that re-calculates a random query string component as part of the onclick JavaScript event handler. Thoughts please.

    Read the article

  • Elmah is only logging 15 Errors

    - by Ev
    Hi, I've just starting looking at a site in place at work. They're using Elmah to log errors. It seems to be logging fine, but in the web interface, when I tell Elmah to show me 100 errors per page, it only shows the most recent 15. Then when I click on "Download Log" I only get shown 15 errors in the CSV. Anyone know how I can configure it to keep all the errors? Or can someone point me to some docs on how to do this? Thanks a lot! -Evan

    Read the article

  • jQuery UI datepicker performance

    - by Richard Ev
    I have a textbox on my web page that is used to specify a date, so I'd like to use the jQuery DatePicker. However, most of my users are locked into using IE6 and the performance of the jQuery DatePicker is a little sluggish in this browser. Can anyone recommend an alternate JavaScript date picker, or any means of improving the display performance of the jQuery DatePicker?

    Read the article

  • Architecting iPhone Views - seeking help on a specific issue + general advice

    - by Ev
    Hi there, I am a web developer (rails, python) that is new to iPhone development. I've done some desktop development in the past within the MS environment (C#). I'm trying to build a really simple iPhone application and I am confused by the way that views work in general. If someone can provide advice for my particular problem, along with some resources where I can learn how to architect iPhone views in the future, that would be awesome. I feel like a lot of the Apple documentation that I've come across is too specific - I am lacking a fundamental understanding of how views work on the iPhone. My particular problem looks like this: I need one view that displays some downloaded text content. This is the view that shows when the app loads, and it is pretty straightforward. Then I need a settings area (I've already decided I don't want to use the iPhone settings area). The settings area main page will have some text fields on it. It will also have a 2-row grouped table. Each cell in that table will take you to another view which also has a grouped table used for multi-select. I suspect that I can reuse the same view for these two final "detailed setting" views. In summary: home page settings main page detailed setting 1 detailed setting 2 Any help and advice appreciated.

    Read the article

  • WPF: How to connect to a sql ce 3.5 database with ADO.NET?

    - by EV
    Hi, I'm trying to write an application that has two DataGrids - the first one displays customers and the second one selected customer's records. I have generated the ADO.NET Entity Model and the connection property are set in App.config file. Now I want to populate the datagrids with the data from sql ce 3.5 database which does not support LINQ-TO-SQL. I used this code for the first datagrid in code behind: CompanyDBEntities db; private void Window_Loaded(object sender, RoutedEventArgs e) { db = new CompanyDBEntities(); ObjectQuery<Employees> departmentQuery = db.Employees; try { // lpgrid is the name of the first datagrid this.lpgrid.ItemsSource = departmentQuery; } catch (Exception ex) { MessageBox.Show(ex.Message); } However, the datagrid is empty although there are records in a database. It would also be better to use it in MVVM pattern but I'm not sure how does the ado.net and MVVM work together and if it is even possible to use them like that. Could anyone help? Thanks in advance.

    Read the article

  • ASP.NET MVC users - do you miss anything from WebForms?

    - by Richard Ev
    There are lots of articles and discussions about the differences between ASP.NET WebForms and ASP.NET MVC that compare the relative merits of the two frameworks. I have a different question for anyone who has experience using WebForms that has since moved to MVC: What is the number one thing that WebForms had, that MVC doesn't, that you really miss? Edit No-one has mentioned the WebForms validation controls. I am now working on some code that has a few dependant validation rules and implementing client-side validation for these is proving slow.

    Read the article

  • Integration Testing an Entire *Existing* Application (w/ automatic execution of test suite)

    - by Ev
    Hi there, I have just joined a team working on an existing Java web app. I have been tasked with creating an automated integration test suite that should run when developers commit to our continuous integration server (TeamCity), which automatically deploys to our staging server - so really the tests will be run against our staging web app server. I have read a lot of stuff about automated integration testing with frameworks like Watir, Selenium and RWebSpec. I have created tests in all of these and while I prefer Watir, I am open to anything. The thing that hasn't become clear to me is how to create an entire test suite for an application, and how to have that suite execute in it's entirety upon execution of some script. I can happily create individual tests of varying complexity, but there is a gap in my knowledge about how to tie everything together into something useful. Does anyone have any advice on how to create a full test suite and have it execute automatically? Thanks!

    Read the article

  • Model binding & derived model classes

    - by Richard Ev
    Does ASP.NET MVC offer any simple way to get model binding to work when you have model classes that inherit from others? In my scenario I have a View that is strongly typed to List<Person>. I have a couple of classes that inherit from Person, namely PersonTypeOne and PersonTypeTwo. I have three strongly typed partial views with names that match these class names (and render form elements for the properties of their respective models). This means that in my main View I can have the following code: <% for(int i = 0; i < Model.Count; i++) { Html.RenderPartial(Model[i].GetType().Name, Model[i]); } %> This works well, apart from when the user submits the form the relevant controller action method just gets a List<Person>, rather than a list of Person, PersonTypeOne and PersonTypeTwo. This is pretty much as expected as the form submission doesn't contain enough information to tell the default model binder to create any instances of PersonTypeOne and PersonTypeTwo classes. So, is there any way to get such functionality from the default model binder?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >