Search Results

Search found 6569 results on 263 pages for 'specification pattern'.

Page 33/263 | < Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >

  • Doubt about a particular pattern of Javascript class definition

    - by fenderplayer
    Recently i saw the following code that creates a class in javascript: var Model.Foo = function(){ // private stuff var a, b; // public properties this.attr1 = ''; this.attr2 = ''; if(Model.Foo._init === 'undefined'){ Model.Foo.prototype = { func1 : function(){ //...}, func2 : function(){ //... }, //other prototype functions } } Model.Foo._init = true; } // Instantiate and use the class as follows: var foo = new Model.Foo(); foo.func1(); I guess the _init variable is used to make sure we don't define the prototypes again. Also, i feel the code is more readable since i am placing everything in a function block (so in oop-speak, all attributes and methods are in one place). Do you see any issues with the code above? Any pitfalls of using this pattern if i need to create lots of classes in a big project?

    Read the article

  • [Bash] Save part of matching pattern to variable

    - by Ben
    I want to extract a substring matching a pattern and save it to a file. An example string: Apr 12 19:24:17 PC_NMG kernel: sd 11:0:0:0: [sdf] Attached SCSI removable disk I want to extract the part between the brackets, in this case []. I tried to do something like grep -e '[$subtext]' to save the text in the brackets to a variable. Of course it doesn't work, but I am looking for a way similar to this. It would be very elegant to include a variable in a regex like this. What can I do best? Thanks!

    Read the article

  • What Design Pattern To Replace 'CurrentStep' Variable

    - by Rob P.
    Tried to search but didn't know how to phrase it. I've got some code that is essentially... Private CurMajorStep as Integer = 0 Private CurMinorStep as Integer = 0 Public Sub PerformNextStep() Select Case iMajorStep Case 0 ThingOne() Case 1 ThingTwo() Case 2 ThingThree() Case 3 ThingFour() Case 4 AnythingElse() Case 5 Finish() End Select End Sub And then, in some of those, the CurMinorStep keeps track of the current state of that particular 'step'. I hope that all makes sense. The code is messy and I know it's going to be problematic to maintain. Can someone point me to a clean OO pattern to handle this?

    Read the article

  • How to construct a flowchart/storyboard in a Func Spec

    - by PeterQ
    Hey I'm a bit embarrassed to write a post on this topic, but I would appreciate the help. At my school, the CS kids (myself included) have created a nice, little program that is built for incoming Chem/Bio students. It consists of several modules that reviews topics they should have a firm grasp on before they start their classes. It's a nice tool since it cuts down on reviewing the material in class but also allows the students to do a quick diagnostic to fix any problems. Now, I'm in charge of constructing a simple interface that reports on the progress of the group and individual students. The interface is pretty simple. It's just a window that pops up, and it has three tabs: the first tab is a "cumulative" report of all of students. The secnod tab has a drop down box that lists the students and once a student is selected, a report for him/her comes up. And the third tab is simply a description of all of the terms used in the 1st and 2nd tabs. Now, I'm trying to be a good CS student and write a func. spec for my interface. My problem comes with the fact that I'd like to insert a little flowchart using Visio. Problem is, and I'm quite embarrassed to admit this, I don't know how to construct the flowchart/storyboard. For instance, I know I start with a "Start/Click Icon" in a rectangle. Then where do I go? Do I draw three arrrows (one going to each tab) and then describing what goes on? In tab one, the only thing that happens is that the user will select a "sort" method in the drop down box. This will sort the list. The End. Similarly, if the user selects the second tab, then he will go to a drop down box with the student names. Selecting a name will bring up student info. And the third tab is just a list of unfamiliar terms coming from the first or second tab. I wanted to storyboard/flowchart what I'm doing, but I'm unclear how to go about it. Any help would be appreciated! (Just to clarify, I'm not having trouble with using Visio, but I don't know how one goes about construct a storyboard or determining the procedure for constructing one)

    Read the article

  • Is this a right way to use NHibernate?

    - by Venemo
    I spent the rest of the evening reading StackOverflow questions and also some blog entries and links about the subject. All of them turned out to be very helpful, but I still feel that they don't really answer my question. So, I'm developing a simple web application. I'd like to create a reusable data access layer which I can later reuse in other solutions. 99% of these will be web applications. This seems to be a good excuse for me to learn NHibernate and some of the patterns around it. My goals are the following: I don't want the business logic layer to know ANYTHING about the inner workings of the database, nor NHibernate itself. I want the business logic layer to have the least possible number of assumptions about the data access layer. I want the data access layer as simplistic and easy-to-use as possible. This is going to be a simple project, so I don't want to overcomplicate anything. I want the data access layer to be as non-intrusive as possible. Will all this in mind, I decided to use the popular repository pattern. I read about this subject on this site and on various dev blogs, and I heard some stuff about the unit of work pattern. I also looked around and checked out various implementations. (Including FubuMVC contrib, and SharpArchitecture, and stuff on some blogs.) I found out that most of these operate with the same principle: They create a "unit of work" which is instantiated when a repository is instantiated, they start a transaction, do stuff, and commit, and then start all over again. So, only one ISession per Repository and that's it. Then the client code needs to instantiate a repository, do stuff with it, and then dispose. This usage pattern doesn't meet my need of being as simplistic as possible, so I began thinking about something else. I found out that NHibernate already has something which makes custom "unit of work" implementations unnecessary, and that is the CurrentSessionContext class. If I configure the session context correctly, and do the clean up when necessary, I'm good to go. So, I came up with this: I have a static class called NHibernateHelper. Firstly, it has a static property called CurrentSessionFactory, which upon first call, instantiates a session factory and stores it in a static field. (One ISessionFactory per one AppDomain is good enough.) Then, more importantly, it has a CurrentSession static property, which checks if there is an ISession bound to the current session context, and if not, creates one, and binds it, and it returns with the ISession bound to the current session context. Because it will be used mostly with WebSessionContext (so, one ISession per HttpRequest, although for the unit tests, I configured ThreadStaticSessionContext), it should work seamlessly. And after creating and binding an ISession, it hooks an event handler to the HttpContext.Current.ApplicationInstance.EndRequest event, which takes care of cleaning up the ISession after the request ends. (Of course, it only does this if it is really running in a web environment.) So, with all this set up, the NHibernateHelper will always be able to return a valid ISession, so there is no need to instantiate a Repository instance for the "unit of work" to operate properly. Instead, the Repository is a static class which operates with the ISession from the NHibernateHelper.CurrentSession property, and exposes some functionality through that. I'm curious, what do you think about this? Is it a valid way of thinking, or am I completely off track here?

    Read the article

  • Entity Framework RC1 DbContext query issue

    - by Steve
    I'm trying to implement the repository pattern using entity framework code first rc 1. The problem I am running into is with creating the DbContext. I have an ioc container resolving the IRepository and it has a contextprovider which just news up a new DbContext with a connection string in a windsor.config file. With linq2sql this part was no problem but EF seems to be choking. I'll describe the problem below with an example. I've pulled out the code to simplify things a bit so that is why you don't see any repository pattern stuff here. just sorta what is happening without all the extra code and classes. using (var context = new PlssContext()) { var x = context.Set<User>(); var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault(); } using (var context2 = new DbContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=PLSS.Models.PlssContext;Integrated Security=True;MultipleActiveResultSets=True")) { var x = context2.Set<User>(); var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault(); } PlssContext is where I am creating my DbContext class. The repository pattern doesn't know anything about PlssContext. The best I thought I could do was create a DbContext with the connection string to the sqlexpress database and query the data that way. The connection string in the var context2 was grabbed from the context after newing up the PlssContext object. So they are pointing at the same sqlexpress database. The first query works. The second query fails miserably with this error: The model backing the 'DbContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data. on this line var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault(); Here is my DbContext namespace PLSS.Models { public class PlssContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Corner> Corners { get; set; } public DbSet<Lookup_County> Lookup_County { get; set; } public DbSet<Lookup_Accuracy> Lookup_Accuracy { get; set; } public DbSet<Lookup_MonumentStatus> Lookup_MonumentStatus { get; set; } public DbSet<Lookup_CoordinateSystem> Lookup_CoordinateSystem { get; set; } public class Initializer : DropCreateDatabaseAlways<PlssContext> { protected override void Seed(PlssContext context) { I've tried all of the Initializer strategies with the same errors. I don't think the database is changing. If I remove the modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); Then the error returns is The entity type User is not part of the model for the current context. Which sort of makes sense. But how do you bring this all together?

    Read the article

  • Web.xml: Are url-pattern tags relative to each other?

    - by sixtyfootersdude
    <servlet-mapping> <servlet-name>myName</servlet-name> <url-pattern>/aName</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> ... <url-pattern> /* </url-pattern> </web-resource-collection> ... </security-constraint> This is an excerpt from web.xml (using it to configure a jboss/tomcat webservice). Just wondering if the url-pattern in web-resource-collection is relative to the url-pattern in servlet-mapping.

    Read the article

  • Web.xml: Are url-pattern tags relitive to each other?

    - by sixtyfootersdude
    <servlet-mapping> <servlet-name>myName</servlet-name> <url-pattern>/aName</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> ... <url-pattern> /* </url-pattern> </web-resource-collection> ... </security-constraint> This is an excerpt from web.xml (using it to configure a jboss/tomcat webservice). Just wondering if the url-pattern in web-resource-collection is relative to the url-pattern in servlet-mapping.

    Read the article

  • MS DOS function like ipconfig to get system performance specs?

    - by JustADude
    I am aware of MSINFO32, but I'm wondering if there is a MS DOS command similar to ipconfig in order to get system specifications? I would like for the system specifications to be displayed in the MS DOS prompt. I would like to see at least: CPU RAM BUS speed Thanks for any insights. Edit: I am unable to install any other software, so just have to use existing DOS programming commands to extract this information. Thank you again. 2nd Edit: Whoops. Using Windows XP and Windows Vista.

    Read the article

  • What's the best way to link formal specs to JIRA enchancement requests?

    - by Adam
    What's the best way to link formal specs to JIRA enhancement requests? I want to track changes to specifications using JIRA. Ideally, I'd like to refer to a functional ID reference in a JIRA ticket (e.g. MYAPPAPPROVAL LOGICMAIN SCREEN), so that program managers can retrospectively categorise defects. The reason for this, is so that QA scripts and documentation tickets can be searched/categorised meaningfully in the tracking system. There seems to be a million possible ways to do this, e.g. should I write a custom component to select functional IDs from a tree? should I write the specs in confluence, or another CMS with a TrackBack facility? should I include a link to the documentation URL? should I use some other 3rd party plugin application? should I use some Atlassian application that i'm unaware of? am I using the wrong tracking tool/process to measure spec growth? What's the best way, in your experience?

    Read the article

  • Microsoft Press Deal of the Day - 13/April/2012 - Building Enterprise Applications with Windows® Presentation Foundation and the MVVM Pattern

    - by TATWORTH
    Today's deal of the day from Microsoft Press at http://shop.oreilly.com/product/0790145309686.do is Building Enterprise Applications with Windows® Presentation Foundation and the MVVM Pattern"Simplify and improve business application development by applying the MVVM pattern to Windows Presentation Foundation (WPF) and Microsoft® Silverlight® 4. With this hands-on guide, you'll use MVVM with data binding, commands, and behaviors to create user interfaces loosely coupled to business logic. MVVM is ideal for .NET developers working with WPF and Silverlight—whether or not you have experience building enterprise applications."

    Read the article

  • Tests unitaires d'un DomainService WCF RIA : pattern Repository, un tutoriel de Kyle McClellan, traduit par Deepin Prayag

    Citation: Étant donné que WCF RIA Services emploie un « pipeline pattern » pour invoquer vos opérations DomainService, il n'est pas toujours évident de savoir comment les tester. Dans cette série d'articles nous allons voir un petit DomainService et comment le tester. Entre autres nous allons voir comment implémenter une IDomainServiceFactory personnalisée, comment implémenter le pattern Repository, et comment utiliser la DomainServiceTestHos...

    Read the article

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

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

    Read the article

  • MVC - Cocoa interface - Cocoa Design pattern book

    - by Idan
    So I started reading this book: http://www.amazon.com/Cocoa-Design-Patterns-Erik-Buck/dp/0321535022 On chapter 2 it explains about the MVC design pattern and gives and example which I need some clarification to. The simple example shows a view with the following fields: hourlyRate, WorkHours, Standarthours , salary. The example is devided into 3 parts : View - contains some text fiels and a table (the table contains a list of employees' data). Controller - comprised of NSArrayController class (contains an array of MyEmployee) Model - MyEmployee class which describes an employee. MyEmployee class has one method which return the salary according to the calculation logic, and attributes in accordance with the view UI controls. MyEmployee inherits from NSManagedObject. Few things i'm not sure of : 1. Inside the MyEmplpyee class implemenation file, the calculation method gets the class attributes using sentence like " [[self valueForKey:@"hourlyRate"] floatValue];" Howevern, inside the header there is no data member named hourlyRate or any of the view fields. I'm not quite sure how does it work, and how it gets the value from the right view field. (does it have to be the same name as the field name in the view). maybe the conncetion is made somehow using the Interface builder and was not shown in the book ? and more important: 2. how does it seperate the view from the model ? let's say ,as the book implies might happen, I decide one day to remove one of the fields in the view. as far as I understand, that means changing the way the salary method works in MyEmplpyee (cause we have one field less) , and removing one attribute from the same calss. So how is that separate the View from the Model if changing one reflect on the other ? I guess I get something wrong... Any comments ? Thanks

    Read the article

  • Business Logic Layer Pattern on Rails? MVCL

    - by Fabiano PS
    That is a broad question, and I appreciate no short/dumb asnwers like: "Oh that is the model job, this quest is retarded (period)" PROBLEM Where I work at people created a system over 2 years for managing the manufacture process over demand in the most simplified still broad as possible, involving selling, buying, assemble, The system is coded over Ruby On Rails. The app has been changed lots of times and the result is a mess on callbacks (some are called several times), 200+ models, and fat controllers: Total bad. The QUESTION is, if there is a gem, or pattern designed to handle Rails large app logic? The logic whould be able to fully talk to models (whose only concern would be data format handling and validation) What I EXPECT is to reduce complexity from various controllers, and hard to track callbacks into files with the responsibility to handle a business operation logic. In some cases there is the need to wait for a response, in others, only validation of the input is enough and a bg process would take place. ie: -- Sell some products (need to wait the operation to finish) 1. Set a View able to get the products input 2. Controller gets the product list inputed by employee and call the logic Logic::ExecuteWithResponse('sell', 'products', :prods => @product_list_with_qtt, :when => @date, :employee => current_user() ) This Logic would handle buying order, assemble order, machine schedule, warehouse reservation, and others. Have in mind that a callback on SalesOrder is not enough, since it depends on where it is called (no field for that), depends on the class of the user, among other stuff not visible for the model, or in some cases it would take long for the model to process.

    Read the article

  • Java exception handling in non sequential tasks (pattern/good practice)

    - by Hernán Eche
    There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...) But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc.. For that kind of tasks, I would like to know a java best practice or pattern for manage exceptions.. The java simple way is: getUFO { try { loadSoundDriver(); loadUsbDriver(); loadAlienDetectorDriver(); loadKeyboardDriver(); } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } But what about having an exception in one of the actions but wanting to try with the next ones?? I've thought this approach, but don't seem to be a good use for exceptions I don't know if it works, doesn't matter, it's really awful!! getUFO { Exception ex=null; try { try{ loadSoundDriver(); }catch (Exception e) { ex=e; } try{ loadUsbDriver(); }catch (Exception e) { ex=e; } try{ loadAlienDetectorDriver(); }catch (Exception e) { ex=e; } try{ loadKeyboardDriver() }catch (Exception e) { ex=e; } close the file; if(ex!=null) { throw ex; } } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } seems not complicated to find a better practice for doing that.. I still didn't thanks for any advice

    Read the article

  • Pattern for sharing data between views (MVP or MVVM)

    - by Dovix
    What is a good pattern for sharing data between related views?. I have an application where 1 form contains many small views, each views behaves independently from each other more or less (they communicate/interact via an event bus). Every so often I need to pass the same objects to the child views. Sometimes I need this same object to be passed to a child view and then the child passes it onto another child itself contains. What is a good approach to sharing this data between all the views contained within the parent form (view) ? I have looked into CAB and their approach and every "view" has a "root work item" this work item has dictionary that contains a shared "state" between the views that are contained. Is this the best approach? just a shared dictionary all the views under a root view can access? My current approach right now is to have a function on the view that allows one to set the object for that view. Something like view.SetCustomer(Customer c); then if the view contains a child view it knows to set it on the child view ala: this.childview1.SetCustomer(c); The application is written in C# 3.5, for winforms using MVP with structure map as a IoC/DI provider.

    Read the article

  • Seeking help with a MT design pattern

    - by SamG
    I have a queue of 1000 work items and a n-proc machine (assume n = 4).The main thread spawns n (=4) worker threads at a time ( 25 outer iterations) and waits for all threads to complete before processing the next n (=4) items until the entire queue is processed for(i= 0 to queue.Length / numprocs) for(j= 0 to numprocs) { CreateThread(WorkerThread,WorkItem) } WaitForMultipleObjects(threadHandle[]) The work done by each (worker) thread is not homogeneous.Therefore in 1 batch (of n) if thread 1 spends 1000 s doing work and rest of the 3 threads only 1 s , above design is inefficient,becaue after 1 sec other 3 processors are idling. Besides there is no pooling - 1000 distinct threads are being created How do I use the NT thread pool (I am not familiar enough- hence the long winded question) and QueueUserWorkitem to achieve the above. The following constraints should hold The main thread requires that all worker items are processed before it can proceed.So I would think that a waitall like construct above is required I want to create as many threads as processors (ie not 1000 threads at a time) Also I dont want to create 1000 distinct events, pass to the worker thread, and wait on all events using the QueueUserWorkitem API or otherwise Exisitng code is in C++.Prefer C++ because I dont know c# I suspect that the above is a very common pattern and was looking for input from you folks.

    Read the article

  • IRequest / IResponse Pattern

    - by traderde
    I am trying to create an Interface-based Request/Response pattern for Web API requests to allow for asynchronous consumer/producer processing, but not sure how I would know what the underlying IResponse class is. public void Run() { List<IRequest> requests = new List<IRequest>(); List<IResponse> responses = new List<IResponse(); requests.Add(AmazonWebRequest); //should be object, trying to keep it simple requests.Add(EBayWebRequest); //should be object, trying to keep it simple foreach (IRequest req in requests) { responses.Add(req.GetResponse()); } foreach (IResponse resp in response) { typeof resp???? } } interface IRequest { IResponse GetResponse(); } interface IResponse { } public class AmazonWebServiceRequest : IRequest { public AmazonWebServiceRequest() { //get data; } public IResponse GetResponse() { AmazonWebServiceRequest request = new AmazonWebServiceRequest(); return (IResponse)request; } } public class AmazonWebServiceResponse : IResponse { XmlDocument _xml; public AmazonWebServiceResponse(XmlDocument xml) { _xml = xml; _parseXml(); } private void _parseXml() { //parse Xml into object; } } public class EBayWebRequest : IRequest { public EBayWebRequest () { //get data; } public IResponse GetResponse() { EBayWebRequest request = new EBayWebRequest(); return (IResponse)request; } } public class EBayWebResponse : IResponse { XmlDocument _xml; public EBayWebResponse(XmlDocument xml) { _xml = xml; _parseXml(); } private void _parseXml() { //parse Xml into object; } }

    Read the article

  • Business Layer Pattern on Rails? MVCL

    - by Fabiano PS
    That is a broad question, and I appreciate no short/dumb asnwers like: "Oh that is the model job, this quest is retarded (period)" PROBLEM Where I work at people created a system over 2 years for managing the manufacture process over demand in the most simplified still broad as possible, involving selling, buying, assemble, The system is coded over Ruby On Rails. The result has been changed lots of times and the result is a mess on callbacks (some are called several times), 200+ models, and fat controllers: Total bad. The QUESTION is, if there is a gem, or pattern designed to handle Rails large app logic? The logic whould be able to fully talk to models (whose only concern would be data format handling and validation) What I EXPECT is to reduce complexity from various controllers, and hard to track callbacks into files with the responsibility to handle a business operation logic. In some cases there is the need to wait for a response, in others, only validation of the input is enough and a bg process would take place. ie: -- Sell some products (need to wait the operation to finish) 1. Set a View able to get the products input 2. Controller gets the product list inputed by employee and call the logic Logic::ExecuteWithResponse('sell', 'products', :prods => @product_list_with_qtt, :when => @date, :employee => current_user() ) This Logic would handle buying order, assemble order, machine schedule, warehouse reservation, and others

    Read the article

  • Repeated properties design pattern

    - by Mark
    I have a DownloadManager class that manages multiple DownloadItem objects. Each DownloadItem has events like ProgressChanged and DownloadCompleted. Usually you want to use the same event handler for all download items, so it's a bit annoying to have to set the event handlers over and over again for each DownloadItem. Thus, I need to decide which pattern to use: Use one DownloadItem as a template and clone it as necessary var dm = DownloadManager(); var di = DownloadItem(); di.ProgressChanged += new DownloadProgressChangedEventHandler(di_ProgressChanged); di.DownloadCompleted += new DownloadProgressChangedEventHandler(di_DownloadCompleted); DownloadItem newDi; newDi = di.Clone(); newDi.Uri = "http://google.com"; dm.Enqueue(newDi); newDi = di.Clone(); newDi.Uri = "http://yahoo.com"; dm.Enqueue(newDi); Set the event handlers on the DownloadManager instead and have it copy the events over to each DownloadItem that is enqeued. var dm = DownloadManager(); dm.ProgressChanged += new DownloadProgressChangedEventHandler(di_ProgressChanged); dm.DownloadCompleted += new DownloadProgressChangedEventHandler(di_DownloadCompleted); dm.Enqueue(new DownloadItem("http://google.com")); dm.Enqueue(new DownloadItem("http://yahoo.com")); Or use some kind of factory var dm = DownloadManager(); var dif = DownloadItemFactory(); dif.ProgressChanged += new DownloadProgressChangedEventHandler(di_ProgressChanged); dif.DownloadCompleted += new DownloadProgressChangedEventHandler(di_DownloadCompleted); dm.Enqueue(dif.Create("http://google.com")); dm.Enqueue(dif.Create("http://yahoo.com")); What would you recommend?

    Read the article

  • Factory Pattern: Determining concrete factory class instantiation?

    - by Chris
    I'm trying to learn patterns and I'm stuck on determining how or where a Factory Pattern determines what class to instanciate. If I have a Application that calls the factory and sends it, say, an xml config file to determine what type of action to take, where does that logic for interpreting the config file happen? THE FACTORY using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace myNamespace { public abstract class SourceFactory { abstract public UploadSource getUploadSource(); } public class TextSourceFactory : SourceFactory { public override UploadSource getUploadSource() { return new TextUploadSource(); } } public class XmlSourceFacotry : SourceFactory { public override UploadSource getUploadSource() { return new XmlUploadSource(); } } public class SqlSourceFactory : SourceFactory { public override UploadSource getUploadSource() { return new SqlUploadSource(); } } } THE CLASSES using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace myNamespace { public abstract class UploadSource { abstract public void Execute(); } public class TextUploadSource : UploadSource { public override void Execute() { Console.WriteLine("You executed a text upload source"); } } public class XmlUploadSource : UploadSource { public override void Execute() { Console.WriteLine("You executed an XML upload source"); } } public class SqlUploadSource : UploadSource { public override void Execute() { Console.WriteLine("You executed a SQL upload source"); } } }

    Read the article

  • Validation with State Pattern for Multi-Page Forms in ASP.NET

    - by philrabin
    I'm trying to implement the state pattern for a multi-page registration form. The data on each page will be accumulated and stored in a session object. Should validation (including service layer calls to the DB) occur on the page level or inside each state class? In other words, should the concrete implementation of IState be concerned with the validation or should it be given a fully populated and valid object? See "EmptyFormState" class below: namespace Example { public class Registrar { private readonly IState formEmptyState; private readonly IState baseInformationComplete; public RegistrarSessionData RegistrarSessionData { get; set;} public Registrar() { RegistrarSessionData = new RegistrarSessionData(); formEmptyState = new EmptyFormState(this); baseInformationComplete = new BasicInfoCompleteState(this); State = formEmptyState; } public IState State { get; set; } public void SubmitData(RegistrarSessionData data) { State.SubmitData(data); } public void ProceedToNextStep() { State.ProceedToNextStep(); } } //actual data stored in the session //to be populated by page public class RegistrarSessionData { public string FirstName { get; set; } public string LastName { get; set; } //will include values of all 4 forms } //State Interface public interface IState { void SubmitData(RegistrarSessionData data); void ProceedToNextStep(); } //Concrete implementation of IState //Beginning state - no data public class EmptyFormState : IState { private readonly Registrar registrar; public EmptyFormState(Registrar registrar) { this.registrar = registrar; } public void SubmitData(RegistrarSessionData data) { //Should Validation occur here? //Should each state object contain a validation class? (IValidator ?) //Should this throw an exception? } public void ProceedToNextStep() { registrar.State = new BasicInfoCompleteState(registrar); } } //Next step, will have 4 in total public class BasicInfoCompleteState : IState { private readonly Registrar registrar; public BasicInfoCompleteState(Registrar registrar) { this.registrar = registrar; } public void SubmitData(RegistrarSessionData data) { //etc } public void ProceedToNextStep() { //etc } } }

    Read the article

  • Best pattern to load enumerated values from DAL using WCF RIA Services

    - by Dale Halliwell
    I would like to be able to load several RIA entitysets in a single call without chaining/nesting several small LoadOperations together so that they load sequentially. I have several pages that have a number of comboboxes on them. These comboboxes are populated with static values from a database (for example status values). Right now I preload these values in my VM by one method that strings together a series of LoadOperations for each type that I want to load. For example: public void LoadEnums() { context.Load(context.GetMyStatusValues1Query()).Completed += (s, e) => { this.StatusValues1 = context.StatusValues1; context.Load(context.GetMyStatusValues2()).Completed += (s1, e1) => { this.StatusValues2 = context.StatusValues2; context.Load(context.GetMyStatusValues3Query()).Completed += (s2, e2) => { this.StatusValues3 = context.StatusValues3; (....and so on) }; }; }; }; While this works fine, it seems a bit nasty. Also, I would like to know when the last loadoperation completes so that I can load whatever entity I want to work on after this, so that these enumerated values resolve properly in form elements like comboboxes and listboxes. (I think) I can't do this easily above without creating a delegate and calling that on the completion of the last loadoperation. So my question is: does anyone out there know a better pattern to use, ideally where I can load all my static entitysets in a single LoadOperation?

    Read the article

  • NHibernate: how to handle entity-based validation using session-per-request pattern, without control

    - by Seth Petry-Johnson
    What is the best way to do entity-based validation (each entity class has an IsValid() method that validates its internal members) in ASP.NET MVC, with a "session-per-request" model, where the controller has zero (or limited) knowledge of the ISession? Here's the pattern I'm using: Get an entity by ID, using an IFooRepository that wraps the current NH session. This returns a connected entity instance. Load the entity with potentially invalid data, coming from the form post. Validate the entity by callings its IsValid() method. If valid, call IFooRepository.Save(entity). Otherwise, display error message. The session is currently opened when the request begins and flushed when the request ends. Since my entity is connected to a session, flushing the session attempts to save the changes even if the object is invalid. What's the best way to keep validation logic in the entity class, limit controller knowledge of NH, and avoid saving invalid changes at the end of a request? Option 1: Explicitly evict on validation failure, implicitly flush: if the validation fails, I could manually evict the invalid object in the action method. If successful, I do nothing and the session is automatically flushed. Con: error prone and counter-intuitive ("I didn't call .Save(), why are my invalid changes being saved anyways?") Option 2: Explicitly flush, do nothing by default: By default I can dispose of the session on request end, only flushing if the controller indicates success. I'd probably create a SaveChanges() method in my base controller that sets a flag indicating success, and then query this flag when closing the session at request end. Pro: More intuitive to troubleshoot if dev forgets this step [relative to option 1] Con: I have to call IRepository.Save(entity)' and SaveChanges(). Option 3: Always work with disconnected objects: I could modify my repositories to return disconnected/transient objects, and modify the Repo.Save() method to re-attach them. Pro: Most intuitive, given that controllers don't know about NH. Con: Does this defeat many of the benefits I'd get from NH?

    Read the article

< Previous Page | 29 30 31 32 33 34 35 36 37 38 39 40  | Next Page >