Search Results

Search found 663 results on 27 pages for 'di seghposs'.

Page 8/27 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • IoC, AOP and more

    - by JMSA
    What is an IoC container? What is an IoC/DI framework? Why do we need a framework for IoC/DI? Is there any relationship between IoC/DI and AOP? What is Spring.net/ninject with respect to IoC and AOP?

    Read the article

  • Could not realize media player

    - by user556894
    I am using this code to run avi file using jmf but the error come like "Could not realize media player" and how to open all video format using jmf import javax.media.*; import javax.media.format.*; import java.io.*; import java.util.*; public class Test{ public static void main(String a[]) throws Exception{ CaptureDeviceInfo di = null; Player p = null; Vector deviceList = CaptureDeviceManager.getDeviceList(new AudioFormat("linear", 44100, 16, 2)); if (deviceList.size() > 0){ di = (CaptureDeviceInfo)deviceList.firstElement(); System.out.println((di.getLocator()).toExternalForm()); }else{ System.out.println("Exiting"); System.exit(-1); } try{ p = Manager.createPlayer(di.getLocator()); }catch (IOException e){ System.out.println(e); }catch (NoPlayerException e) { System.out.println(e); } System.out.println("Playing Started"); p.start(); } }

    Read the article

  • MACRO compilation PROBLEM

    - by wildfly
    i was given a primitive task to find out (and to put in cl) how many nums in an array are bigger than the following ones, (meaning if (arr[i] arr[i+1]) count++;) but i've problems as it has to be a macro. i am getting errors from TASM. can someone give me a pointer? SortA macro a, l LOCAL noes irp reg, <si,di,bx> push reg endm xor bx,bx xor si,si rept l-1 ;;also tried rept 3 : wont' compile mov bl,a[si] inc si cmp bl,arr[si] jb noes inc di noes: add di,0 endm mov cx,di irp reg2, <bx,di,si> pop reg2 endm endm dseg segment arr db 10,9,8,7 len = 4 dseg ends sseg segment stack dw 100 dup (?) sseg ends cseg segment assume ds:dseg, ss:sseg, cs:cseg start: mov ax, dseg mov ds,ax sortA arr,len cseg ends end start errors: Assembling file: sorta.asm **Error** sorta.asm(51) REPT(4) Expecting pointer type **Error** sorta.asm(51) REPT(6) Symbol already different kind: NOES **Error** sorta.asm(51) REPT(10) Expecting pointer type **Error** sorta.asm(51) REPT(12) Symbol already different kind: NOES **Error** sorta.asm(51) REPT(16) Expecting pointer type **Error** sorta.asm(51) REPT(18) Symbol already different kind: NOES Error messages: 6

    Read the article

  • Using DirectoryInfo in C#

    - by pm_2
    If there a more efficient way to do the following: DirectoryInfo di = new DirectoryInfo(@"c:\"); newFileName = Path.Combine(di.FullName, "MyFile.Txt"); I realise that it’s only two lines of code, but given that I already have the directory, it feels like I should be able to do something like: newFileName = di.Combine(“MyFile.txt”);

    Read the article

  • Android: Adding data to Intent fails to load Activity

    - by DroidIn.net
    I have a widget that supposed to call an Activity of the main app when the user clicks on widget body. My setup works for a single widget instance but for a second instance of the same widget the PendingIntent gets reused and as result the vital information that I'm sending as extra gets overwritten for the 1st instance. So I figured that I should pass widget ID as Intent data however as soon as I add Intent#setData I would see in the log that 2 separate Intents are appropriately fired but the Activity fails to pick it up so basically Activity will not come up and nothing happens (no error or warning ether) Here's how the activity is setup in the Manifest: <activity android:name=".SearchResultsView" android:label="@string/search_results" <intent-filter> <action android:name="bostone.android.search.RESULTS" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> And here's code that is setup for handling the click Intent di = new Intent("bostone.android.search.RESULTS"); di.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // if line below is commented out - the Activity will start di.setData(ContentUris.withAppendedId(Uri.EMPTY, widgetId)); di.putExtra("URL", url); views.setOnClickPendingIntent(R.id.widgetContent, PendingIntent.getActivity(this, 0, di, 0)); The main app and the widget are packaged as 2 separate APK each in its own package and Manifest

    Read the article

  • Attempted to perform an unauthorized operation

    - by Lefteris Gkinis
    Now I use the following code: Public Function SetACL(ByVal filename As String, ByVal account As String, ByVal sender As Object, ByVal e As System.EventArgs) As Boolean Try Dim rule As FileSystemAccessRule = New FileSystemAccessRule(account, FileSystemRights.Write, AccessControlType.Allow) Dim fp As PermissionSet = New PermissionSet(Permissions.PermissionState.Unrestricted) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Read, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Write, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.PathDiscovery, filename)) fp.Assert() Dim di As DirectoryInfo = New DirectoryInfo(Path.GetDirectoryName(filename)) SetACL = False Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) security.ModifyAccessRule(AccessControlModification.Add, rule, SetACL) di.SetAccessControl(security) Return SetACL Catch ex As Exception MessageBox.Show(ex.Message, "Set Security Sub", MessageBoxButtons.OK, MessageBoxIcon.Stop) Finalize() End Try End Function The Error of 'Attempted to perform an unauthorized operation' comes when i'm trying to execute the instraction Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) Please if anybody knows why that error comes here to respond

    Read the article

  • SCVMM 2012 R2 - Installing Virtual Switch Fails with Error 2916

    - by Brian M.
    So I've been attempting to teach myself SCVMM 2012 and Hyper-V Server 2012 R2, and I seem to have hit a snag. I've connected my Hyper-V Host to SCVMM 2012 successfully, and created a logical network, logical switch, and uplink port profile (which I essentially blew through with the default settings). However when I attempt to create a virtual switch on my Hyper-V host, I run into an issue. The job will use my logical network settings I created to configure the virtual switch, but when it tries to apply it to the host, it stalls and eventually fails with the following error: Error (2916) VMM is unable to complete the request. The connection to the agent vmhost1.test.loc was lost. WinRM: URL: [h**p://vmhost1.test.loc:5985], Verb: [GET], Resource: [h**p://schemas.microsoft.com/wbem/wsman/1/wmi/root/virtualization/v2/Msvm_ConcreteJob?InstanceID=2F401A71-14A2-4636-9B3E-10C0EE942D33] Unknown error (0x80338126) Recommended Action Ensure that the Windows Remote Management (WinRM) service and the VMM agent are installed and running and that a firewall is not blocking HTTP/HTTPS traffic. Ensure that VMM server is able to communicate with econ-hyperv2.econ.loc over WinRM by successfully running the following command: winrm id –r:vmhost1.test.loc This problem can also be caused by a Windows Management Instrumentation (WMI) service crash. If the server is running Windows Server 2008 R2, ensure that KB 982293 (h**p://support.microsoft.com/kb/982293) is installed on it. If the error persists, restart vmhost1.test.loc and then try the operation again. Refer to h**p://support.microsoft.com/kb/2742275 for more details. I restarted the server, and upon booting am greeted with a message stating "No active network adapters found." I load up powershell and run "Get-NetAdapter -IncludeHidden" to see what's going on, and get the following: Name InterfaceDescription ifIndex Status ---- -------------------- ------- ----- Local Area Connection* 5 WAN Miniport (PPPOE) 6 Di... Ethernet Microsoft Hyper-V Network Switch Def... 10 Local Area Connection* 1 WAN Miniport (L2TP) 2 Di... Local Area Connection* 8 WAN Miniport (Network Monitor) 9 Up Local Area Connection* 4 WAN Miniport (PPTP) 5 Di... Ethernet 2 Broadcom NetXtreme Gigabit Ethernet 13 Up Local Area Connection* 7 WAN Miniport (IPv6) 8 Up Local Area Connection* 9 Microsoft Kernel Debug Network Adapter 11 No... Local Area Connection* 3 WAN Miniport (IKEv2) 4 Di... Local Area Connection* 2 WAN Miniport (SSTP) 3 Di... vSwitch (TEST Test Swi... Hyper-V Virtual Switch Extension Ada... 17 Up Local Area Connection* 6 WAN Miniport (IP) 7 Up Now the machine is no longer visible on the network, and I don't have the slightest idea what went wrong, and more importantly how to undo the damage I caused in order to get back to where I was (save for re-installing Hyper-V Server, but I really would rather know what's going on and how to fix it)! Does anybody have any ideas? Much appreciated!

    Read the article

  • Windows CE training in Italy

    - by Valter Minute
    Se volete approfondire le vostre conoscenze su Windows CE (anche relativamente alle novità introdotte con la versione R3), o desiderate acquisire le basi per cominciare a lavorare con questo sistema operativo, questa è un'occasione da non perdere. Dal 12 al 16 Aprile si terrà presso gli uffici di Fortech Embedded Labs di Saronno (VA) il corso "Building Solutions with Windows Embedded CE 6.0", tenuto dal sottoscritto. Per maggiori informazioni sui contenuti e i costi: http://www.fortechembeddedlabs.it/node/27

    Read the article

  • How dependecy injection increases coupling?

    - by B?????
    Reading wiki page on Dependency injection, the disadvantages section tells this : Dependency injection increases coupling by requiring the user of a subsystem to provide for the needs of that subsystem. with a link to an article against DI. What DI does is that it makes a class use the interface instead of the concrete implementation. That should be decreased coupling, no? So, what am I missing? How is dependency injection increasing coupling between classes?

    Read the article

  • La ripresa economica si sta consolidando, siete pronti a cogliere questa opportunità?

    - by antonella.buonagurio(at)oracle.com
    L'esclusiva ricerca IDC indica i percorsi strategici più innovativi a supporto delle Vendite, del Customer Service e del Marketing.        La ricerca basata su più di 300 interviste a executive, CIO e CEO di medie e grandi organizzazioni in tutta Europa, vi guiderà nel comprendere l'evoluzione e l'impatto dei trend più rilevanti sui processi che gestiscono ed indirizzano la relazione tra azienda e clienti.

    Read the article

  • Piumini Woolrich è popolare a livello globale

    - by WoolrichParka
    Woolrich Parka femmine è molto popolare per la sua calda e resistente a freddo times.You può comprare un creato di copertura cappotto in pile che è proprio come una tua grande-nonno, o iniziare la vostra abitudine proprio con mobili su misura di qualità che durerà anche nel la prossima creazione del vostro family.Now, Woolrich è popolare a livello globale e la donna Woolrich Arctic Parka questo parka inverno è anche il più noto disponibile sul settore. Con il suo stile eccellente riscaldata e, ad alte prestazioni, Maestro piace molto.wufengfengmaple36

    Read the article

  • Oracle Cloud Applications Day 2013, tutte le foto!

    - by claudiac.caramelli
    Non sarete con noi al Sole 24Ore? Tutte le foto dell'evento le potrete trovare a questo link, caricate in diretta per vivere l'esperienza ancora più live.  Seguite l'andamento della plenaria su Twitter e partecipate alla discussione con l'hashtag #CloudDayIt. Non perdetevi nessun contenuto che vi aiuterà a scoprire i vantaggi e le opportunità di un nuovo modo di operare per rafforzare la propria competitività.

    Read the article

  • Xcode workspace with Unity3D as a sub-project?

    - by Di Wu
    Let's say we're developing a 2D game with Cocos2d-iPhone and UIKit and CoreAnimation. But we're also considering leveraging the 3D capabilities of Unity 3D. Is it possible that we add the Unity3D-generated Xcode project as a sub-project into the workspace and expose the 3D UI element as some kind of UIView subclass so that the native UIKit and CoreAnimation code could use them without the need to mess up with their underlying Unity3D implementation?

    Read the article

  • How to configure an Ubuntu server so that all traffic goes through a VPN?

    - by Di Wu
    This question is Not about how to set up VPN on an Ubuntu server. Edited: I think what I'm looking for is the way to set up a PPTP VPN client on my Ubuntu server by command line. I have an Ubuntu server running and connected to the internet. I also have a VPN service (PPTP) running on another Linux machine. Now all I want to do is configure this Ubuntu server so that all the internet traffic it generates goes through the VPN. How can I achieve this?

    Read the article

  • Isn't class scope purely for organization?

    - by Di-0xide
    Isn't scope just a way to organize classes, preventing outside code from accessing certain things you don't want accessed? More specifically, is there any functional gain to having public, protected, or private-scoped methods? Is there any advantage to classifying method/property scope rather than to, say, just public-ize everything? My presumption says no simply because, in binary code, there is no sense of scope (other than r/w/e, which isn't really scope at all, but rather global permissions for a block of memory). Is this correct? What about in languages like Java and C#[.NET]?

    Read the article

  • CakePHP pair programming practise

    - by The-Di-Lab
    We are on the stage of planning a CakePHP project. It is a relatively a big project for us, as a developer+project manager, I want to hire someone to work with me. But what I really want is to spend less time on actual coding, without losing control of the code quality. What I want to do is that I will design all the functions of the project in CakePHP, at least all the model's functions, and leave the implementation part to the coder who I am going to hire. But my worry is still if I am going to lose control of the code quality using this approach? is it feasible to do so or it is going to turn this project to a chaos. Thank you all in advanced for reading my question and give me answers.

    Read the article

  • Serverless Web Application

    - by Andrea Di Persio
    In my company we work on a software that produce reports in html format. My bosses love the fact that static html pages can be moved across computer simply by moving/copying a folder and no web server is involved, so the customer only need a browser. The problem is that they asking me to implement a lot of feature which is very hard to implement properly and in a clean way without an application server. Frames cross domain problem, the impossibility to work with GET and POST data, no URLs routing...is very hard to work with this limitations. Anyone had similiar experience and wants to share their tricks/suggestion ? Do I need to tell my boss 'there is no future without a web server'? Regards.

    Read the article

  • Is a 1:* write:read thread system safe?

    - by Di-0xide
    Theoretically, thread-safe code should fix race conditions. Race conditions, as I understand it, occur because two threads attempt to write to the same location at the same time. However, what about a threading model in which a single thread is designed to write to a location, and several slave/worker threads simply read from the location? Assuming the value/timing at which they read the data isn't relevant/doesn't hinder the worker thread's outcome, wouldn't this be considered 'thread safe', or am I missing something in my logic?

    Read the article

  • Computer does not switch on after power outage

    - by cristian
    VOLTAGE DROP OFF FOR PC does not restart The other day my pc was turned off due to power outage. Since that time the computer would not turn on again, no sign of life, it seems dead. I did several tests, changed the power outlet and disconnect the wires ... also I have reseated the cards ... but the result is that nothing changes. What can I do? Could there may be damage to the hardware due to the power outage? Note: the voltage drop is not due to a lightning storm and so is not due to damaged components (burnt card etc ...) Original Text: l'altro giorno il pc mi si è spento improvvisamente per calo tensione.... da quel momento non si è piu' riacceso...nessun segnale di vita...sembra proprio morto. Ho fatto diverse prove, cambio presa di alimentazione, scollegare i fili...insomma ho "mischiato le carte"...ma il risultato è che non cambia nulla. Cosa posso fare? cosa puo' essere successo? Possono esserci danni hardware per il calo di tensione? NB: il calo di tensione non e' dovuto ad una saetta e quindi escluderei danni causa temporale (bruciature scheda ecc...) Grazie mille

    Read the article

  • Rebuilding CoasterBuzz, Part IV: Dependency injection, it's what's for breakfast

    - by Jeff
    (Repost from my personal blog.) This is another post in a series about rebuilding one of my Web sites, which has been around for 12 years. I hope to relaunch soon. More: Part I: Evolution, and death to WCF Part II: Hot data objects Part III: The architecture using the "Web stack of love" If anything generally good for the craft has come out of the rise of ASP.NET MVC, it's that people are more likely to use dependency injection, and loosely couple the pieces parts of their applications. A lot of the emphasis on coding this way has been to facilitate unit testing, and that's awesome. Unit testing makes me feel a lot less like a hack, and a lot more confident in what I'm doing. Dependency injection is pretty straight forward. It says, "Given an instance of this class, I need instances of other classes, defined not by their concrete implementations, but their interfaces." Probably the first place a developer exercises this in when having a class talk to some kind of data repository. For a very simple example, pretend the FooService has to get some Foo. It looks like this: public class FooService {    public FooService(IFooRepository fooRepo)    {       _fooRepo = fooRepo;    }    private readonly IFooRepository _fooRepo;    public Foo GetMeFoo()    {       return _fooRepo.FooFromDatabase();    } } When we need the FooService, we ask the dependency container to get it for us. It says, "You'll need an IFooRepository in that, so let me see what that's mapped to, and put it in there for you." Why is this good for you? It's good because your FooService doesn't know or care about how you get some foo. You can stub out what the methods and properties on a fake IFooRepository might return, and test just the FooService. I don't want to get too far into unit testing, but it's the most commonly cited reason to use DI containers in MVC. What I wanted to mention is how there's another benefit in a project like mine, where I have to glue together a bunch of stuff. For example, when I have someone sign up for a new account on CoasterBuzz, I'm actually using POP Forums' new account mailer, which composes a bunch of text that includes a link to verify your account. The thing is, I want to use custom text and some other logic that's specific to CoasterBuzz. To accomplish this, I make a new class that inherits from the forum's NewAccountMailer, and override some stuff. Easy enough. Then I use Ninject, the DI container I'm using, to unbind the forum's implementation, and substitute my own. Ninject uses something called a NinjectModule to bind interfaces to concrete implementations. The forum has its own module, and then the CoasterBuzz module is loaded second. The CB module has two lines of code to swap out the mailer implementation: Unbind<PopForums.Email.INewAccountMailer>(); Bind<PopForums.Email.INewAccountMailer>().To<CbNewAccountMailer>(); Piece of cake! Now, when code asks the DI container for an INewAccountMailer, it gets my custom implementation instead. This is a lot easier to deal with than some of the alternatives. I could do some copy-paste, but then I'm not using well-tested code from the forum. I could write stuff from scratch, but then I'm throwing away a bunch of logic I've already written (in this case, stuff around e-mail, e-mail settings, mail delivery failures). There are other places where the DI container comes in handy. For example, CoasterBuzz does a number of custom things with user profiles, and special content for paid members. It uses the forum as the core piece to managing users, so I can ask the container to get me instances of classes that do user lookups, for example, and have zero care about how the forum handles database calls, configuration, etc. What a great world to live in, compared to ten years ago. Sure, the primary interest in DI is around the "separation of concerns" and facilitating unit testing, but as your library grows and you use more open source, it starts to be the glue that pulls everything together.

    Read the article

  • Splitting a set of object into several subsets of 'similar' objects

    - by doublep
    Suppose I have a set of objects, S. There is an algorithm f that, given a set S builds certain data structure D on it: f(S) = D. If S is large and/or contains vastly different objects, D becomes large, to the point of being unusable (i.e. not fitting in allotted memory). To overcome this, I split S into several non-intersecting subsets: S = S1 + S2 + ... + Sn and build Di for each subset. Using n structures is less efficient than using one, but at least this way I can fit into memory constraints. Since size of f(S) grows faster than S itself, combined size of Di is much less than size of D. However, it is still desirable to reduce n, i.e. the number of subsets; or reduce the combined size of Di. For this, I need to split S in such a way that each Si contains "similar" objects, because then f will produce a smaller output structure if input objects are "similar enough" to each other. The problems is that while "similarity" of objects in S and size of f(S) do correlate, there is no way to compute the latter other than just evaluating f(S), and f is not quite fast. Algorithm I have currently is to iteratively add each next object from S into one of Si, so that this results in the least possible (at this stage) increase in combined Di size: for x in S: i = such i that size(f(Si + {x})) - size(f(Si)) is min Si = Si + {x} This gives practically useful results, but certainly pretty far from optimum (i.e. the minimal possible combined size). Also, this is slow. To speed up somewhat, I compute size(f(Si + {x})) - size(f(Si)) only for those i where x is "similar enough" to objects already in Si. Is there any standard approach to such kinds of problems? I know of branch and bounds algorithm family, but it cannot be applied here because it would be prohibitively slow. My guess is that it is simply not possible to compute optimal distribution of S into Si in reasonable time. But is there some common iteratively improving algorithm?

    Read the article

  • Json get a parameter can't access on it iOS

    - by Usi Usi
    That's an example { "updated":1350213484, "id":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson", "title":"Risultati di feed per \"Prova\"", "self":[ { "href":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson" } ], "items":[ { "title":"Home Page - La prova del cuoco", "id":"http://www.laprovadelcuoco.rai.it/", "updated":1350213485, "feed":[ { "href":"http://www.laprovadelcuoco.rai.it/dl/portali/site/page/Page-ffb545b4-9e72-41e5-866f-a465588c43fa-rss.html" } ], "alternate":[ { "href":"http://www.laprovadelcuoco.rai.it/", "type":"text/html" } ], "content":{ "direction":"ltr", "content":"Diventa un cuoco provetto con “La Prova del Cuoco”: le videoricette in un' applicazione di facile e veloce consultazione per il tuo Iphone. Scopri come acquistare ..." } }, { "title":"Le prove Invalsi di matematica e italiano", "id":"http://online.scuola.zanichelli.it/quartaprova/", "updated":1350213486, "feed":[ { "href":"http://online.scuola.zanichelli.it/quartaprova/feed/" } ], "alternate":[ { "href":"http://online.scuola.zanichelli.it/quartaprova/", "type":"text/html" } ], "content":{ "direction":"ltr", "content":"Un sito Zanichelli dedicato alle prove Invalsi di italiano e matematica: esercitazioni, consigli, informazioni utili, novità, aggiornamenti e blog d'autore sulle prove ..." } }, How can I get the feed URL? That's what I do NSString *daParsare=[reader searchFeed:searchText]; NSArray *items = [[daParsare JSONValue] objectForKey:@"items"]; for (NSDictionary *item in items) { NSString *title = [item objectForKey:@"title"]; NSString *feed = [item valueForKeyPath:@"feed.href"]; } [tab reloadData]; With the title everything is ok but when I try to access to the feed paramater I get the error...

    Read the article

  • Building applications with WPF, MVVM and Prism(aka CAG)

    - by skjagini
    In this article I am going to walk through an application using WPF and Prism (aka composite application guidance, CAG) which simulates engaging a taxi (cab).  The rules are simple, the app would have3 screens A login screen to authenticate the user An information screen. A screen to engage the cab and roam around and calculating the total fare Metered Rate of Fare The meter is required to be engaged when a cab is occupied by anyone $3.00 upon entry $0.35 for each additional unit The unit fare is: one-fifth of a mile, when the cab is traveling at 6 miles an hour or more; or 60 seconds when not in motion or traveling at less than 12 miles per hour. Night surcharge of $.50 after 8:00 PM & before 6:00 AM Peak hour Weekday Surcharge of $1.00 Monday - Friday after 4:00 PM & before 8:00 PM New York State Tax Surcharge of $.50 per ride. Example: Friday (2010-10-08) 5:30pm Start at Lexington Ave & E 57th St End at Irving Pl & E 15th St Start = $3.00 Travels 2 miles at less than 6 mph for 15 minutes = $3.50 Travels at more than 12 mph for 5 minutes = $1.75 Peak hour Weekday Surcharge = $1.00 (ride started at 5:30 pm) New York State Tax Surcharge = $0.50 Before we dive into the app, I would like to give brief description about the framework.  If you want to jump on to the source code, scroll all the way to the end of the post. MVVM MVVM pattern is in no way related to the usage of PRISM in your application and should be considered if you are using WPF irrespective of PRISM or not. Lets say you are not familiar with MVVM, your typical UI would involve adding some UI controls like text boxes, a button, double clicking on the button,  generating event handler, calling a method from business layer and updating the user interface, it works most of the time for developing small scale applications. The problem with this approach is that there is some amount of code specific to business logic wrapped in UI specific code which is hard to unit test it, mock it and MVVM helps to solve the exact problem. MVVM stands for Model(M) – View(V) – ViewModel(VM),  based on the interactions with in the three parties it should be called VVMM,  MVVM sounds more like MVC (Model-View-Controller) so the name. Why it should be called VVMM: View – View Model - Model WPF allows to create user interfaces using XAML and MVVM takes it to the next level by allowing complete separation of user interface and business logic. In WPF each view will have a property, DataContext when set to an instance of a class (which happens to be your view model) provides the data the view is interested in, i.e., view interacts with view model and at the same time view model interacts with view through DataContext. Sujith, if view and view model are interacting directly with each other how does MVVM is helping me separation of concerns? Well, the catch is DataContext is of type Object, since it is of type object view doesn’t know exact type of view model allowing views and views models to be loosely coupled. View models aggregate data from models (data access layer, services, etc) and make it available for views through properties, methods etc, i.e., View Models interact with Models. PRISM Prism is provided by Microsoft Patterns and Practices team and it can be downloaded from codeplex for source code,  samples and documentation on msdn.  The name composite implies, to compose user interface from different modules (views) without direct dependencies on each other, again allowing  loosely coupled development. Well Sujith, I can already do that with user controls, why shall I learn another framework?  That’s correct, you can decouple using user controls, but you still have to manage some amount of coupling, like how to do you communicate between the controls, how do you subscribe/unsubscribe, loading/unloading views dynamically. Prism is not a replacement for user controls, provides the following features which greatly help in designing the composite applications. Dependency Injection (DI)/ Inversion of Control (IoC) Modules Regions Event Aggregator  Commands Simply put, MVVM helps building a single view and Prism helps building an application using the views There are other open source alternatives to Prism, like MVVMLight, Cinch, take a look at them as well. Lets dig into the source code.  1. Solution The solution is made of the following projects Framework: Holds the common functionality in building applications using WPF and Prism TaxiClient: Start up project, boot strapping and app styling TaxiCommon: Helps with the business logic TaxiModules: Holds the meat of the application with views and view models TaxiTests: To test the application 2. DI / IoC Dependency Injection (DI) as the name implies refers to injecting dependencies and Inversion of Control (IoC) means the calling code has no direct control on the dependencies, opposite of normal way of programming where dependencies are passed by caller, i.e inversion; aside from some differences in terminology the concept is same in both the cases. The idea behind DI/IoC pattern is to reduce the amount of direct coupling between different components of the application, the higher the dependency the more tightly coupled the application resulting in code which is hard to modify, unit test and mock.  Initializing Dependency Injection through BootStrapper TaxiClient is the starting project of the solution and App (App.xaml)  is the starting class that gets called when you run the application. From the App’s OnStartup method we will invoke BootStrapper.   namespace TaxiClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e);   (new BootStrapper()).Run(); } } } BootStrapper is your contact point for initializing the application including dependency injection, creating Shell and other frameworks. We are going to use Unity for DI and there are lot of open source DI frameworks like Spring.Net, StructureMap etc with different feature set  and you can choose a framework based on your preferences. Note that Prism comes with in built support for Unity, for example we are deriving from UnityBootStrapper in our case and for any other DI framework you have to extend the Prism appropriately   namespace TaxiClient { public class BootStrapper: UnityBootstrapper { protected override IModuleCatalog CreateModuleCatalog() { return new ConfigurationModuleCatalog(); } protected override DependencyObject CreateShell() { Framework.FrameworkBootStrapper.Run(Container, Application.Current.Dispatcher);   Shell shell = new Shell(); shell.ResizeMode = ResizeMode.NoResize; shell.Show();   return shell; } } } Lets take a look into  FrameworkBootStrapper to check out how to register with unity container. namespace Framework { public class FrameworkBootStrapper { public static void Run(IUnityContainer container, Dispatcher dispatcher) { UIDispatcher uiDispatcher = new UIDispatcher(dispatcher); container.RegisterInstance<IDispatcherService>(uiDispatcher);   container.RegisterType<IInjectSingleViewService, InjectSingleViewService>( new ContainerControlledLifetimeManager());   . . . } } } In the above code we are registering two components with unity container. You shall observe that we are following two different approaches, RegisterInstance and RegisterType.  With RegisterInstance we are registering an existing instance and the same instance will be returned for every request made for IDispatcherService   and with RegisterType we are requesting unity container to create an instance for us when required, i.e., when I request for an instance for IInjectSingleViewService, unity will create/return an instance of InjectSingleViewService class and with RegisterType we can configure the life time of the instance being created. With ContaienrControllerLifetimeManager, the unity container caches the instance and reuses for any subsequent requests, without recreating a new instance. Lets take a look into FareViewModel.cs and it’s constructor. The constructor takes one parameter IEventAggregator and if you try to find all references in your solution for IEventAggregator, you will not find a single location where an instance of EventAggregator is passed directly to the constructor. The compiler still finds an instance and works fine because Prism is already configured when used with Unity container to return an instance of EventAggregator when requested for IEventAggregator and in this particular case it is called constructor injection. public class FareViewModel:ObservableBase, IDataErrorInfo { ... private IEventAggregator _eventAggregator;   public FareViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; InitializePropertyNames(); InitializeModel(); PropertyChanged += OnPropertyChanged; } ... 3. Shell Shells are very similar in operation to Master Pages in asp.net or MDI in Windows Forms. And shells contain regions which display the views, you can have as many regions as you wish in a given view. You can also nest regions. i.e, one region can load a view which in itself may contain other regions. We have to create a shell at the start of the application and are doing it by overriding CreateShell method from BootStrapper From the following Shell.xaml you shall notice that we have two content controls with Region names as ‘MenuRegion’ and ‘MainRegion’.  The idea here is that you can inject any user controls into the regions dynamically, i.e., a Menu User Control for MenuRegion and based on the user action you can load appropriate view into MainRegion.    <Window x:Class="TaxiClient.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism" Title="Taxi" Height="370" Width="800"> <Grid Margin="2"> <ContentControl Regions:RegionManager.RegionName="MenuRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />   <ContentControl Grid.Row="1" Regions:RegionManager.RegionName="MainRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" /> <!--<Border Grid.ColumnSpan="2" BorderThickness="2" CornerRadius="3" BorderBrush="LightBlue" />-->   </Grid> </Window> 4. Modules Prism provides the ability to build composite applications and modules play an important role in it. For example if you are building a Mortgage Loan Processor application with 3 components, i.e. customer’s credit history,  existing mortgages, new home/loan information; and consider that the customer’s credit history component involves gathering data about his/her address, background information, job details etc. The idea here using Prism modules is to separate the implementation of these 3 components into their own visual studio projects allowing to build components with no dependency on each other and independently. If we need to add another component to the application, the component can be developed by in house team or some other team in the organization by starting with a new Visual Studio project and adding to the solution at the run time with very little knowledge about the application. Prism modules are defined by implementing the IModule interface and each visual studio project to be considered as a module should implement the IModule interface.  From the BootStrapper.cs you shall observe that we are overriding the method by returning a ConfiguratingModuleCatalog which returns the modules that are registered for the application using the app.config file  and you can also add module using code. Lets take a look into configuration file.   <?xml version="1.0"?> <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Prism.Modularity.ModulesConfigurationSection, Microsoft.Practices.Prism"/> </configSections> <modules> <module assemblyFile="TaxiModules.dll" moduleType="TaxiModules.ModuleInitializer, TaxiModules" moduleName="TaxiModules"/> </modules> </configuration> Here we are adding TaxiModules project to our solution and TaxiModules.ModuleInitializer implements IModule interface   5. Module Mapper With Prism modules you can dynamically add or remove modules from the regions, apart from that Prism also provides API to control adding/removing the views from a region within the same module. Taxi Information Screen: Engage the Taxi Screen: The sample application has two screens, ‘Taxi Information’ and ‘Engage the Taxi’ and they both reside in same module, TaxiModules. ‘Engage the Taxi’ is again made of two user controls, FareView on the left and TotalView on the right. We have created a Shell with two regions, MenuRegion and MainRegion with menu loaded into MenuRegion. We can create a wrapper user control called EngageTheTaxi made of FareView and TotalView and load either TaxiInfo or EngageTheTaxi into MainRegion based on the user action. Though it will work it tightly binds the user controls and for every combination of user controls, we need to create a dummy wrapper control to contain them. Instead we can apply the principles we learned so far from Shell/regions and introduce another template (LeftAndRightRegionView.xaml) made of two regions Region1 (left) and Region2 (right) and load  FareView and TotalView dynamically.  To help with loading of the views dynamically I have introduce an helper an interface, IInjectSingleViewService,  idea suggested by Mike Taulty, a must read blog for .Net developers. using System; using System.Collections.Generic; using System.ComponentModel;   namespace Framework.PresentationUtility.Navigation {   public interface IInjectSingleViewService : INotifyPropertyChanged { IEnumerable<CommandViewDefinition> Commands { get; } IEnumerable<ModuleViewDefinition> Modules { get; }   void RegisterViewForRegion(string commandName, string viewName, string regionName, Type viewType); void ClearViewFromRegion(string viewName, string regionName); void RegisterModule(string moduleName, IList<ModuleMapper> moduleMappers); } } The Interface declares three methods to work with views: RegisterViewForRegion: Registers a view with a particular region. You can register multiple views and their regions under one command.  When this particular command is invoked all the views registered under it will be loaded into their regions. ClearViewFromRegion: To unload a specific view from a region. RegisterModule: The idea is when a command is invoked you can load the UI with set of controls in their default position and based on the user interaction, you can load different contols in to different regions on the fly.  And it is supported ModuleViewDefinition and ModuleMappers as shown below. namespace Framework.PresentationUtility.Navigation { public class ModuleViewDefinition { public string ModuleName { get; set; } public IList<ModuleMapper> ModuleMappers; public ICommand Command { get; set; } }   public class ModuleMapper { public string ViewName { get; set; } public string RegionName { get; set; } public Type ViewType { get; set; } } } 6. Event Aggregator Prism event aggregator enables messaging between components as in Observable pattern, Notifier notifies the Observer which receives notification it is interested in. When it comes to Observable pattern, Observer has to unsubscribes for notifications when it no longer interested in notifications, which allows the Notifier to remove the Observer’s reference from it’s local cache. Though .Net has managed garbage collection it cannot remove inactive the instances referenced by an active instance resulting in memory leak, keeping the Observers in memory as long as Notifier stays in memory.  Developers have to be very careful to unsubscribe when necessary and it often gets overlooked, to overcome these problems Prism Event Aggregator uses weak references to cache the reference (Observer in this case)  and releases the reference (memory) once the instance goes out of scope. Using event aggregator is very simple, declare a generic type of CompositePresenationEvent by inheriting from it. using Microsoft.Practices.Prism.Events; using TaxiCommon.BAO;   namespace TaxiCommon.CompositeEvents { public class TaxiOnMoveEvent:CompositePresentationEvent<TaxiOnMove> { } }   TaxiOnMove.cs includes the properties which we want to exchange between the parties, FareView and TotalView. using System;   namespace TaxiCommon.BAO { public class TaxiOnMove { public TimeSpan MinutesAtTweleveMPH { get; set; } public double MilesAtSixMPH { get; set; } } }   Lets take a look into FareViewodel (Notifier) and how it raises the event.  Here we are raising the event by getting the event through GetEvent<..>() and publishing it with the payload private void OnAddMinutes(object obj) { TaxiOnMove payload = new TaxiOnMove(); if(MilesAtSixMPH != null) payload.MilesAtSixMPH = MilesAtSixMPH.Value; if(MinutesAtTweleveMPH != null) payload.MinutesAtTweleveMPH = new TimeSpan(0,0,MinutesAtTweleveMPH.Value,0);   _eventAggregator.GetEvent<TaxiOnMoveEvent>().Publish(payload); ResetMinutesAndMiles(); } And TotalViewModel(Observer) subscribes to notifications by getting the event through GetEvent<..>() namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { .... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; ... }   private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>() .Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>() .Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>() .Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   ... private void OnTaxiMove(TaxiOnMove taxiOnMove) { OnMoveFare fare = new OnMoveFare(taxiOnMove); Fares.Add(fare); SetTotalFare(new []{fare}); }   .... 7. MVVM through example In this section we are going to look into MVVM implementation through example.  I have all the modules declared in a single project, TaxiModules, again it is not necessary to have them into one project. Once the user logs into the application, will be greeted with the ‘Engage the Taxi’ screen which is made of two user controls, FareView.xaml and TotalView.Xaml. As you can see from the solution explorer, each of them have their own code behind files and  ViewModel classes, FareViewMode.cs, TotalViewModel.cs Lets take a look in to the FareView and how it interacts with FareViewModel using MVVM implementation. FareView.xaml acts as a view and FareViewMode.cs is it’s view model. The FareView code behind class   namespace TaxiModules.Views { /// <summary> /// Interaction logic for FareView.xaml /// </summary> public partial class FareView : UserControl { public FareView(FareViewModel viewModel) { InitializeComponent(); this.Loaded += (s, e) => { this.DataContext = viewModel; }; } } } The FareView is bound to FareViewModel through the data context  and you shall observe that DataContext is of type Object, i.e. the FareView doesn’t really know the type of ViewModel (FareViewModel). This helps separation of View and ViewModel as View and ViewModel are independent of each other, you can bind FareView to FareViewModel2 as well and the application compiles just fine. Lets take a look into FareView xaml file  <UserControl x:Class="TaxiModules.Views.FareView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:Commands="clr-namespace:Microsoft.Practices.Prism.Commands;assembly=Microsoft.Practices.Prism"> <Grid Margin="10" > ....   <Border Style="{DynamicResource innerBorder}" Grid.Row="0" Grid.Column="0" Grid.RowSpan="11" Grid.ColumnSpan="2" Panel.ZIndex="1"/>   <Label Grid.Row="0" Content="Engage the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="1" Content="Select the State"/> <ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding States}" Height="auto"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ComboBox.ItemTemplate> <ComboBox.SelectedItem> <Binding Path="SelectedState" Mode="TwoWay"/> </ComboBox.SelectedItem> </ComboBox> <Label Grid.Row="2" Content="Select the Date of Entry"/> <Toolkit:DatePicker Grid.Row="2" Grid.Column="1" SelectedDate="{Binding DateOfEntry, ValidatesOnDataErrors=true}" /> <Label Grid.Row="3" Content="Enter time 24hr format"/> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding TimeOfEntry, TargetNullValue=''}"/> <Button Grid.Row="4" Grid.Column="1" Content="Start the Meter" Commands:Click.Command="{Binding StartMeterCommand}" />   <Label Grid.Row="5" Content="Run the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="6" Content="Number of Miles &lt;@6mph"/> <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding MilesAtSixMPH, TargetNullValue='', ValidatesOnDataErrors=true}"/> <Label Grid.Row="7" Content="Number of Minutes @12mph"/> <TextBox Grid.Row="7" Grid.Column="1" Text="{Binding MinutesAtTweleveMPH, TargetNullValue=''}"/> <Button Grid.Row="8" Grid.Column="1" Content="Add Minutes and Miles " Commands:Click.Command="{Binding AddMinutesCommand}"/> <Label Grid.Row="9" Content="Other Operations" Style="{DynamicResource innerHeader}"/> <Button Grid.Row="10" Grid.Column="1" Content="Reset the Meter" Commands:Click.Command="{Binding ResetCommand}"/>   </Grid> </UserControl> The highlighted code from the above code shows data binding, for example ComboBox which displays list of states has it’s ItemsSource bound to States property, with DataTemplate bound to Name and SelectedItem  to SelectedState. You might be wondering what are all these properties and how it is able to bind to them.  The answer lies in data context, i.e., when you bound a control, WPF looks for data context on the root object (Grid in this case) and if it can’t find data context it will look into root’s root, i.e. FareView UserControl and it is bound to FareViewModel.  Each of those properties have be declared on the ViewModel for the View to bind correctly. To put simply, View is bound to ViewModel through data context of type object and every control that is bound on the View actually binds to the public property on the ViewModel. Lets look into the ViewModel code (the following code is not an exact copy of FareViewMode.cs, pasted relevant code for this section)   namespace TaxiModules.ViewModels { public class FareViewModel:ObservableBase, IDataErrorInfo { public List<USState> States { get { return USStates.StateList; } }   public USState SelectedState { get { return _selectedState; } set { _selectedState = value; RaisePropertyChanged(_selectedStatePropertyName); } }   public DateTime? DateOfEntry { get { return _dateOfEntry; } set { _dateOfEntry = value; RaisePropertyChanged(_dateOfEntryPropertyName); } }   public TimeSpan? TimeOfEntry { get { return _timeOfEntry; } set { _timeOfEntry = value; RaisePropertyChanged(_timeOfEntryPropertyName); } }   public double? MilesAtSixMPH { get { return _milesAtSixMPH; } set { _milesAtSixMPH = value; RaisePropertyChanged(_distanceAtSixMPHPropertyName); } }   public int? MinutesAtTweleveMPH { get { return _minutesAtTweleveMPH; } set { _minutesAtTweleveMPH = value; RaisePropertyChanged(_minutesAtTweleveMPHPropertyName); } }   public ICommand StartMeterCommand { get { if(_startMeterCommand == null) { _startMeterCommand = new DelegateCommand<object>(OnStartMeter, CanStartMeter); } return _startMeterCommand; } }   public ICommand AddMinutesCommand { get { if(_addMinutesCommand == null) { _addMinutesCommand = new DelegateCommand<object>(OnAddMinutes, CanAddMinutes); } return _addMinutesCommand; } }   public ICommand ResetCommand { get { if(_resetCommand == null) { _resetCommand = new DelegateCommand<object>(OnResetCommand); } return _resetCommand; } }   } private void OnStartMeter(object obj) { _eventAggregator.GetEvent<TaxiStartedEvent>().Publish( new TaxiStarted() { EngagedOn = DateOfEntry.Value.Date + TimeOfEntry.Value, EngagedState = SelectedState.Value });   _isMeterStarted = true; OnPropertyChanged(this,null); } And views communicate user actions like button clicks, tree view item selections, etc using commands. When user clicks on ‘Start the Meter’ button it invokes the method StartMeterCommand, which calls the method OnStartMeter which publishes the event to TotalViewModel using event aggregator  and TaxiStartedEvent. namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { ... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator;   InitializePropertyNames(); InitializeModel(); SubscribeToEvents(); }   public decimal? TotalFare { get { return _totalFare; } set { _totalFare = value; RaisePropertyChanged(_totalFarePropertyName); } } .... private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>().Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>().Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>().Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   private void OnTaxiStarted(TaxiStarted taxiStarted) { Fares.Add(new EntryFare()); Fares.Add(new StateTaxFare(taxiStarted)); Fares.Add(new NightSurchargeFare(taxiStarted)); Fares.Add(new PeakHourWeekdayFare(taxiStarted));   SetTotalFare(Fares); }   private void SetTotalFare(IEnumerable<IFare> fares) { TotalFare = (_totalFare ?? 0) + TaxiFareHelper.GetTotalFare(fares); } ....   } }   TotalViewModel subscribes to events, TaxiStartedEvent and rest. When TaxiStartedEvent gets invoked it calls the OnTaxiStarted method which sets the total fare which includes entry fee, state tax, nightly surcharge, peak hour weekday fare.   Note that TotalViewModel derives from ObservableBase which implements the method RaisePropertyChanged which we are invoking in Set of TotalFare property, i.e, once we update the TotalFare property it raises an the event that  allows the TotalFare text box to fetch the new value through the data context. ViewModel is communicating with View through data context and it has no knowledge about View, helping in loose coupling of ViewModel and View.   I have attached the source code (.Net 4.0, Prism 4.0, VS 2010) , download and play with it and don’t forget to leave your comments.  

    Read the article

  • Dependency Injection -Colloquial explanation

    - by nettguy
    Recently I was asked to express the DI in colloquial explanation. I answered : 1) I am going to a hotel.I ordered food.The hotel management asks me to clean the plates and clean the tables.So here i am a client,I am responsible for managing the service (Instantiating,executing,disposing).But DI decouples such tasks so the service consumer no need not worry about controlling the life cycle of the service. 2) He also asked is there any microsoft API follows DI ?.I answered (This was my guess) In WCF you can create a Proxy using ChannelFactory that controls the life time of your factory. for item (1) he said only 10% is correct for item(2) he said that is factory pattern not dependency injection. Actually what went wrong in my explanation (apart from my bad English) ? What is the real answers for those? I am waiting for your valuable suggestions.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >