Search Results

Search found 749 results on 30 pages for 'giuseppe di federico'.

Page 26/30 | < Previous Page | 22 23 24 25 26 27 28 29 30  | Next Page >

  • ASP.NET MVC unit testing

    - by Simon Lomax
    Hi, I'm getting started with unit testing and trying to do some TDD. I've read a fair bit about the subject and written a few tests. I just want to know if the following is the right approach. I want to add the usual "contact us" facility on my web site. You know the thing, the user fills out a form with their email address, enters a brief message and hits a button to post the form back. The model binders do their stuff and my action method accepts the posted data as a model. The action method would then parse the model and use smtp to send an email to the web site administrator infoming him/her that somebody filled out the contact form on their site. Now for the question .... In order to test this, would I be right in creating an interface IDeliver that has a method Send(emailAddress, message) to accept the email address and message body. Implement the inteface in a concrete class and let that class deal with smtp stuff and actually send the mail. If I add the inteface as a parameter to my controller constructor I can then use DI and IoC to inject the concrete class into the controller. But when unit testing I can create a fake or mock version of my IDeliver and do assertions on that. The reason I ask is that I've seen other examples of people generating interfaces for SmtpClient and then mocking that. Is there really any need to go that far or am I not understanding this stuff?

    Read the article

  • Spring 3.0 vs J2EE 6.0

    - by StudiousJoseph
    Hi everybody, I'm confronted with a situation... I've been asked to give an advise regarding which approach to take, in terms of J2EE development between Spring 3.0 and J2EE 6.0. I was, and still am, a promoter of Spring 2.5 over classic J2EE 5 development, specially with JBoss, I even migrated old apps to Spring and influenced the re-definition of the development policy here to include Spring specific APIs, and helped the development of a strategic plan to foster more lightweight solutions like Spring + Tomcat, instead of the heavier ones of JBoss, right now, we're using JBoss merely as a Web container, having what i call the "container inside the container paradox", that is, having Spring apps, with most of its APIs, running inside JBoss, So we're in the process of migrating to tomcat. However, with the coming of J2EE 6.0 many features, that made Spring attractive at that time, easy deployment, less-coupling, even some sort of D.I, etc, seems to have been mimicked, in one way or the other. JSF 2.0, JPA 2.0, WebBeans, WebProfiles, etc. So, the question goes... From your point of view, how save, and logical, it is to continue to invest in a non-standard J2EE development framework like Spring given the new perspectives offered by J2EE 6.0? Can we talk about maybe 3 or 4 more years of Spring development, or do you recommend early adoption of J2EE 6.0 APIs and it's practices? I'll appreciate any insights with this...

    Read the article

  • new Statefull session bean instance without calling lookup

    - by kislo_metal
    Hi! Scenario: I have @Singleton UserFactory (@Stateless could be) , it`s method createSession() generating @Statefull UserSession bean by manual lookup. If I am injecting by DI @EJB - i will get same instance during calling fromFactory() method(as it should be) What I want - is to get new instance of UserSession without preforming lookup. Q1: how could I call new instance of @Statefull session bean? Code: @Singleton @Startup @LocalBean public class UserFactory { @EJB private UserSession session; public UserFactory() { } @Schedule(second = "*/1", minute = "*", hour = "*") public void creatingInstances(){ try { InitialContext ctx = new InitialContext(); UserSession session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } } @Schedule(second = "*/1", minute = "*", hour = "*") public void fromFactory(){ System.out.println("in singleton UUID " +session.getSessionUUID()); } public UserSession creatSession(){ UserSession session2 = null; try { InitialContext ctx = new InitialContext(); session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } return session2; } } As I understand, calling of session.getClass().newInstance(); is not a best idea Q2 : is it true? I am using glassfish v3, ejb 3.1.

    Read the article

  • Can I use my Ninject .NET project within Orchard CMS?

    - by Mattias Z
    I am creating a website using Orchard CMS and I have an external .NET project written with Ninject for dependency injection which I would like to use together with a module within Orchard CMS. I know that Orchard uses Autofac for dependency injection and this is causing me problems since I never worked with DI before. I have created a Autofac module UserModule which registers the source UserRegistrationSource and I configured Orchard to load the module like this: OrchardStarter.cs .... builder.RegisterModule(new UserModule()); .... UserModule.cs public class UserModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterSource(new UserRegistrationSource()); base.Load(builder); } } UserRegistrationSource.cs public class UserRegistrationSource : IRegistrationSource { public bool IsAdapterForIndividualComponents { get { return false; } } public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var serviceWithType = service as IServiceWithType; if (serviceWithType == null) yield break; var serviceType = serviceWithType.ServiceType; if (!serviceType.IsInterface || !typeof(IUserServices).IsAssignableFrom(serviceType) || serviceType == typeof(IUserServices)) yield break; var registrationBuilder = ... yield return registrationBuilder.CreateRegistration(); } } But now I'm stuck... Should I somehow try to resolve the dependencies in UserRegistrationSource by getting the requested types from the Ninject container (kernel) with Autofac or is this the wrong approach? Or should the Ninject kernel do the resolves for Autofac for the external project?

    Read the article

  • Can I use a static cache Helper method in a NET MVC controller?

    - by Euston
    I realise there have been a few posts regarding where to add a cache check/update and the separation of concerns between the controller, the model and the caching code. There are two great examples that I have tried to work with but being new to MVC I wonder which one is the cleanest and suits the MVC methodology the best? I know you need to take into account DI and unit testing. Example 1 (Helper method with delegate) ...in controller var myObject = CacheDataHelper.Get(thisID, () => WebServiceServiceWrapper.GetMyObjectBythisID(thisID)); Example 2 (check for cache in model class) in controller var myObject = WebServiceServiceWrapper.GetMyObjectBythisID(thisID)); then in model class.............. if (!CacheDataHelper.Get(cachekey, out myObject)) { //do some repository processing // Add obect to cache CacheDataHelper.Add(myObject, cachekey); } Both use a static cache helper class but the first example uses a method signature with a delegate method passed in that has the name of the repository method being called. If the data is not in cache the method is called and the cache helper class handles the adding or updating to the current cache. In the second example the cache check is part of the repository method with an extra line to call the cache helper add method to update the current cache. Due to my lack of experience and knowledge I am not sure which one is best suited to MVC. I like the idea of calling the cache helper with the delegate method name in order to remove any cache code in the repository but I am not sure if using the static method in the controller is ideal? The second example deals with the above but now there is no separation between the caching check and the repository lookup. Perhaps that is not a problem as you know it requires caching anyway?

    Read the article

  • Problem with close socket

    - by zp26
    Hi, I have a problem with my socket program. I create the client program (my code is below) I have a problem when i close the socket with the disconnect method. Can i help me? Thanks and sorry for my English XP CFSocketRef s; -(void)CreaConnessione { CFSocketError errore; struct sockaddr_in sin; CFDataRef address; CFRunLoopSourceRef source; CFSocketContext context = { 0, self, NULL, NULL, NULL }; s = CFSocketCreate( NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack, AcceptDataCallback, &context); memset(&sin, 0, sizeof(sin)); int port = [fieldPorta.text intValue]; NSString *tempIp = fieldIndirizzo.text; const char *ip = [tempIp UTF8String]; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = (long)inet_addr(ip); address = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin)); errore = CFSocketConnectToAddress(s, address, 0); if(errore == 0){ buttonInvioMess.enabled = TRUE; fieldMessaggioInvio.enabled = TRUE; labelTemp.text = [NSString stringWithFormat:@"Connesso al Server"]; CFRelease(address); source = CFSocketCreateRunLoopSource(NULL, s, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode); CFRelease(source); CFRunLoopRun(); } else{ labelTemp.text = [NSString stringWithFormat:@"Errore di connessione. Verificare Ip e Porta"]; switchConnection.on = FALSE; } } //the socket doesn't disconnect -(void)Disconnetti{ CFSocketInvalidate(s); CFRelease(s); } -(IBAction)Connetti { if(switchConnection.on) [self CreaConnessione]; else [self Disconnetti]; }

    Read the article

  • Using StructureMap to create classes by a name?

    - by Bevan
    How can I use StructureMap to resolve to an appropriate implementation of an interface based on a name stored in an attribute? In my project, I have many different kinds of widgets, each descending from IWidget, and each decorated with an attribute specifying the kind of associated element. To illustrate: [Configuration("header")] public class HeaderWidget : IWidget { } [Configuration("linegraph")] public class LineGraphWidget : IWidget { } When processing my (XML) configuration file, I want to obtain an instance of the appropriate concrete class based on the name of the element I'm processing. public IWidget CreateWidget(XElement definition) { var kind = definition.Name.LocalName; var widget = // What goes here? widget.Configure(definition); return widget; } Each definition should result in a different widget being created - I don't need or want the instances to be shared. In the past I've written plenty of code to do this kind of thing manually, including writing a custom "roll-your-own" IoC container for one project. However, one of my goals with this project is to become proficient with StructureMap instead of reinventing the wheel. I think I've already managed to set up automatic scanning of assemblies so that StructureMap knows about all my IWidget implementations: public class WidgetRegistration : Registry { public WidgetRegistration() { Scan( scanner => { scanner.AssembliesFromApplicationBaseDirectory(); scanner.AddAllTypesOf<IWidget>(); }); } } However, this isn't registering the names of my widgets with StructureMap. What do I need to add to make my scenario work? (While I am trying to use StructureMap in this project, an answer showing me how to solve this problem with a different DI/IoC tool would still be valuable.)

    Read the article

  • Use different configurations with Simple Injection

    - by Ruben.Canton
    I'm using the library "Simple Injector" (http://simpleinjector.codeplex.com) and it looks cool and nice. But after building a configuration and use it, now I want to know how to change from one configuration to another. Scenario: Let's imagine I've set up a configuration in the Global Asax and I have the public and global Container there. Now I want to make some tests and I want them to use mock classes so I want to change the configuration. I can, of course, build another configuration and assign it to the global Container created by default, so that every time I run a test the alternative configuration will be set. But on doing that and though I'm in development context the Container is changed for everyone, even for normal requests. I know I'm testing in this context and that shouldn't matter, but I have the feeling that this is not the way for doing this... and I wonder how to change from one configuration to another in the correct way. Note: At Simple Injector documentation says that you can ask questions in stackoverflow so that's why I'm here. =P PD: I'm new in this IoC and DI world so try to be easy with me when explaining it :)

    Read the article

  • PHP OOP: Avoid Singleton/Static Methods in Domain Model Pattern

    - by sunwukung
    I understand the importance of Dependency Injection and its role in Unit testing, which is why the following issue is giving me pause: One area where I struggle not to use the Singleton is the Identity Map/Unit of Work pattern (Which keeps tabs on Domain Object state). //Not actual code, but it should demonstrate the point class Monitor{//singleton construction omitted for brevity static $members = array();//keeps record of all objects static $dirty = array();//keeps record of all modified objects static $clean = array();//keeps record of all clean objects } class Mapper{//queries database, maps values to object fields public function find($id){ if(isset(Monitor::members[$id]){ return Monitor::members[$id]; } $values = $this->selectStmt($id); //field mapping process omitted for brevity $Object = new Object($values); Monitor::new[$id]=$Object return $Object; } $User = $UserMapper->find(1);//domain object is registered in Id Map $User->changePropertyX();//object is marked "dirty" in UoW // at this point, I can save by passing the Domain Object back to the Mapper $UserMapper->save($User);//object is marked clean in UoW //but a nicer API would be something like this $User->save(); //but if I want to do this - it has to make a call to the mapper/db somehow $User->getBlogPosts(); //or else have to generate specific collection/object graphing methods in the mapper $UserPosts = $UserMapper->getBlogPosts(); $User->setPosts($UserPosts); Any advice on how you might handle this situation? I would be loathe to pass/generate instances of the mapper/database access into the Domain Object itself to satisfy DI - At the same time, avoiding that results in lots of calls within the Domain Object to external static methods. Although I guess if I want "save" to be part of its behaviour then a facility to do so is required in its construction. Perhaps it's a problem with responsibility, the Domain Object shouldn't be burdened with saving. It's just quite a neat feature from the Active Record pattern - it would be nice to implement it in some way.

    Read the article

  • Serializing Configurations for a Dependency Injection / Inversion of Control

    - by Joshua Starner
    I've been researching Dependency Injection and Inversion of Control practices lately in an effort to improve the architecture of our application framework and I can't seem to find a good answer to this question. It's very likely that I have my terminology confused, mixed up, or that I'm just naive to the concept right now, so any links or clarification would be appreciated. Many examples of DI and IoC containers don't illustrate how the container will connect things together when you have a "library" of possible "plugins", or how to "serialize" a given configuration. (From what I've read about MEF, having multiple declarations of [Export] for the same type will not work if your object only requires 1 [Import]). Maybe that's a different pattern or I'm blinded by my current way of thinking. Here's some code for an example reference: public abstract class Engine { } public class FastEngine : Engine { } public class MediumEngine : Engine { } public class SlowEngine : Engine { } public class Car { public Car(Engine e) { engine = e; } private Engine engine; } This post talks about "Fine-grained context" where 2 instances of the same object need different implementations of the "Engine" class: http://stackoverflow.com/questions/2176833/ioc-resolve-vs-constructor-injection Is there a good framework that helps you configure or serialize a configuration to achieve something like this without hard coding it or hand-rolling the code to do this? public class Application { public void Go() { Car c1 = new Car(new FastEngine()); Car c2 = new Car(new SlowEngine()); } } Sample XML: <XML> <Cars> <Car name="c1" engine="FastEngine" /> <Car name="c2" engine="SlowEngine" /> </Cars> </XML>

    Read the article

  • Dependency injection in constructors

    - by andre
    Hello everyone. I'm starting a new project and setting up the base to work on. A few questions have risen and I'll probably be asking quite a few in here, hopefully I'll find some answers. First step is to handle dependencies for objects. I've decided to go with the dependency injection design pattern, to which I'm somewhat new, to handle all of this for the application. When actually coding it I came across a problem. If a class has multiple dependencies and you want to pass on multiple dependencies via the constructor (so that they cannot be changed after you instantiate the object). How do you do it without passing an array of dependencies, using call_user_func_array(), eval() or Reflection? This is what i'm looking for: <?php class DI { public function getClass($classname) { if(!$this->pool[$classname]) { # Load dependencies $deps = $this->loadDependencies($classname); # Here is where the magic should happen $instance = new $classname($dep1, $dep2, $dep3); # Add to pool $this->pool[$classname] = $instance; return $instance; } else { return $this->pool[$classname]; } } } Again, I would like to avoid the most costly methods to call the class. Any other suggestions?

    Read the article

  • What is the difference between Inversion of Control and Dependency injection in C++?

    - by rlbond
    I've been reading recently about DI and IoC in C++. I am a little confused (even after reading related questions here on SO) and was hoping for some clarification. It seems to me that being familiar with the STL and Boost leads to use of dependency injection quite a bit. For example, let's say I made a function that found the mean of a range of numbers: template <typename Iter> double mean(Iter first, Iter last) { double sum = 0; size_t number = 0; while (first != last) { sum += *(first++); ++number; } return sum/number; }; Is this dependency injection? Inversion of control? Neither? Let's look at another example. We have a class: class Dice { public: typedef boost::mt19937 Engine; Dice(int num_dice, Engine& rng) : n_(num_dice), eng_(rng) {} int roll() { int sum = 0; for (int i = 0; i < num_dice; ++i) sum += boost::uniform_int<>(1,6)(eng_); return sum; } private: Engine& eng_; int n_; }; This seems like dependency injection. But is it inversion of control? Also, if I'm missing something, can someone help me out?

    Read the article

  • C#; On casting to the SAME class that came from another assembly

    - by G. Stoynev
    For complete separation/decoupling, I've implemented a DAL in an assebly that is simply being copied over via post-build event to the website BIN folder. The website then on Application Start loads that assembly via System.Reflection.Assembly.LoadFile. Again, using reflection, I construct a couple of instances from classes in that assembly. I then store a reference to these instances in the session (HttpContext.Current.Items) Later, when I try to get the object stored in the session, I am not able to cast them to their own types (was trying interfaces initially, but for debugging tried to cast to THEIR OWN TYPES), getting this error: [A]DAL_QSYSCamper.NHibernateSessionBuilder cannot be cast to [B] DAL_QSYSCamper.NHibernateSessionBuilder. Type A originates from 'DAL_QSYSCamper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Users\dull.anomal\AppData\Local\Temp\Temporary ASP.NET Files\root\ad6e8bff\70fa2384\assembly\dl3\aaf7a5b0\84f01b09_b10acb01\DAL_QSYSCamper.DLL'. Type B originates from 'DAL_QSYSCamper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'C:\Users\dull.anomal\Documents\Projects\QSYS\Deleteme\UI\MVCClient\bin\DAL_QSYSCa mper.DLL'. This is happening while debugging in VS - VS manages to stop into the source DAL project even though I've loaded from assembly and the project is not refferenced by the website project (they're both in the solution). I do understand the error, but I don't understand how and why the assembly is being used/loaded from two locations - I only load it once from the file and there's no referrence to the project. Should mention that I also use Windsor for DI. The object that tries to extract the object from the session is A) from a class from that DAL assembly; B) is injected into a website class by Windsor. I will work on adding some sample code to this question, but wanted to put it out in case it's obvious what I do wrong.

    Read the article

  • Stuck trying to get Log4Net to work with Dependency Injection

    - by Pure.Krome
    I've got a simple winform test app i'm using to try some Log4Net Dependency Injection stuff. I've made a simple interface in my Services project :- public interface ILogging { void Debug(string message); // snip the other's. } Then my concrete type will be using Log4Net... public class Log4NetLogging : ILogging { private static ILog Log4Net { get { return LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } public void Debug(string message) { if (Log4Net.IsDebugEnabled) { Log4Net.Debug(message); } } } So far so good. Nothing too hard there. Now, in a different project (and therefore namesapce), I try and use this ... public partial class Form1 : Form { public Form1() { FileInfo fileInfo = new FileInfo("Log4Net.config"); log4net.Config.XmlConfigurator.Configure(fileInfo); } private void Foo() { // This would be handled with DI, but i've not set it up // (on the constructor, in this code example). ILogging logging = new Log4NetLogging(); logging.Debug("Test message"); } } Ok .. also pretty simple. I've hardcoded the ILogging instance but that is usually dependency injected via the constructor. Anyways, when i check this line of code... return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); the DeclaringType type value is of the Service namespace, not the type of the Form (ie. X.Y.Z.Form1) which actually called the method. Without passing the type INTO method as another argument, is there anyway using reflection to figure out the real method that called it?

    Read the article

  • new Stateful session bean instance without calling lookup

    - by kislo_metal
    Scenario: I have @Singleton UserFactory (@Stateless could be) , its method createSession() generating @Stateful UserSession bean by manual lookup. If I am injecting by DI @EJB - i will get same instance during calling fromFactory() method(as it should be) What I want - is to get new instance of UserSession without preforming lookup. Q1: how could I call new instance of @Stateful session bean? Code: @Singleton @Startup @LocalBean public class UserFactory { @EJB private UserSession session; public UserFactory() { } @Schedule(second = "*/1", minute = "*", hour = "*") public void creatingInstances(){ try { InitialContext ctx = new InitialContext(); UserSession session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } } @Schedule(second = "*/1", minute = "*", hour = "*") public void fromFactory(){ System.out.println("in singleton UUID " +session.getSessionUUID()); } public UserSession creatSession(){ UserSession session2 = null; try { InitialContext ctx = new InitialContext(); session2 = (UserSession) ctx.lookup("java:global/inferno/lic/UserSession"); System.out.println("in singleton UUID " +session2.getSessionUUID()); } catch (NamingException e) { e.printStackTrace(); } return session2; } } As I understand, calling of session.getClass().newInstance(); is not a best idea Q2 : is it true? I am using glassfish v3, ejb 3.1.

    Read the article

  • Ninject: How do I inject into a class library ?

    - by DennyDotNet
    To start I'm using Ninject 1.5. I have two projects: Web project and a Class library. My DI configuration is within the Web project. Within my class library I have the following defined: public interface ICacheService<T> { string Identifier { get; } T Get(); void Set( T objectToCache, TimeSpan timeSpan ); bool Exists(); } And then a concrete class called CategoryCacheService. In my web project I bind the two: Bind( typeof( ICacheService<List<Category>> ) ).To( typeof(CategoryCacheService)).Using<SingletonBehavior>(); In my class library I have extension methods for the HtmlHelper class, for example: public static class Category { [Inject] public static ICacheService Categories { get; set; } public static string RenderCategories(this HtmlHelper htmlHelper) { var c = Categories.Get(); return string.Join(", ", c.Select(s = s.Name).ToArray()); } } I've been told that you cannot inject into static properties, instead I should use Kernel.Get<() - However... Since the code above is in a class library I don't have access to the Kernel. How can I get the Kernel from this point or is there a better way of doing this? Thanks!

    Read the article

  • Difference between MVC FilterAttribute and Filter

    - by zaaaaphod
    I'm trying to write my own custom AuthorizationAttribute that uses DI. I'm using the MUNQ IoC provider for it's speed and have decided to use constructor injection on all my classes as opposed to post instatiation property binding (because I prefer it). I'm trying to write a custom IFilterProvider that will use my IoC container to return requests for filters (so that I can map concrete classes using the container). I've come up with the following. public class FilterProvider : IFilterProvider { private readonly IocContainer _container; public FilterProvider(IocContainer container) { _container = container; } public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var x = Enumerable.Union<Object>(_container.ResolveAll<IActionFilter>(), _container.ResolveAll<IAuthorizationFilter>()); foreach (Filter actionFilter in x) yield return new Filter(actionFilter, FilterScope.First, null); } } The above code will fail during the foreach because my objects that implement IAuthorizationFilter are based on FilterAttribute and not Filter My question is, what is the difference between Filter and FilterAttribute? I would have thought that there would have been a common link between them, unless I'm missing something. Another deeper question is, how come there is no IFilterAttributeProvider that would support IEnumerable GetFilters(...) Is there some other way that I should be using to resolve IAuthorizationFilter via my IoC container? Thank you very much for your help. Z

    Read the article

  • Adding a column to a model at runtime (without additional tables) in rails

    - by Marek
    I'm trying to give admins of my web application the ability to add some new fields to a model. The model is called Artwork and i would like to add, for instante, a test_column column at runtime. I'm just teting, so i added a simple link to do it, it will be of course parametric. I managed to do it through migrations: def test_migration_create Artwork.add_column :test_column, :integer flash[:notice] = "Added Column test_column to artworks" redirect_to :action => 'index' end def test_migration_delete Artwork.remove_column :test_column flash[:notice] = "Removed column test_column from artworks" redirect_to :action => 'index' end It works, the column gets added/ removed to/from the databse without issues. I'm using active_scaffold at the moment, so i get the test_column field in the form without adding anything. When i submit a create or an update, however, the test_column does not get updated and stay empty. Inspecting the parameters, i can see: Parameters: {"commit"=>"Update", "authenticity_token"=>"37Bo5pT2jeoXtyY1HgkEdIhglhz8iQL0i3XAx7vu9H4=", "id"=>"62", "record"=>{"number"=>"test_artwork", "author"=>"", "title"=>"Opera di Test", "test_column"=>"TEEST", "year"=>"", "description"=>""}} the test_column parameter is passed correctly. So why active record keeps ignoring it? I tried to restart the server too without success. I'm using ruby 1.8.7, rails 2.3.5, and mongrel with an sqlite3 database. Thanks

    Read the article

  • DCI: How to implement Context with Dependency Injection?

    - by ciscoheat
    Most examples of a DCI Context are implemented as a Command pattern. When using Dependency Injection though, it's useful to have the dependencies injected in the constructor and send the parameters into the executing method. Compare the Command pattern class: public class SomeContext { private readonly SomeRole _someRole; private readonly IRepository<User> _userRepository; // Everything goes into the constructor for a true encapsuled command. public SomeContext(SomeRole someRole, IRepository<User> userRepository) { _someRole = someRole; _userRepository = userRepository; } public void Execute() { _someRole.DoStuff(_userRepository); } } With the Dependency injected class: public class SomeContext { private readonly IRepository<User> _userRepository; // Only what can be injected using the DI provider. public SomeContext(IRepository<User> userRepository) { _userRepository = userRepository; } // Parameters from the executing method public void Execute(SomeRole someRole) { someRole.DoStuff(_userRepository); } } The last one seems a bit nicer, but I've never seen it implemented like this so I'm curious if there are any things to consider.

    Read the article

  • WCF RIA Services DomainContext Abstraction Strategies–Say That 10 Times!

    - by dwahlin
    The DomainContext available with WCF RIA Services provides a lot of functionality that can help track object state and handle making calls from a Silverlight client to a DomainService. One of the questions I get quite often in our Silverlight training classes (and see often in various forums and other areas) is how the DomainContext can be abstracted out of ViewModel classes when using the MVVM pattern in Silverlight applications. It’s not something that’s super obvious at first especially if you don’t work with delegates a lot, but it can definitely be done. There are various techniques and strategies that can be used but I thought I’d share some of the core techniques I find useful. To start, let’s assume you have the following ViewModel class (this is from my Silverlight Firestarter talk available to watch online here if you’re interested in getting started with WCF RIA Services): public class AdminViewModel : ViewModelBase { BookClubContext _Context = new BookClubContext(); public AdminViewModel() { if (!DesignerProperties.IsInDesignTool) { LoadBooks(); } } private void LoadBooks() { _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, null); } private void LoadBooksCallback(LoadOperation<Book> books) { Books = new ObservableCollection<Book>(books.Entities); } } Notice that BookClubContext is being used directly in the ViewModel class. There’s nothing wrong with that of course, but if other ViewModel objects need to load books then code would be duplicated across classes. Plus, the ViewModel has direct knowledge of how to load data and I like to make it more loosely-coupled. To do this I create what I call a “Service Agent” class. This class is responsible for getting data from the DomainService and returning it to a ViewModel. It only knows how to get and return data but doesn’t know how data should be stored and isn’t used with data binding operations. An example of a simple ServiceAgent class is shown next. Notice that I’m using the Action<T> delegate to handle callbacks from the ServiceAgent to the ViewModel object. Because LoadBooks accepts an Action<ObservableCollection<Book>>, the callback method in the ViewModel must accept ObservableCollection<Book> as a parameter. The callback is initiated by calling the Invoke method exposed by Action<T>: public class ServiceAgent { BookClubContext _Context = new BookClubContext(); public void LoadBooks(Action<ObservableCollection<Book>> callback) { _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, callback); } public void LoadBooksCallback(LoadOperation<Book> lo) { //Check for errors of course...keeping this brief var books = new ObservableCollection<Book>(lo.Entities); var action = (Action<ObservableCollection<Book>>)lo.UserState; action.Invoke(books); } } This can be simplified by taking advantage of lambda expressions. Notice that in the following code I don’t have a separate callback method and don’t have to worry about passing any user state or casting any user state (the user state is the 3rd parameter in the _Context.Load method call shown above). public class ServiceAgent { BookClubContext _Context = new BookClubContext(); public void LoadBooks(Action<ObservableCollection<Book>> callback) { _Context.Load(_Context.GetBooksQuery(), (lo) => { var books = new ObservableCollection<Book>(lo.Entities); callback.Invoke(books); }, null); } } A ViewModel class can then call into the ServiceAgent to retrieve books yet never know anything about the DomainContext object or even know how data is loaded behind the scenes: public class AdminViewModel : ViewModelBase { ServiceAgent _ServiceAgent = new ServiceAgent(); public AdminViewModel() { if (!DesignerProperties.IsInDesignTool) { LoadBooks(); } } private void LoadBooks() { _ServiceAgent.LoadBooks(LoadBooksCallback); } private void LoadBooksCallback(ObservableCollection<Book> books) { Books = books } } You could also handle the LoadBooksCallback method using a lambda if you wanted to minimize code just like I did earlier with the LoadBooks method in the ServiceAgent class.  If you’re into Dependency Injection (DI), you could create an interface for the ServiceAgent type, reference it in the ViewModel and then inject in the object to use at runtime. There are certainly other techniques and strategies that can be used, but the code shown here provides an introductory look at the topic that should help get you started abstracting the DomainContext out of your ViewModel classes when using WCF RIA Services in Silverlight applications.

    Read the article

  • Doing your first mock with JustMock

    - by mehfuzh
    In this post, i will start with a  more traditional mocking example that  includes a fund transfer scenario between two different currency account using JustMock.Our target interface that we will be mocking looks similar to: public interface ICurrencyService {     float GetConversionRate(string fromCurrency, string toCurrency); } Moving forward the SUT or class that will be consuming the  service and will be invoked by user [provided that the ICurrencyService will be passed in a DI style] looks like: public class AccountService : IAccountService         {             private readonly ICurrencyService currencyService;               public AccountService(ICurrencyService currencyService)             {                 this.currencyService = currencyService;             }               #region IAccountService Members               public void TransferFunds(Account from, Account to, float amount)             {                 from.Withdraw(amount);                 float conversionRate = currencyService.GetConversionRate(from.Currency, to.Currency);                 float convertedAmount = amount * conversionRate;                 to.Deposit(convertedAmount);             }               #endregion         }   As, we can see there is a TransferFunds action implemented from IAccountService  takes in a source account from where it withdraws some money and a target account to where the transfer takes place using the provided conversion rate. Our first step is to create the mock. The syntax for creating your instance mocks is pretty much same and  is valid for all interfaces, non-sealed/sealed concrete instance classes. You can pass in additional stuffs like whether its an strict mock or not, by default all the mocks in JustMock are loose, you can use it as default valued objects or stubs as well. ICurrencyService currencyService = Mock.Create<ICurrencyService>(); Using JustMock, setting up your expectations and asserting them always goes with Mock.Arrang|Assert and this is pretty much same syntax no matter what type of mocking you are doing. Therefore,  in the above scenario we want to make sure that the conversion rate always returns 2.20F when converting from GBP to CAD. To do so we need to arrange in the following way: Mock.Arrange(() => currencyService.GetConversionRate("GBP", "CAD")).Returns(2.20f).MustBeCalled(); Here, I have additionally marked the mock call as must. That means it should be invoked anywhere in the code before we do Mock.Assert, we can also assert mocks directly though lamda expressions  but the more general Mock.Assert(mocked) will assert only the setups that are marked as "MustBeCalled()”. Now, coming back to the main topic , as we setup the mock, now its time to act on it. Therefore, first we create our account service class and create our from and to accounts respectively. var accountService = new AccountService(currencyService);   var canadianAccount = new Account(0, "CAD"); var britishAccount = new Account(0, "GBP"); Next, we add some money to the GBP  account: britishAccount.Deposit(100); Finally, we do our transfer by the following: accountService.TransferFunds(britishAccount, canadianAccount, 100); Once, everything is completed, we need to make sure that things were as it is we have expected, so its time for assertions.Here, we first do the general assertions: Assert.Equal(0, britishAccount.Balance); Assert.Equal(220, canadianAccount.Balance); Following, we do our mock assertion,  as have marked the call as “MustBeCalled” it will make sure that our mock is actually invoked. Moreover, we can add filters like how many times our expected mock call has occurred that will be covered in coming posts. Mock.Assert(currencyService); So far, that actually concludes our  first  mock with JustMock and do stay tuned for more. Enjoy!!

    Read the article

  • JustMock is here !!

    - by mehfuzh
    As announced earlier by Hristo Kosev at Telerik blogs , we have started giving out JustMock builds from today. This is the first of early builds before the official Q2 release and we are pretty excited to get your feedbacks. Its pretty early to say anything on it. It actually depends on your feedback. To add few, with JustMock we tried to build a mocking tool with simple and intuitive syntax as possible excluding more and more noises and avoiding any smell that can be made to your code [We are still trying everyday] and we want to make the tool even better with your help. JustMock can be used to mock virtually anything. Moreover, we left an option open that it can be used to reduce / elevate the features  just though a single click. We tried to make a strong API and make stuffs fluent and guided as possible so that you never have the chance to get de-railed. Our syntax is AAA (Arrange – Act – Assert) , we don’t believe in Record – Reply model which some of the smarter mocking tools are planning to remove from their coming release or even don’t have [its always fun to lean from each other]. Overall more signals equals more complexity , reminds me of 37 signals :-). Currently, here are the things you can do with JustMock ( will cover more in-depth in coming days) Proxied mode Mock interfaces and class with virtuals Mock properties that includes indexers Set raise event for specific calls Use matchers to control mock arguments Assert specific occurrence of a mocked calls. Assert using matchers Do recursive mocks Do Sequential mocking ( same method with argument returns different values or perform different tasks) Do strict mocking (by default and i prefer loose , so that i can use it as stubs) Elevated mode Mock static calls Mock final class Mock sealed classes Mock Extension methods Partially mock a  class member directly using Mock.Arrange Mock MsCorlib (we will support more and more members in coming days) , currently we support FileInfo, File and DateTime. These are few, you need to take a look at the test project that is provided with the build to find more [Along with the document]. Also, one of feature that will i will be using it for my next OS projects is the ability to run it separately in  proxied mode which makes it easy to redistribute and do some personal development in a more DI model and my option to elevate as it go.   I’ve surely forgotten tons of other features to mention that i will cover time but  don’t for get the URL : www.telerik.com/justmock   Finally a little mock code:   var lvMock = Mock.Create<ILoveJustMock>();    // set your goal  Mock.Arrange(() => lvMock.Response(Arg.Any<string>())).Returns((int result) => result);    //perform  string ret =  lvMock.Echo("Yes");    Assert.Equal(ret, "Yes");  // make sure everything is fine  Mock.Assert(() => lvMock.Echo("Yes"), Occurs.Once());   Hope that helps to get started,  will cover if not :-).

    Read the article

  • problem with network-manager-pptp

    - by Riuzaki90
    I've a problema with the VPA CAble connection of my university... on the website of the university there's a .sh file that set all the variables of the connection in ETC/PPP/PEERS and another .sh file that call the connection...I'm on ubuntu 11.10 and when I run the setup.sh I have this error: impossible to find network-manager-pptp these are the two file that I had talk about: #!/bin/bash echo "Creazione della connessione in corso attendere........." apt-get update apt-get install pptp-linux network-manager-pptp echo -n "Digitare la propria Username: " read USERNAME echo -n "Digitare la propria Password: " read PASSWORD pptpsetup --create UNICAL_Campus_Access --server 160.97.73.253 --username $USERNAME --password $PASSWORD echo 'pty "pptp 160.97.73.253 --nolaunchpppd"' >/etc/ppp/peers/UNICAL_Campus_Access echo 'require-mppe-128' >>/etc/ppp/peers/UNICAL_Campus_Access echo 'file /etc/ppp/options.pptp'>>/etc/ppp/peers/UNICAL_Campus_Access echo 'name '$USERNAME''>>/etc/ppp/peers/UNICAL_Campus_Access echo 'remotename PPTP'>>/etc/ppp/peers/UNICAL_Campus_Access echo 'ipparam UNICAL_Campus_Access'>>/etc/ppp/peers/UNICAL_Campus_Access echo $USERNAME' PPTP '$PASSWORD' *'>>/etc/ppp/chap-secrets rm /etc/ppp/options.pptp echo '###############################################################################'>/etc/ppp/options.pptp echo '# $Id: options.pptp,v 1.3 2006/03/26 23:11:05 quozl Exp $'>>/etc/ppp/options.pptp echo '#'>>/etc/ppp/options.pptp echo '# Sample PPTP PPP options file /etc/ppp/options.pptp'>>/etc/ppp/options.pptp echo '# Options used by PPP when a connection is made by a PPTP client.'>>/etc/ppp/options.pptp echo '# This file can be referred to by an /etc/ppp/peers file for the tunnel.'>>/etc/ppp/options.pptp echo '# Changes are effective on the next connection. See "man pppd".'>>/etc/ppp/options.pptp echo '#'>>/etc/ppp/options.pptp echo '# You are expected to change this file to suit your system. As'>>/etc/ppp/options.pptp echo '# packaged, it requires PPP 2.4.2 or later from http://ppp.samba.org/'>>/etc/ppp/options.pptp echo '# and the kernel MPPE module available from the CVS repository also on'>>/etc/ppp/options.pptp echo '# http://ppp.samba.org/, which is packaged for DKMS as kernel_ppp_mppe.'>>/etc/ppp/options.pptp echo '###############################################################################'>>/etc/ppp/options.pptp echo '# Lock the port'>>/etc/ppp/options.pptp echo 'lock'>>/etc/ppp/options.pptp echo '# Authentication'>>/etc/ppp/options.pptp echo '# We do not need the tunnel server to authenticate itself'>>/etc/ppp/options.pptp echo 'noauth'>>/etc/ppp/options.pptp echo '#We won"t do PAP, EAP, CHAP, or MSCHAP, but we will accept MSCHAP-V2'>>/etc/ppp/options.pptp echo '#(you may need to remove these refusals if the server is not using MPPE)'>>/etc/ppp/options.pptp echo 'refuse-pap'>>/etc/ppp/options.pptp echo 'refuse-eap'>>/etc/ppp/options.pptp echo 'refuse-chap'>>/etc/ppp/options.pptp echo 'refuse-mschap'>>/etc/ppp/options.pptp echo '# Compression Turn off compression protocols we know won"t be used'>>/etc/ppp/options.pptp echo 'nobsdcomp'>>/etc/ppp/options.pptp echo 'nodeflate'>>/etc/ppp/options.pptp echo '# Encryption'>>/etc/ppp/options.pptp echo '# (There have been multiple versions of PPP with encryption support,'>>/etc/ppp/options.pptp echo '# choose with of the following sections you will use. Note that MPPE'>>/etc/ppp/options.pptp echo '# requires the use of MSCHAP-V2 during authentication)'>>/etc/ppp/options.pptp echo '# http://ppp.samba.org/ the PPP project version of PPP by Paul Mackarras'>>/etc/ppp/options.pptp echo '# ppp-2.4.2 or later with MPPE only, kernel module ppp_mppe.o'>>/etc/ppp/options.pptp echo '#{{{'>>/etc/ppp/options.pptp echo '# Require MPPE 128-bit encryption'>>/etc/ppp/options.pptp echo '#require-mppe-128'>>/etc/ppp/options.pptp echo '#}}}'>>/etc/ppp/options.pptp echo '# http://polbox.com/h/hs001/ fork from PPP project by Jan Dubiec'>>/etc/ppp/options.pptp echo '#ppp-2.4.2 or later with MPPE and MPPC, kernel module ppp_mppe_mppc.o'>>/etc/ppp/options.pptp echo '#{{{'>>/etc/ppp/options.pptp echo '# Require MPPE 128-bit encryption'>>/etc/ppp/options.pptp echo '#mppe required,stateless'>>/etc/ppp/options.pptp echo '# }}}'>>/etc/ppp/options.pptp echo "setup di 'UNICAL Campus Access' terminato correttamente" echo "per connettersi eseguire lo script 'UNICAL_Campus_Access.sh' " and the second: #!/bin/bash echo "Connessione alla Rete del Centro Residenziale in corso attendere........." modprobe ppp_mppe pppd call UNICAL_Campus_Access sleep 30 tail -n 8 /var/log/messages echo "Connessione Stabilita" echo -n "Per terminare la connessione premere invio (in alternativa eseguire il commando 'killall pppd'):----> " read CONN killall pppd echo "Connessione terminata" I've correctly installed network-manager-pptp to the latest version...help?

    Read the article

  • First Day of Data Integration Track at Oracle OpenWorld 2012

    - by Irem Radzik
    OpenWorld started full speed for us today with a great set of sessions in the Data Integration track. After the exciting keynote session on Oracle Database 12c in the morning; Brad Adelberg, VP of Development for Data Integration products, presented Oracle’s data integration product strategy. His session highlighted the new requirements for data integration to achieve pervasive and continuous access to trusted data. The new requirements and product focus areas presented in this session are: Provide access to any data at any source On premise or on cloud Enable zero downtime operations and maximum performance Leverage real-time data for accurate business insights And ensure high quality data is used across the enterprise During the session Brad walked over how Oracle’s data integration products, Oracle Data Integrator, Oracle GoldenGate, Oracle Enterprise Data Quality, and Oracle Data Service Integrator, deliver on these requirements and how recent product releases build on this strategy. Soon after Brad’s session we heard from a panel of Oracle GoldenGate customers, St. Jude Medical, Equifax, and Bank of America, how they achieved zero downtime operations using Oracle GoldenGate. The panel presented different use cases of GoldenGate, from Active-Active replication to offloading reporting. Especially St. Jude Medical’s implementation, which involves the alert management system for patients that use their pacemakers, reminded me in some cases downtime of mission-critical systems can be a matter of life or death. It is very comforting to hear that GoldenGate delivers highly-reliable continuous availability for life-saving medical systems. In the afternoon, Nick Wagner from the Product Management team and I followed the customer panel with the review of Oracle GoldenGate 11gR2’s New Features.  Many questions we received from audience were about GoldenGate’s new Integrated Capture for Oracle Database and the enhanced Conflict Management features, as well as how GoldenGate compares to Oracle Streams. In addition to giving details on GoldenGate’s unique capability to capture changed data with a direct integration to the Oracle DBMS engine, we reminded the audience that enhancements to Oracle GoldenGate will continue, while Streams will be primarily maintained. Last but not least, Tim Garrod and Ryan Fonnett from Raymond James presented a unified real-time data integration solution using Oracle Data Integrator and GoldenGate for their operational data store (ODS). The ODS supports application services across the enterprise and providing timely data is a critical requirement. In this solution, Oracle GoldenGate does the log-based change data capture for Oracle Data Integrator’s near real-time data integration between heterogeneous systems. As Raymond James’ ODS supports mission-critical services for their advisors, the project team had to set up this integration environment to be highly available. During the session, Ryan and Tim explained how they use ODI to enable automated process execution and “always-on” integration processes. Their presentation included 2 demonstrations that focused on CDC patterns deployed with ODI and the automated multi-instance execution and monitoring. We are very grateful to Tim and Ryan for their very-well prepared presentation at OpenWorld this year. Day 2 (Tuesday) will be also a busy day in our track. In addition to the Fusion Middleware Innovation Awards ceremony at 11:45am at Moscone West 3001, we have the following DI sessions Real-World Operational Reporting Customer Panel 11:45am Moscone West- 3005 Oracle Data Integrator Product Update and Future Strategy 1:15pm Moscone West- 3005 High-volume OLTP with Oracle GoldenGate: Best Practices from Comcast 1:15pm Moscone West- 3005 Everything You need to Know about Monitoring Oracle GoldenGate 5pm Moscone West-3005 If you are at OpenWorld please join us in these sessions. For a full review of data integration track at OpenWorld please see our Focus-On document.

    Read the article

  • SEASON'S GREETINGS AND HAPPY HOLIDAYS

    - by klaudia.drulis
    p.msonormal { margin:0in; margin-bottom:.0001pt; font-size:11.0pt; font-family:calibri; } li.msonormal { margin:0in; margin-bottom:.0001pt; font-size:11.0pt; font-family:calibri; } p.listparagraph { margin-top:0in; margin-right:0in; margin-bottom:.0001pt; margin-left:.5in; font-size:11.0pt; font-family:calibri; } -- ! Please follow Guidelines for a proper working email ! ___________________________________________________________________________________________________________________ Oracle standard tags   symbol entity Special character Ampersand & & Apostrophe ’ ’ Copyright © © Ellipsis … … Em dash — — En dash – – Euro € € Pound £ £ Left quote “ “ Right quote ” ” Registered trademark ® ® Trademark ™ ℄ Yen ¥ ¥ ___________________________________________________________________________________________________________________ IMPORTANT in creating a link to have a desired color (red, black, etc) that will work in Hotmail, Yahoo, Outlook, and Gmail You MUST Place the inside the Example Click Here The order you must follow to make the colored link appear in browsers. If not the default window link will appear 1. Select the word you want to use for the link 2. Select the desired color, Red, Black, etc 3. Select bold if necessary ___________________________________________________________________________________________________________________ Templates use two sizes of fonts and the sans-serif font tag for the email. All Fonts should be (Arial, Helvetica, sans-serif) tags Normal size reading body fonts should be set to the size of 2. Small font sizes should be set to 1 !!!!!!!DO NOT USE ANY OTHER SIZE FONT FOR THE EMAILS!!!!!!!! ___________________________________________________________________________________________________________________ --   SEASON'S GREETINGS AND HAPPY HOLIDAYS Click here to view the e-card We would like to wish you a Merry Christmas and a prosperous new year. Tanti auguri di buon natale e felice anno nuovo!!! Je vous souhaite de joyeuses fetes, et tous mes voeux de succes pour l'annee a venir ! Tous mes voeux de bonheur, de succes et d’epanouissement pour 2011! Va urez Sarbatori Fericite si un an nou fericit!!! El equipo de Recruitment de Oracle te desea una feliz navidad y un fantastico 2011 Namens het campus recruitment team wensen wij je fijne feestdagen en een uitdagend 2011! In this closing paragraph, reinforce the primary benefit or opportunity being offered. Include a call to action and contact information. Body copy to this point should not exceed 150 words. Wszystkim Sympatykom naszego Blogu skladamy zyczenia Spokojnych i Radosnych Swiat Bozego Narodzenia oraz Pomyslnosci i Sukcesów w Nowym Roku.     Stay Connected: Facebook Experienced YouTube Twitter OracleMix Graduates Copyright © 2010, Oracle and/or its affiliates. All rights reserved.    

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30  | Next Page >