First of all, I am creating a something like a client/server solution using a standard ASP.NET website - I do know this method is not adviced, and most people would love to scream "COMET!" or "HTML5 Sockets!" - but please don't ;-) !
What I am doing...
I am creating an MMORPG on a website.
I have several clients whom need to be in contact at the same time. This is done by a global object in the Application scope.
My problem
I need to invoke an event to several clients. For instance, when an attack has been performed, I need to update some graphics. The attack logic is resolved in the global object, but each of the clients has to respond to this.
Right now I do the following:
fightTrace.Reciever.InvokeMoveEnded(this);
fightTrace.FiredBy.InvokeMoveEnded(this);
(This is a kind of observer pattern)
What now happends is a race condition. The one who loads the page_load event will get both of these events, and the one who is not running them, will experience no changes in the UI.
So what is it I really want?
What I really need is some genuine and nice way to create an observer pattern through the application state. I need to send an event out to every "listener" which is in this case is a client, and then do some update.
One way to do this is some session-thing, with true/false.. But I would really like some better way!
Thanks!
If I understood your context correctly then whenever the state of your application state object is changed you want to synchronize all the clients of your applications. What you are forgetting here is the stateless behavior of HTTP protocol. Once a response is sent the connection is lost you need to send an HTTP request again to be served again. However you can emulate some thing using State Management and Ajax based short and timely updates to simulate a connected environment. However I've to utter the words which you don't want to hear. Not recommended.
Instead what you can do is to save the state of application object and whenever a request comes serve the response based on updated state of your object. Any how a client has to initiate a request.
Related
I don't know too much about services so if I am trying to do something they are not intended for please forgive me.
I am trying to wright dispatching software for a family member. They plan on starting with 3 or 4 dispatchers but it may scale in the future. I need the software to constantly (every 5 or 10 seconds at the very least) check and see if a new unhandled call has been placed when not in a call or if they are in a call see if another dispatcher updated the call (due to a call in with additional information).
Which option would be better for the above scenario
A) Have a table in a database that tracks updates to calls/ new calls and poll it every 5 - 10 seconds from every instance of the software.
B) Have a service running on the machine that has the database and have that service take care of all SQL. Create an instance of each call in the service and then just ask the service if there are any changes or unhandled call.
If B, is it possible to create a delegate in the service that the software on another (networked) machine can subscribe to? If so where might I find information on doing that, I could not find anything on google.
This is kind to broad.
However, you can use the following
DB Trigger to watch for inserts ect, then do and fabulous db stuff when triggered.
Create a Windows Service that polls, thats not a problem at all.
You could even self host a WCF server with a Duplex Contract that other software subscribes to, you could then send notifications ect via that channel.
or use SignalR for notification which would work just fine in this situation as well, and is a 5 minute job to get working.
Though, there is lots of approaches here, You really need to do some research to find what suits you most
Solution B is better.
If B, is it possible to create a delegate in the service that the
software on another (networked) machine can subscribe to? If so where
might I find information on doing that, I could not find anything on
google.
It depends on your need and project type.
You can use SignalR in ASP.Net
If you work with sockets you can keep connection alive and store client context in a list and notify theme
I am currently working on a project in ASP.NET MVC 4 and came along a module where a progress bar is needed. The question I am having right now is "What is the best way to implement an async progress bar?".
After some lookup I came across the following method:
Create a startEvent() and getProgress() in C# code.
Use javascript setTimeout() to call the getProgress() method asynchronously.
(Example: https://www.devexpress.com/Support/Center/Example/Details/E4244)
My remark with this method is that that causes the code to be dependent on the timeout you choose. So it would take some fiddling to find the best and most performant timeout.
Now the method that I would most likely have used before I researched the matter is the following:
In code behind, create a method handleItem(int index) which takes an index and does everything you want to do with the item at that index.
Determine the number of items you want to handle and pass that to your javascript.
In javascript, initiate a for loop that loops from 0 to the amount - 1, and for each index, it initiates an ajax-call to handleItem(i).
On that ajax-call's complete-statement, you can update the progress bar with the new amount.
My questions here are the following:
Does this expose too much of the program logic?
Does this create too much overhead seeing as every call goes to the server and back?
Are there any other reasons why I should refrain from using this method?
Thanks in advance
Koen Morren
This is not a recommended strategy, because the client drives the process. If there is any discontinuation of connectivity or maybe the user closes the browser, the process will stop.
Generally, if you use straight HTTP you will need to poll (aka pull) from javascript. The pseudo code is pretty much this:
Call Creates Task ID and sends it to client
Client queries the status of task with given ID
Another possibility are WebSockets, which allow your client to listen for changes that are pushed by the server.
There are many options to store the progress of a given state. You can index the progress by the HttpContext, task id, or some user id, or even store it in a database and use SqlDependency to get notifications of when the status is changed.
In summary, polling has more lag than push mechanisms. Clients should not drive an asynchronous process, but they should be either notified or provided some mechanisms on the status of an async process.
Unlike ASP.NET, there is few way to push data from server to client in MVC, WebSockets or SingnalR like api(s) can work for you.
The ajax approach is good and give you reliable mechanism to update data no matter user go to other page or closes the browser, every time ajax launched it will update UI. So there is nothing wrong there just have a fair interval in javascript.
Does this expose too much of the program logic?
Code will be written only in class file to calculate current %age.
2.Does this create too much overhead seeing as every call goes to the server and back?
No, ajax are light-weight calls
3.Are there any other reasons why I should refrain from using this method?
This method will allow user to freely navigate to other resources as ajax will work independently.
I have this scenario, and I don't really know where to start. Suppose there's a Web service-like app (might be API tho) hosted on a server. That app receives a request to proccess some data (through some method we will call processData(data theData)).
On the other side, there's a robot (might be installed on the same server) that procceses the data. So, The web-service inserts the request on a common Database (both programms have access to it), and it's supposed to wait for that row to change and send the results back.
The robot periodically check the database for new rows, proccesses the data and set some sort of flag to that row, indicating that the data was processed.
So the main problem here is, what should the method proccessData(..) do to check for the changes of the data row?.
I know one way to do it: I can build an iteration block that checks for the row every x secs. But i don't want to do that. What I want to do is to build some sort of event listener, that triggers when the row changes. I know it might involve some asynchronous programming
I might be dreaming, but is that even possible in a web enviroment.?
I've been reading about a SqlDependency class, Async and AWait classes, etc..
Depending on how much control you have over design of this distributed system, it might be better for its architecture if you take a step back and try to think outside the domain of solutions you have narrowed the problem down to so far. You have identified the "main problem" to be finding a way for the distributed services to communicate with each other through the common database. Maybe that is a thought you should challenge.
There are many potential ways for these components to communicate and if your design goal is to reduce latency and thus avoid polling, it might in fact be the right way for the service that needs to be informed of completion of this work item to be informed of it right away. However, if in the future the throughput of this system has to increase, processing work items in bulk and instead poll for the information might become the only feasible option. This is also why I have chosen to word my answer a bit more generically and discuss the design of this distributed system more abstractly.
If after this consideration your answer remains the same and you do want immediate notification, consider having the component that processes a work item to notify the component(s) that need to be notified. As a general design principle for distributed systems, it is best to have the component that is most authoritative for a given set of data to also be the component to answer requests about that data. In this case, the data you have is the completion status of your work items, so the best component to act on this would be the component completing the work items. It might be better for that component to inform calling clients and components of that completion. Here it's also important to know if you only write this data to the database for the sake of communication between components or if those rows have any value beyond the completion of a given work item, such as for reporting purposes or performance indicators (KPIs).
I think there can be valid reasons, though, why you would not want to have such a call, such as reducing coupling between components or lack of access to communicate with the other component in a direct manner. There are many communication primitives that allow such notification, such as MSMQ under Windows, or Queues in Windows Azure. There are also reasons against it, such as dependency on a third component for communication within your system, which could reduce the availability of your system and lead to outages. The questions you might want to ask yourself here are: "How much work can my component do when everything around it goes down?" and "What are my design priorities for this system in terms of reliability and availability?"
So I think the main problem you might want to really try to solve fist is a bit more abstract: how should the interface through which components of this distributed system communicate look like?
If after all of this you remain set on having the interface of communication between those components be the SQL database, you could explore using INSERT and UPDATE triggers in SQL. You can easily look up the syntax of those commands and specify Stored Procedures that then get executed. In those stored procedures you would want to check the completion flag of any new rows and possibly restrain the number of rows you check by date or have an ID for the last processed work item. To then notify the other component, you could go as far as using the built-in stored procedure XP_cmdshell to execute command lines under Windows. The command you execute could be a simple tool that pings your service for completion of the task.
I'm sorry to have initially overlooked your suggestion to use SQL Query Notifications. That is also a feasible way and works through the Service Broker component. You would define a SqlCommand, as if normally querying your database, pass this to an instance of SqlDependency and then subscribe to the event called OnChange. Once you execute the SqlCommand, you should get calls to the event handler you added to OnChange.
I am not sure, however, how to get the exact changes to the database out of the SqlNotificationEventArgs object that will be passed to your event handler, so your query might need to be specific enough for the application to tell that the work item has completed whenever the query changes, or you might have to do another round-trip to the database from your application every time you are notified to be able to tell what exactly has changed.
Are you referring to a Message Queue? The .Net framework already provides this facility. I would say let the web service manage an application level queue. The robot will request the same web service for things to do. Assuming that the data needed for the jobs are small, you can keep the whole thing in memory. I would rather not involve a database, if you don't already have one.
Ok, long story short I have a Windows service that handles Win32_VolumeChangeEvent and logs USB disk device arrivals to the Event Log and to a SQL database. An additional component to this is a hidden UI (WinForms) which loads in the user session at login - this pops up a message box reminding users of company policy about USB keys etc. AFAIK, this was the best way to go since services can no longer run in interactive mode.
Anywho... architecturally, v1 of this little thing ran with the UI component handling WndProc messages for device insertion, then passed the device identifier through IPC (named pipes) to the service which would handle WMI methods / EventLog writing (as not all users have local admin rights). This had the downside of the UI element being process killed and no longer detecting device insertions.
So, current version is that the service handles Win32_VolumeChangeEvents and gets the needed details from the device, then logs to EventLog and SQL. All is outstanding and works perfectly. Except now I'm wondering what the best way to trigger the UI into displaying the popup is.
I've researched around Google and here, looking for ideas about eventing over IPC, so I can just subscribe to an event from the UI component and fire it within the service, but I'm not finding much that jumps out as being helpful. I'm also constrained to .net2, so WCF is out of the picture (although I'm not afraid of p/invoke if you want to go that way).
So. How would you do it? Links, thoughts, ramblings, pseudocode, actual code... all is appreciated. I'm trying to stick to what I believe is best practice, although I also think programming is a bit of an art form and my best practice may be someone else's horror story.
So SO - what would you do? Let me know if I need to clarify :)
Back in the bad old days of Windows API programming, we'd sometimes use RegisterWindowMessage to register a unique message ID that (presumably) only our window knew how to handle. We could then trigger that window from another application by calling PostMessage with a window handle of HWND_BROADCAST, and the msg parameter being that unique message value. That works great if everything you want to share between the processes can fit into two DWORD values (wparam and lparam). Sharing more data can be done if you allocate global memory and pass a reference as one of the parameters.
That should still be possible with .NET. Certainly there's no trouble calling PostMessage. As for handling the message in the UI code, you have to override the Form's WndProc. See How do I send/receive windows messages between VB6 and c#? for an example.
You could do something with named events, although that would only notify the UI that some change had occurred. It wouldn't actually tell you what happened. I suppose, if there's only a small set of possible events, you could have multiple events, but that gets complicated pretty quickly.
You could go the named event route and use shared memory (memory mapped file) to share the state.
Or, you could set up sockets, named pipes, TcpListener/TcpClient, or even a UdpClient. All should work, with varying degrees of complexity and/or reliability.
The only idea that comes to my mind is to have a service check the state of the UI application periodically and restart it if it has been killed. There seems to be no standard module that would run within user's session and let the service send notifications to this module. There exist third-party solutions but they can be killed (not saying that they should be installed in order to be used).
Update: after re-reading the question I think that maybe your UI doesn't receive windows messages, so you need another mechanism. Why not create a Semaphore synchronization object in service and wait for it in UI process (in a separate thread)?
I'm currently in the process of building an ASP.NET MVC web application in c#.
I want to make sure that this application is built so that it can scale out in the future without the need for major re-factoring.
I'm quite keen on using some sort of queue to post any writes to my database base to and have a process which polls that queue asynchronously to perform the update. Once this data has been posted back to the database the client then needs to be updated with the new information. The implication here being that the process to write the data back to the database could take a short while based on business rules executing on the server.
My question is what would be the best way to handle the update from the client\browser perspective.
I'm thinking along the lines of posting the data back to the server and adding it to the queue and immediately sending a response to the client then polling at some frequency to get the updated data. Any best practices or patterns on this would be appreciated.
Also in terms of reading data from the database would you suggest using any particular techniques or would reading straight from db be sufficient given my scenario.
Update
Thought I'd post an update on this as it's been a while. We've actually ended up using Windows Azure but the solution is applicable to other platforms.
What we've ended up doing is using the Windows Azure Queue to post messages\commands to. This is a very quick process and returns immediately. We then have a worker role which processes these messages on another thread. This allows us to minimize any db writes\updates on the web role in theory allowing us to scale more easily.
We handle informing the user via emails or even silently depending on the type of data we are dealing with.
Not sure if this helps but why dont you have an auto refresh on the page every 30 seconds for example. This is sometimes how news feeds work on sports websites, saying the page will be updated every x minutes.
<meta http-equiv="refresh" content="120;url=index.aspx">
Why not let the user manually poll the status of the request? This is how your typical e-commerce app is implemented. When you purchase something online, the order is submitted to a queue for fullfillment. After it's submitted, the user is presented with a "Thank you for your order" page and a link where they can check the status of the order. The user can visit the link anytime to check the status, no need for an auto-poll mechanism.
Is your scenario so different from this?
Sorry in my previous answer I might have misunderstood. I was talking of a "queue" as something stored in a SQL DB, but it seems on reading your post again you are may be talking about a separate message queueing component like MSMQ or JMS?
I would never put a message queue in the front end, between a user and backend SQL DB. Queues are good for scaling across time, which is suitable between backend components, where variances in processing times are acceptable (e.g. order fulfillment)... when dealing with users, this variance is usually not acceptable.
While I don't know if I agree with the logic of why, I do know that something like jQuery is going to make your life a LOT easier. I would suggest making a RESTful web API that your client-side code consumes. For example, you want to post a new order to the system and have the client responsive? Make a post to www.mystore.com/order/create and have that return the new URI to access the order (i.e. order#) as a URI (www.mystore.com/order/1234). That response is then stored in the client code and a jQuery call is setup to poll for a response or stop polling on an error.
For further reading check out this Wikipedia article on the concept of REST.
Additionally you might consider the Reactive Extensions for .NET and within that check out the RxJS sub-project which has some pretty slick ways of handling with the polling problem without causing you to write the polling code yourself. Fun things to play with!
Maybe you can add a "pending transactions" area to the UI. When you queue a transaction, add it to the user's "pending transactions" list.
When it completes, show that in the user's "pending transactions" list the next time they request a new page.
You can make a completed transaction stay listed until the user clicks on it, or for a predetermined length of time.