Why cant WPF's MainWindow be a WCF service? - wpf

I have a WPF app that will show youtube videos on my tv via a media center pc. This app will receive commands to PlayVideo(string VideoId), PauseVideo(), etc via a WCF service hosted inside the WPF app.
This is a newbie question, but why can my MainWindow not implement the service contract and then be used as the service using the new ServiceHost() constructor that takes an object singleton in?
When I try I get this exception:
System.InvalidOperationException: Service 'Desktop.MainWindow' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
My reasoning for doing this is that the simple commands needs to end up at the window anyway, so why not just have the window receive the messages directly instead of indirectly via subscribing to events on the service or having the service have a reference to the MainWindow and call methods on it.

The error, System.InvalidOperationException: Service 'Desktop.MainWindow' has zero application , simply means your app.config (if you have one) does not have the endpoints or the A,B,C's setup correctly (address, binding, contract).
You can host a wcf service in a winform or wpf form, you would only want to do that maybe for a test project in some kind of proof of concept work but never in an application you plan to give to a client or a real user.
If you're new to WPF I strongly recommend reading up on the Model-view-view-Model design pattern. This will allow you to implement the WCF service abstracted away from the UI in your WPF app and will give you a better separation of concerns and responsibilities for the logic in your app.

If you were writing code that others were going to maintain then I'd say...
Why not? Because you're mixing areas of responsibility. The Main Window doesn't need to know anything about WCF, it's job is to present things on screen.
Given that it's your app for your own personal needs, nobody cares what structure you use (just don't ask someone else to maintain it!) :) Having said that, if you want to make it easy for yourself to modify, I'd suggest making an effort to keep the code clean. What you're aiming to do, in my view, doesn't fit that description.
Your mainwindow probably could implement that Service Contract, but I think it's a very bad idea.

Related

How to use google.maps within an asmx web service

I need to calculate distances for some logic within a web service and assume google.maps API is appropriate. Everything I've seen is Jscript and requires a reference to the script in html tags <script>, which does not apply here. A .dll would make things obvious to me, but that does not seem to be available...
How do you access google.maps within a c# .asmx??
You will have to do the same thing that would be done by the JavaScript code you're seeing as examples. You'll want to use the WebClient class or maybe the WebRequest class to do the network I/O, but you've got to send and receive HTTP messages.
"Add Service Reference" won't work, of course.
Note that this problem is not specific to ASMX web services. You would have the exact same issue in a console program or Winforms application.

WPF using PRISM and WCF - how to implement multiple views that connect to WCF services?

