I've multiple SMS gateways and I want to send SMS though any one vendor who is having high success ratio and less in cost. I've the data ready with me of cost and success ratio.
Which design pattern will best suit to switch between SMS gateway on runtime to keep my SMS wrapper up 100% and cost effective.
'Best' often turns out very relative but if you want to switch between the senders at runtime you could use the factory/resolver/provider:
public interface ISMSSenderProvider/Resolver/Factory
{
ISMSSender GetSender()
}
Inside GetSender you can do whatever is necessary to figure out which sender to return - you could ask a db*, ask an api*, check a setting, etc.
* - probably cached
Related
What is the difference? As I understood the Tell (object, IActorRef) sends original sender. But why not to use just the Forward method?
Thank you
You can think of actorRef.Tell(msg) as a shortcut for actorRef.Tell(msg, Context.Self), while actorRef.Forward(msg) keeps original message Sender. This also mean, that you need an active actor context in the background to have any meaningful Sender defined.
Using Tell(object, IActorRef) allows you to set Sender to any actor ref you like, including things like impersonation as another actor or ActorRefs.NoSender, which may be used i.e. to reduce size of a payload send over the wire, as the message sender won't be serialized.
In some of remote scenarios, if you don't expect to send an answer to a Sender, using actorRef.Tell(msg, ActorRefs.NoSender) may bring nice performance benefit.
Why? IActorRef is serialized as URI string (example: akka.tcp://system-name#localhost:9001/user/parent/child). When you're sending small messages i.e. stock price ticks or a game character position changes, this may mean that the most expensive part of your payload is actually a Sender.
Deserializing IActorRef also takes some extra time, because actor provider needs to resolve correct message transport for it.
For those reasons, if you don't need the Sender, using ActorRefs.NoSender may be a valid option.
I wish to send packets to sync properties of constantly changing game objects in a game. I've sent notifications of when a property changes on the server side to a EntitySync object that is in charge of sending out updates for the client to consume.
Right now, I'm pre-fixing the property string name. This is a lot of overhead for when you're sending a lot of updates (position, HP, angle). I'd like for a semi-unique way to idneity these packets.
I thought about attributes (reflection... slow?), using a suffix on the end and sending that as an ID (Position_A, HP_A) but I'm at a loss of a clean way to identify these properties quickly with a low foot print. It should consume as few bytes as possible.
Ideas?
Expanding on Charlie's explanation,
The protobuf-net library made by Marc Gravell is exactly what you are looking for in terms of serialization. To clarify, this is Marc Gravell's library, not Googles. It uses Google's protocol buffer encoding. It is one of the smallest footprint serializes out there, in fact it will likely generate smaller packets than you manually serializing it will ( How default Unity3D handles networking, yuck ).
As for speed, Marc uses some very clever trickery (Namely HyperDescriptors) http://www.codeproject.com/Articles/18450/HyperDescriptor-Accelerated-dynamic-property-acces
to all but remove the overhead of run time reflection.
Food for thought on the network abstraction; take a look at Rx http://msdn.microsoft.com/en-us/data/gg577609.aspx Event streams are the most elegant way I have dealt with networking and multithreaded intra-subsystem communication to date:
// Sending an object:
m_eventStream.Push(objectInstance);
// 'handling' an object when it arrives:
m_eventStream.Of(typeof(MyClass))
.Subscribe ( obj =>
{
MyClass thisInstance = (MyClass) obj;
// Code here will be run when a packet arrives and is deserialized
});
It sounds like you're trying to serialize your objects for sending over a network. I agree it's not efficient to send the full property name over the wire; this consumes way more bytes than you need.
Why not use a really fantastic library that Google invented just for this purpose.
This is the .NET port: http://code.google.com/p/protobuf-net/
In a nutshell, you define the messages you want to send such that each property has a unique id to make sending the properties more efficient:
SomeProperty = 12345
Then it just sends the id of the property and its value. It also optimizes the way it sends the values, so it might use only 1, 2, 3 bytes etc depending on how large the value is. Very clever, really.
I'm building the mail module for a line-of-business application. The situation is that when sending the mails in response to some input, they should be grouped so a user doesn't receive several consecutive mails with different items but just one with all items included. Also, mails should be grouped by a specific type, that depends on the type of input that created the mail notification, I have the list of inputs, and each one with its specific grouping type, for instance:
Hierarchy: Employee has Processes has Requests has Activities
Activity 1: By Employee (so a receiver will get all notifications of the processes he owns of this activity type in just one mail)
Activity 2: By Process (a receiver will get a group of all notifications of all requests on this process, and this activity type)
Activity 3: By Request (activities of this request will be grouped)
Activity 4: By Activity (each activity will be sent in a separate mail)
This groupings will change constantly.
You may think, well in order to do that inputs should be made at once so mails are generated at the same time and so grouped, otherwise how the system will know when to wait for other inputs and when to just send a separate mail?.. well the answer is both, so what I'm doing is setting a timer so the mail service runs every 5 minutes, some immediate mails might get delayed a few minutes, but that's an affordable trade off.
So I chose to use this Chain of Responsability Design Pattern and here's the structure:
So I have two interfaces IGroupingType which defines how each type should be, and has 2 methods: CalculateGrouping(): determines if this is the grouping of the activity. GroupEmailsToSend(): if this is the grouping, gets the mails list.
Interface IGroupingHandler is the service class that will call each grouping type, the GetGroupingResult() just calls the 2 methods on the IGroupingType concrete implemetations, first CalculateGrouping() to get the correct grouping, when it finds it, calls the GroupEmailsToSend(). This interface also registers the next node in the chain for each grouping.
The grouping Enum is just for returning the result of grouping calculations.
And then there's also the EndOfChainSendingGrouping class, in case no grouping was found I'll just send the mail right away.
Basicaly I just need some advice on this structure, since I'm kind of new to this pattern, does it have any pitfalls? is there something I can improve? or is there a better way to accomplish this?
Thanks in advance..
I think chaining sounds good and seems to be the best fitting here. Eventually the Decorator pattern could be used for filtering the receiver lists.
Whenever i feel hungry i will publish i am hungry.This will be notified to the service providers say (MealsService,FruitService,JuiceService ).(These service providers know what to serve).
But the serving priority is the concern. Priority here means my first choice is MealsService when there are enough meal is available my need is end with MealsService.To verify the enough meal is availabe the MealsService raises the event "updateMeTheStockStatus" to the "MealsServiceStockUpdateListener" .
The "MealsServiceStockUpdateListener" will only reply back to "MealsService" . No other Service providers ( FruitService,JuiceService ) will be notified by the "MealsServiceStockUpdateListener" .If there is no sufficient stock then only the MealsService passes notification to the JuiceService (as it is the second priority).As usual it checks the stock.If stock is not sufficient it passes message to FruitService,so the flow continues like this.
How can i technically implement this?
Any implemention like priority based delagates and delegate chaining make sense ?
(Somebody! Please reframe it for good readability ).
Update : In this model there is no direct communication between "StackUpdateListener" and "me".Only The "Service Providers" will communicate me.
Like other answerers, I'm not entirely convinced that an event is the way forward, but let's go along with it for the moment.
It seems to me that the business with the MealsServiceStockUpdateListener is a red herring really - you're just trying to execute some event handlers but not others. This sort of thing crops up elsewhere when you have a "BeforeXXX" event which allows cancellation, or perhaps some sort of exception handling event.
Basically you need to get at each of your handlers separately. There are two different ways of doing that - either you can use a normal multicast delegate and call GetInvocationList() or you can change your event declaration to explicitly keep a list of handlers:
private List<EventHandler> handlers = new List<EventHandler>();
public event EventHandler MealRequired
{
add { handlers.Add(value); }
remove
{
int index = handlers.LastIndexOf(value);
if (index != -1)
{
handlers.RemoveAt(index);
}
}
}
These two approaches are not quite equivalent - if you subscribe with a delegate instance which is already a compound delegate, GetInvocationList will flatten it but the List approach won't. I'd probably go with GetInvocationList myself.
Now, the second issue is how to detect when the meal has provided. Again, there are two approaches. The first is to use the normal event handler pattern, making the EventArgs subclass in question mutable. This is the approach that HandledEventArgs takes. The second is to break the normal event pattern, and use a delegate that returns a value which can be used to indicate success or failure (and possibly other information). This is the approach that ResolveEventHandler takes. Either way, you execute the delegates in turn until one of them satistfies your requirements. Here's a short example (not using events per se, but using a compound delegate):
using System;
public class Test
{
static void Main(string[] args)
{
Func<bool> x = FirstProvider;
x += SecondProvider;
x += ThirdProvider;
Execute(x);
}
static void Execute(Func<bool> providers)
{
foreach (Func<bool> provider in providers.GetInvocationList())
{
if (provider())
{
Console.WriteLine("Done!");
return;
}
}
Console.WriteLine("No provider succeeded");
}
static bool FirstProvider()
{
Console.WriteLine("First provider returning false");
return false;
}
static bool SecondProvider()
{
Console.WriteLine("Second provider returning true");
return true;
}
static bool ThirdProvider()
{
Console.WriteLine("Third provider returning false");
return false;
}
}
Rather than publish a message "I'm hungry" to the providers, publish "I need to know current stock available". Then listen until you have enough information to make a request to the correct food service for what you need. This way the logic of what-makes-me-full is not spread amongst the food services... It seems cleaner to me.
Message passing isn't baked into .NET directly, you need to implement your own message forwarding by hand. Fortunately, the "chain of responsiblity design pattern" is designed specifically for the problem you're trying to solve, namely forwarding a message down a chain until someone can handle it.
Useful resources:
Chain of Responsibility on Wikipedia
C# implementation on DoFactory.com
I'm not sure if you really need a priority event. Anyways, let's suppose we want to code that just for fun.
The .NET Framework has no support for such a peculiar construct. Let me show one possible approach to implement it.
The first step would be to create custom store for event delegates (like described here);
Internally, the custom event store could work like a priority queue;
The specific EventArgs used would be HandledEventArgs (or a subclass of it). This would allow the event provider to stop calling handlers after one of them sets the event as Handled;
The next step is the hardest. How to say to tell the event provider what is the priority of the event handler that is being added?
Let me clarify the problem. Usually, the adding of a handler is like this:
eater.GotHungry += mealsService.Someone_GotHungry;
eater.GotHungry += juiceService.Someone_GotHungry;
eater.GotHungry += fruitService.Someone_GotHungry;
The += operator will only receive an delegate. It's not possible to pass a second priority parameter. There might be several possible solutions for this problem. One would be to define the priority in a custom attribute set at the event handler method. A scond approach is discussed in the question.
Compared to the chain of responsibility implementation at dofactory.com, this approach has some advantages. First, the handlers (your food services) do not need to know each other. Also, handlers can be added and remove at any time dynamically. Of course, you could implement a variation of a chain of responsibility that has this advantages too.
I don't think delegates are the proper solution to your problem. Delegates are a low-level service provided by C# for relatively tightly coupled events between components. If I understand your question properly (It is worded a little oddly, so I am not sure I clearly understand your problem), then I think what you need is a mediated consumer/provider.
Rather than having your consumers directly consume the meal, juice, and fruit providers, have them request a food item from a central mediator. The mediator would then be responsible for determining what is available and what should be provided to the consumer. The mediator would be a subscriber to events published by all three services. Whenever stock is added/updated in the Meal, Juice, or Fruit services, they would publish their current stock to all subscribers. The mediator, being a subscriber, would track current stock reductions on its own, and be able to determine for itself whether to send a meal, juice, or fruit to a food consumer when a get food request is made.
For example:
|---------- (GetFoodResponse) ----------------
V |
FoodConsumer ---- (GetFoodRequest) ------> FoodProvider <-----> [ Local Stock Data ]
^
|
|
MealService ---- (PublishStockMessage) ----------|
^
JuiceService --- (PublishStockMessage) ----------|
^
FruitService --- (PublishStockMessage) ----------|
The benefits of such a solution are that you reduce coupling, properly segregate responsibility, and solve your problem. For one, your consumers only need to consume a single service...the FoodProvider. The FoodProvider subscribes to publications from the other three services, and is responsible for determining what food to provide to a consumer. The three food services are not responsible for anything related to the hunger of your food consumers, they are only responsible for providing food and tracking the stock of the food they provide. You also gain the ability to distribute the various components. Your consumers, the food provider, and each of the three food services can all be hosted on different physical machines if required.
However, to achieve the above benefits, your solution becomes more complex. You have more parts, and they need to be connected to each other properly. You have to publish and subscribe to messages, which requires some kind of supporting infrastructure (WCF, MSMQ, some third party ESB, custom solution, etc.) You also have duplication of data, since the food provider tracks stock on its own in addition to each of the food services, which could lead to discontinuity in available stock. This can be mitigated if you manage stock updated properly, but that would also increase complexity.
If you can handle the additional complexity, ultimately, a solution like this would more flexible and adaptable than a more tightly connected solution that uses components and C# events in a local-deployment-only scenario (as in your original example.)
I am having a bit of trouble understanding your analogy here, which sounds like you're obscuring the actual intent of the software, but I think I have done something like what you are describing.
In my case the software was telemarketing software and each of the telemarketers had a calling queue. When that queue raises the event signifying that it is nearing empty, the program will grab a list of available people to call, and then pass them through a chain of responsibility which pushes the available call into the telemarketer's queue like so:
Each element in the chain acts as a priority filter: the first link in the chain will grab all of the people who have never been called before, and if it finishes (ie. went through all of the people who have never been called) without filling up the queue, it will pass the remaining list of people to call to the next link in the chain - which will apply another filter/search. This continues until the last link in the chain which just fires off an e-mail to an administrator indicating that there are no available people to be called and a human needs to intervene quickly before the telemarketers have no work to do.
I have a winforms app and i want to keep track of every time a user clicks certain buttons, etc as well as other actions. What is the best way for me to keep track of this information and then put it together so i can run metrics on most used features, etc.
This is a winforms app and I have users around the world.
There are 2 big issues your design has to be sure to address
Privacy (what Don alluded to) - You must be crystal clear what information you are collecting and sending up to your central server, ideally the users should be able to inspect the exact data you are sending back to the central server (if they wish to) - For any public software there should be a very easy way to opt out.
Performance and Scalability - You have to estimate how much data you really need on the server side and look at all sort of tricks that aggregate and compress the data client side (as well as have hard limits on the amount of traffic you will be sending and how often you will be sending it)
As to the client side implementation, I would recommend investigating Sqlite.net or another embedded DB. Using an embedded DB to store this information on the client will give you lots of flexibility with aggregations and will have the advantage of being transactional, fast and simple to implement. Sqlite has a very generous public domain license so from a legal perspective its really easy to use in public apps.
Try doing a google scholar search. There are some interesting ideas by Ben Liblit and co-authors, and another series of ideas by Alex Orso and co-authors (disclaimer - I'm one of Alex Orso's co-authors) based on taking a sample of runtime information from each user, and putting it together in an interesting way.
http://theory.stanford.edu/~aiken/publications/papers/pldi03b.pdf
and
http://www.cs.umd.edu/class/fall2006/cmsc838p/Ramss/remoteClassJournal.pdf
are two (not necessarily the best) examples of such papers/ideas.
I'd try something like this:
// execute this method once all forms have been created
public static void HookButtons()
{
foreach( Form f in Application.OpenForms )
{
EnumerateControls( f.Controls );
}
}
public static void EnumerateControls( ICollection controls )
{
foreach( Control ctrl in controls )
{
if( ctrl.Controls.Count > 0 )
{
EnumerateControls( ctrl.Controls );
}
if( ctrl is ButtonBase )
{
ctrl.MouseClick +=new MouseEventHandler( ctrl_MouseClick );
}
}
}
static void ctrl_MouseClick( object sender, MouseEventArgs e )
{
ButtonBase clicked = ((ButtonBase)sender);
// do something with the click information here
}
Be careful how you handle this. Some companies have gotten user backlash from collecting too much information or not being clear what was collected. The safest way is to ask the user before enabling any "phone home" features. Allowing the user to see the actual data before you send it seems good, too.
I've wondered if there's some way to piggyback on the one-click deployment call that happens whenever a one-click app starts up and checks for updates. I haven't investigated yet, though.
As for collecting the actual numbers, perhaps the user settings are the easiest place. If you're not familiar with them, just check out the project properties and go to the Settings tab.