like this
public class MyClass {
public static instance = new MyClass();
private List<int> idList;
}
.
I am using this class in two different window application. like this MyClass.instance.IdList.Add(1); All data in idList i am storing in file and fetching info from that file. I am adding value to idList in one app and I am fetching idList info in another app. but it is not showing idList content in second application which is added by first apllication. How to achive this?
Here are a few ways to share data between applications:
WCF would be my preferred way to do this and I will add some explanation here
1) Use of WCF
- Host a WCF service with following functionality [Effort: Moderate]
//Notice the use of Publisher -Subscriber pattern here (each app will subscribe to the service, the service could be hosted by all apps at certain endpoint i.e. net.pipe://localhost/NotificationService (Since multiple applications will try to host the same service only one would succeed and that's exactly what we want)
void Subscribe(object);
void Unsubscribe(object);
// Any client wanting to add an object to the list will call Add
void Add(object objectToAdd);
// Iterate through each subscribing app and send a notification that list changed
void Notify();
// Return the current state of list
IEnumerable<object> GetYourList();
2) Use of Clipboard [Effort: Simple]
3) Use of File system & listening to the file change notification
[Effort: Simple]
4) Memory Mapped Files [Effort: Simple-Moderate]
Maybe Remoting helps you. It allows you to let other applications access functions in your server application over the internet (or a local network). So the code is executed on the server application.
Here is an example: http://www.codeproject.com/KB/IP/Net_Remoting.aspx
Maybe you are aware of this already, but types declared static are local to a single process (application). Reading your example it appears that you are expecting the static instance to be shared and accessible between applications. This is not the case.
A standard way to do what you need is to create a 3rd application/process that exposes synchronised access to a list that both of the other applications can add/remove items from.
why not you are using xml as a mediator between two application. Use XML for the communication.
If you are gonna use .Net 4.0, you could use Memory Mapped Files.
I think this is the prefect candidate for a Message Queue
With the message queue, you can add IDs to the queue in one app, and pull them off in another.
This page gives a good example of how to implement queues: Use Microsoft Message Queuing in C# for inter-process communication
The MSDN gives an example service here: C#: A Message Queuing Service Application
Message Queue is the best way of communicating.
However cheque that you need to enable the "Microsoft Message Queue" component before you can use the service.
Further, we can get real time data exchange as it also creates event, if configured to do so. and FIFO way of accessing the message will enable to process each and every message without missing any single message.
In my case, I had 2 application
WCF Service based application
Windows application
I had used Message Queue to overcome this data sharing issue
Add how much ever queue you want.
Its a blocking read, hence your application doesn't overrun and hog the CPU.
Pretty reliable, no Data loss.
Add Header along with Each data, to recognize it what type of data is this.
How to use :
Create private queues.
push data into it from client side.
another side read and parse it.
How about using the SQL Server Compact Edition?
Related
The cluster needs access to a dataset that lives in sql server, that is outside of the cluster.
Rather than forcing remote calls to the database for every request, I would like to create a stateful service that will periodically refresh its cache with data from the remote database.
Would we be looking at something like this following?
internal sealed class StatefulBackendService : StatefulService
{
public StatefulBackendService(StatefulServiceContext context)
: base(context)
{
}
/// <summary>
/// Optional override to create listeners (like tcp, http) for this service instance.
/// </summary>
/// <returns>The collection of listeners.</returns>
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
return new ServiceReplicaListener[]
{
new ServiceReplicaListener(
serviceContext =>
new KestrelCommunicationListener(
serviceContext,
(url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
return new WebHostBuilder()
.UseKestrel()
.ConfigureServices(
services => services
.AddSingleton<IReliableStateManager>(this.StateManager)
.AddSingleton<StatefulServiceContext>(serviceContext))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl)
.UseStartup<Startup>()
.UseUrls(url)
.Build();
}))
};
}
}
Within this stateful service, how would I load data from a remote database and serve it through controllers?
Let's assume we have a simple model:
Create table Account (varchar name, int key)
I imagine that the operations would be in the following order:
Load Account table into memory
respond to requests such as http://statefulservice/account?$top=10
refresh data in the service on a time interval basis
What are the datatypes that I should be using in order to cache this data? What would be the process of loading the data into the stateful service from a sql server database>?
IMHO, even though it's possible to use Statefull services as a cache backed up by some database, the real power comes when you keep your data in the reliable collections only. With Service Fabric and Reliable Collections, you can store data directly in your service without the need for an external persistent store. See Application scenarios. Aside from providing high availability and low latency, the state is reliably replicated across multiple nodes so it could survive a node failure, and moreover, there is a Back up and restore feature that allows you to deal even with the entire cluster outage.
There are many things you should know about when dealing with Reliable Services. Service partiotioning, Transactions and lock modes, Guidelines and recommendations, etc.
As for the data types, explore Reliable Collection object serialization and Serialization and Upgrade.
Another thing you also should be aware of, is the Reliable Dictionary periodically removes least recently used values from memory, which could increase read latencies in certain cases. See more here - Service fabric reliable dictionary linq query very slow.
A simple example of integrating controllers and StateManager you could find in this article.
l--''''''---------''''''''''''
Here's a little more info related to your comment...
Hey m8... the reliable collections are designed to run multiple instances (the run on more than one node at a time)... Within each instance the data is partitioned into one or more groups (how you decide to partition is entirely up to you)... So there is load distribution and fail over, there is more to say... but I don't want to muddy the waters so I'm attempting to keep it high level. This type of service data in reliable collections exists in memory and can be "backed up"... If you want your data formally written to disc and have more control over WHEN it is written to disc you will need to take a look at Actors. This is a good (very simple) collection of examples of service fabric, reliable collections, and wiring up internal communications. Only think funky about looking at this one is there are a lot of different 'recipes' used to facilitate back-end and communication from the back-end to the public (stateless) side.
I see you added to your question and changed the intent a little... I will pointedly tell you what I 'think' you need for what you are really after... You want one or multiple 'Stateful Service's (this is your data service layer, this can be abstracted into 3 components if you want... the stateful service itself, and 2 class libraries one for your service interface and one for your contracts ... or rather your data models... basically this is a POCO), you would include the 2 class libraries in your stateful service and use them to create dictionary entries (probably something like new IReliableDictionary... and bind the interface. You will want to use (add to) the IService interface (you will need to grab a nuget package 'Service Fabric Remoting' for the interface project you created for your service interface, there is plenty of info out there on how to achieve remoting within service fabric as it is a standard communication method. There is more, but simply building this would be a viable experiment and would effectively take the place or you database. You can formally persist the data to disc using Actors or a simple backup method that is canned with service fabric. Essentially I suggest you build this in order to firm up the fact you can completely remove the database from this scenario... you really don't need it. What I have described above takes the place of the db ONLY... without writing a front-end for this (that uses remoting to communicate with your backend) this would not be accessible to the public... at least not easily.
TL;DR - Basically I'm agreeing with what one of your other contributors is stating... My opinion is less humble so I'll simple state it. You application will be less complicated, faster and more reliable if you handle your data within service fabric... Still TL;DR? - Ditch the db my man. If you are really nervous about it only existing in memory, use Actors
I'd like to have a List<int> that multiple instances of my application can access. At the moment I can cheat and use a global mutex but that hardly would work well after 10K ints. How do I get multiple instances of a program to share a list?
An easy way to do that is to put this data in a custom windows service.
Host in this service the data you want to share and provide access to this data using any kind of IPC. The simplest is WCF.
Another method may consists in having only one instance of the application. Instead of having on form in your app, manage multiple forms as separate "pseudo" instances. When firing the app again, check if the app is already launched and trigger a message to this app.
Lastly, as Raja suggest, use a queue to share data between apps. But this requires more information about how and when the list is populated.
I am trying to implement a scenario.
One of the component of my app system needs to send and receive data from same direct exchange but with two different routing key.
So is there any thing I need to consider such as:
Sharing of variables
such as connection,channel,
Data flow to correct listener
One more thing two components of my app system uses same direct exchange to publish data but uses different routing key. So is it safe?
For guidance around threading then take a look at the .net client documentation, specifically section 2.9 entitled Threading, deadlocks, and associated restrictions on
consumers.
The summary is to create one instance of IConnection, the create a channel (IModel) per thread.
In terms of how you use your queues etc...you will need to ensure that the logic is correct for what you want to achieve.
I want to be able to develop a windows service which is capable of running multiple instances each with different parameters.
Ideally I want to be able to maintain these parameters in a browser based control panel.
I have written a control panel in C# which saves the config data to an XML file.
From this I want to be able to configure the number of services to run, and what their parameters should be.
I want to be able to dynamically add and remove instances of the service as required.
My questions are:
1) Is this even possible?
2) Can I start a service with specific properties, from the control panel? (Maybe by using "NET START" with command line parameters?
[Edit]
I just saw something online regarding the ServiceController class; can this be used to add and remove instances of a service as well as start/stop services?
[/Edit]
Thanks for any help
Edit: My initial answer was factually wrong.
You can use command line parameters, either with NET START (which however will only accept parameters starting with a backslash) or with SC START (which will accept anything as a parameter).
You cannot start a service with dynamically chosen command line parameters. Parameters can also be specified at service registration time, in which case they remain constant thereafter.
However, starting multiple instances of a service sounds like the wrong idea. There is nothing stopping you from making just one instance of the service that you configure at runtime by communicating with it (e.g. with ServiceController.ExecuteCommand), which is what you should do IMHO.
To communicate with a service, see for example How to communicate with a windows service from an application that interacts with the desktop? and How to create and communicate with a C++ Windows Service in Visual Studio 2010?
I am working in VS 2008 C# and need to share an instance of an object created in one project with another project. I tried creating a static class in project1 and adding it as a link to project2, but the information wasn't saved. The static class was written in project1.
//object o = new object
//project1.staticObject = o
//project2.object = project1.staticObject
When I tried something like above, project2.object would be null. By adding a class as a link, is it creating a new instance of the static class in project2 or is it referencing the same class? If it is referencing the same class, shouldn't any information saved into the static class from project1 be accessible by project2? I know this isn't the most elegant manner of sharing data, but if anyone would help with this problem or provide a better manner of doing it, I would greatly appreciate it.
Thanks in advance.
Projects run in separate processes, so they can't share data in this manner. You'll need to persist the data in another type of store. I recommend using a database (hey, 20 gazillion websites, stock trading apps, airlines, etc can't be wrong).
If you don't want to use a database, you could open an IP connection between instances of the app and have a thread send packets of data to sync back and forth between the applications. Or, in your "server" app, add a web service that each process would call to update and retrieve information.
If you need really high-speed communication between the processes, sockets with a peer or star topology is a good way to go. If you're okay with some latency, having a web service (which works fine even if these aren't web apps) or a database could be a good solution. The right approach depends on your application.
WCF could also solve this problem. It effectively wraps the IP/socket layer and provides some nice object persistence/remote control capabilities, but I find it overly complex for most applications.
To share a single instance of an object among different processes (that's what I think you are intending to do) you need something that will maintain that object's state. You can look at the WCF and how to set up it's behaviour to act as a singleton so essentially every requester gets the same instance across the board.
http://msdn.microsoft.com/en-us/magazine/cc163590.aspx
Creating the link creates only applies to the source code. When you compile each project, it then has that single class definition available in both projects. The process you took does nothing for instances during runtime for sharing.
You can look at WCF or .NET Remoting, although .NET Remoting is now officially replaced by WCF.
If you are talking about sharing the same object between two processes, you can do that, the concept is called memory-mapped files. Here is some starter docs from msdn.
Though the docs and API use the term "FileMapping" quite a bit, you can use it just for sharing memory between two processes.
In .NET 4.0, you can use the System.IO.MemoryMappedFiles namespace. For your case, looks like .NET 3.5, you'll have to use some sort of interop to use the Win API.