I am implementing a WPF client application in MVVM architecture using PRISM (I am new to PRISM).
The WPF application has 3 main regions :
Left Region
Right Region
Side Region
The left region has a view with a 'Fetch Button', that when pressed should connect to a 'FETCH' WCF service, fetch items, disconnect from the service and present the items in the view.
The right region has a view with no buttons. This view should connect every 10 minutes to the 'POLL' WCF service, fetch items, disconnect from the service and present the items in the view.
The side region has a view with no buttons. This view should connect to the 'NOTIFICATIONS' WCF service, and stay connected to it during the whole application life cycle. It should receive callbacks from the service, that should be presented in the Side view.
Here is an image showing what it should look like:
Questions :
What should I pass on to the constructor of the 'FETCH MODULE' that includes the 'Fetch View' ? should it be the service itself or should it be some channel factory ? I think it should be some kind of channel factory, because the connection to the 'Fetch WCF Service' needs to be initiated every time the user pressed the 'fetch' button.
Same question goes for the 'POLL MODULE'.
Regarding the 'NOTIFICATIONS MODULE' - should I pass a Singleton instance of the 'Notification Service Client' ? (since the application needs to open only one client to the service, and it should stay connected all the time)
In order to avoid the 'Notifications' client faulting because of a timeout, I need to implement some sort of 'heartbeat', that will call a stub method on the 'Notifications' WCFservice, so that it doesn't timeout. Where should I place the code for the heartbeat ? should it be in the 'NOTIFICATIONS MODULE' ? who should initiate it ? (I believe it should run in some sort of background thread)
I am currently using MEF, and I don't really know what I am doing (I decorated the views with [Export] and the [ViewModel] setter with [Import] etc, but I still don't understand how I control who gets loaded and when). In addition - I don't understand how the Dependency Injection works in MEF. What are the differences between using 'MEF Bootstrapper' and 'Unity Bootstrapper' ?
I have seen some people use MEF and just use [Import] and [Export] attributes, and some people that inherit their modules from 'IModule' and implement 'InitializeModule' with EventAggreagator, Container and RegionManager. What are the differences between these approaches, and when should you use each approach ?
Do you recommend using the 'Add Service Reference...' or to manually create an 'IChannelFactory' ? (PROs \ CONs)
Should the service clients be part of the Modules or part of the Infrastructure ?
I have searched a lot on the internet for samples of WPF+PRISM+WCF and could not find any good samples I can use, so I can understand how to inject the services into my view-models. Can anyone offer any examples \ sample links ?
Following 4 questions are a tough cookie:
All 3 WCF services I have mentioned use the same 'Username+Password' authentication method, which means I need to pop-up a 'Login' window when the application loads. What is the best practice for doing such a thing in PRISM and MVVM ? Should the 'Login' window replace the 'Shell' window ? (I don't think so, so what should it be ?)
When the user enters the username+password - Should I try to connect to just the first service, and if it succeeds - disconnect from it and close the 'Login' view (meaning, I assume that the connection will succeed with the other services).
Where could I store the username+password the user has entered, so that the application can keep on reconnecting to the services without requesting the user to provide the credentials each time ?
What do you advise should be the approach I take if for some reason - one of the modules tries to connect to one of the WCF services, and doesn't succeed because of credentials ? Should I raise an event that forces all other modules to disconnect from their services, and then pop-up the 'Login' view ?
Sorry for the long post ...

Using ASP.NET session state with Silverlight (PRISM)

The scenario:
I have a PRISM application developed in Silverlight (4), and I'm using a ASP.NET server side application to host several web-services (which, in turn, accesses WCF-services, but that's not really important here). The Silverlight application must be able to call the web services cross-domain (meaning that the web services isn't necessarily on the same server hosting the silverlight application).
The Silverlight application consists of several modules, each accessing the ASP.NET web-services.
I do not have much experience with Silverlight and PRISM, but as far as I can see, this is not a very unusual scenario...
The problem:
My challange is, that when 2 different modules access the web-services, I get 2 new sessions on the web-server. I would have thought that since both modules live on the same HTML-page (and then also in the same browser session), they would get the same session on the web-server...?
I have tried to make the web-service Proxy-client globally available in the container (using Unity), by registering an instance (using Container.RegisterInstance), and then getting this instance whenever a module needs to make a web-service call (using Container.Resolve), but this doesn't seem to help.
However, any calls made within the same module always gets the same session on the server.
Can anyone see what I'm missing here...?
Thanks!
Jon
Looks like I found my own answer.
The problem was that my application was firing multiple web-service calls upon startup (the different PRISM-modules working independently). And when several calls were made before any responses was given from the web-server, no session (and hence no "ASP.NET_SessionId" cookie was provided) back to the client before subsequent calls were made.
My solution was to make sure I make one call (async as always), for example to a simple Ping-like web-service, then hold all other calls to the web-server until this response is back. Then, all subsequent calls are given the same Session on the server (because now they all contain the "ASP.NET_SessionId" cookie in the header).
In pratice, this call is made by the PRISM-shell, and no modules are beeing loaded before I receive the reponse. Then I'm absolutely sure that none of the other modules get trigger-happy before I have a session-state on hand.
Still, if anybody sees any other problems with this solution, I'm more than happy to hear from you.
Thanks!
Jon

Calling Function on a different client SIlverlight

I have one very weird question.
There are 2 Silverlight Client
1. Admin
2. User
Now, I want a scenario wherein the Admin Silverlight can initiate a function call on the User Silverlight.
Pretty much a newbie with SL so wonder if that would be possible.
I'd appreciate any help.
Thanks
I suppose the applications are not in the same browser / machine, and when you describe the usage pattern as admin and user, I take that there are probably more users than admins.
You might want to take a look at duplex bindings for WCF services - this is a web service binding that allows pushing notifications to clients from the server. When all clients establish such a channel, you can implement hub-and-spoke communication between clients.
This blog post gives a good receipt for getting started:
http://silverlightforbusiness.net/2009/06/23/pushing-data-from-the-server-to-silverlight-3-using-a-duplex-wcf-service/
If they are both in the same frame/browser, you could call JavaScript in the first using the HtmlPage API, which could interact with the second.
So:
Silverlight control -> injects JS into HtmlPage -> JS interacts with Silverlight control 2 (assuming this is possible, please correct me if wrong) -> Silverlight control responds.
If they are in separate windows or running "out of browser", I would expect it wouldn't work.
If the 2 instances are seperated (i.e., the admin is on one machine and the user is on another) there's no direct way to do it. However, you can rig it up with a publisher/subscriber style system.
Assumption: You have some sort of shared data store between the two, maybe a database or something.
Idea: You have the admin client write a request to this shared data store; an entry in a table, or a new file in a network share, or something. You have the user client app regularly scan this table/share for new entries, say every .5 seconds or so. When it sees the entry, it executes the requested operation, storing any return values back to the shared store. When the admin sees the return value, he knows the operation has been successfully executed.
There are a couple of options that I can think of.
You could implement some sort of remote procedure call via web services whereby one Silverlight app posts a request to call the method, and the other Silverlight regularly checks for method call requests.
If hosted on the same HTML page in a browser, you could use javascript to allow the two controls to interact.
However, direct communication between two Silverlight instances isn't supported, and while the suggestions may help to achieve something close to what you want, they don't provide a complete solution that will work in all scenarios.

What is the best practice for exception handling in silverlight?

In ASP.NET, I usually log exceptions at server-side, In windows forms I can either log exceptions server-side or write to a log file on the client. Silverlight seems to fit somewhere in between.
I wanted to know what everyone else is doing to handle their Silverlight exceptions and I was curious if any best practices have emerged for this yet.
For real logging that you could store & track, you will need to do it on the server, since you can't be guaranteed anything on the client will be persisted.
I would suggest exposing a "LogEvent(..)" method on a server side web service (maybe you already have one) which would then do the same kind of logging you do in ASP.net
Here's a video about basic web service calls in Silverlight if you haven't done that yet
http://silverlight.net/learn/learnvideo.aspx?video=66723
I'm not sure about any logging best practices though, my first guess would be to do the best practicies for logging in a web sevice on the server and expose that to the client.
Hope this helps!
I would say that Silverlight fits much better to ASP.NET side of the model. You have server which serves web page. An object (Silverlight app) on the page pings data service to fetch data and display it.
All data access happens on the server side and it does not matter if data is used to create ASP.NET pages on the server or sent raw to the RIA for display. I do log any failures in data service on server side (event log works fine) and do not allow any exception to pass to WCF. When client does not receive expected data (it gets null collection or something similar), it display generic data access error to the user. We may need to extend that soon to pass a bit more information (distinguishing between access denied/missing database/infrastructure failure/internal error/etc), but we do not plan to pass exception error messages to the client.
As for client side, sometimes we may get in situation where async call times out -- it is just another message. For general exceptions from client code (typically, bugs in our code), I just pass exception to the browser to display in same manner as any script exception.
Also take a look at the new Silverlight Integration Pack for Enterprise Library from Microsoft patterns & practices. It provides support for logging exceptions to isolated storage or remote services and is configurable via policies in external config or programmatically. Batch logging and automatic retry (in case of occasionally connected scenarios) are also supported.
Use the Isolated Storage available for Silverlight application. You should store here your log.
Then you can develop a mecanism to send the user log to a webservice like the Windows bug report service.
It very much depends on the type of application that youre developing.
if its an mvc / mvp based architecture then your model, or most of it at least, will be on the server, and this is where most of your exceptions will be thrown i would imagine, so you can log them there and choose to display a message to the user or not.
for exceptions from the client you may want to know the details so just send them back.

Resources