Automatically detect when storing an object with ServiceStack.Redis - events

I am looking for a way to subscribe to events like Storing a specific object type to ServiceStack.Redis.
For example I may
using (var redisClient = new RedisClient())
using (var redisMyObjects = redisClient.As<MyObject>())
{
redisMyObjects.Store(myObject);//<-- I want this to trigger an event somehow
}
Is there anything like a OnStore event which I can hook too, anything out of the box? if not, is there any recommendation about how this should be done?

I don't think there is anything you can hook into (could be wrong).
Two options that came to mind:
1 - Make an extension method
2 - Publish a message to store your object and have a handler that listens for a response and does something. This is probably overkill since it's heading into the publish/subscribe realm. But, I think, worth looking into. (Basic example here and see Pub/Sub here).
Extension Method
public static class RedisClientExtensions
{
public static void StoreWithTrigger<T>(this IRedisTypedClient<T> redisClient, T value, Action<T> trigger)
{
redisClient.Store(value);
trigger(value);
}
}
Using ExtensionMethod
public void MyMethod()
{
using (var redisClient = new RedisClient())
using (var redisMyObjects = redisClient.As<MyObject>())
{
redisMyObjects.StoreWithTrigger<MyObject>(new MyObject(), TriggerEvent);//<-- I want this to trigger an event somehow
}
}
private void TriggerEvent<T>(T value)
{
//dosomething
}
Hope this gives you some ideas.

Related

How to use CXCallObserver in Xamarin?

I need to subscribe an event to handle incoming phone call. Since iOS version 11.0 CTCallCenter is deprecated we have to use CXCallObserver. I successfully implemented solution for CTCallCenter, but I am not able to subscribe event for CXCallObserver. Does anyone have working solution for CXCallObserver?
Here is my code to subscribe event for CTCallCenter..
_callCenter = new CTCallCenter();
_callCenter.CallEventHandler += CallEvent;
private void CallEvent(CTCall call)
{
CoreFoundation.DispatchQueue.MainQueue.DispatchSync(() =>
{
if(call.CallState.Equals(call.StateIncoming))
//Do something
});
}
Implement the delegate for CXCallObserver:
public class MyCXCallObserverDelegate : CXCallObserverDelegate
{
public override void CallChanged(CXCallObserver callObserver, CXCall call)
{
Console.WriteLine(call);
}
}
Then in your code, create a instance of CXCallObserver (maintain a strong reference to this) and then assign the delegate:
cXCallObserver = new CXCallObserver();
cXCallObserver.SetDelegate(new MyCXCallObserverDelegate(), null);

using signalR .net core client

I have set up a signalR website .net core. My function in my hub is:
public async Task Notify(int id) {
await Clients.All.InvokeAsync("Notified", id);
}
I have also tested this with the following js:
let connection = new signalR.HubConnection(myURL);
connection.on('Notified', data => {
console.log(4, data);
});
connection.start();
The js code seems to work fine and I see the log when I try connection.Invoke('Notify').
Now I have a console app that can needs to make the invoke. I am trying this in two ways and don't mind either solution:
1. A mvc controller within the signalR website that can take the id and invoke 'Notified'.
2. Use the client library Microsoft.AspNetCore.SignalR.Client in the console app.
The way 1 I have only done in classic asp.net like this:
GlobalHost.ConnectionManager.GetHubContext(hubName)
But couldn't find a way to do this in .net core.
Way 2 I have used the library and tried this so far:
var con = new HubConnectionBuilder();
con.WithUrl(myURL);
var connection = con.Build();
connection.InvokeAsync("Notify",args[0]).Wait();
This is the closest I have come to create a connection in the same way as the js code. However this code throws a null pointer when calling connection.InvokeAsync. The connection object is not null. It seems to be an internal object that is null. According to the stack trace the exception is thrown when a MoveNext() function is internally called.
Well looks like both are not currently possible. As of now I just used a forced way which is hopefully temporary.
I have created and used the following base class for hubs:
public abstract class MyHub : Hub
{
private static Dictionary<string, IHubClients> _clients = new Dictionary<string, IHubClients>();
public override Task OnConnectedAsync()
{
var c = base.OnConnectedAsync();
_clients.Remove(Name);
_clients.Add(Name, Clients);
return c;
}
public static IHubClients GetClients(string Name) {
return _clients.GetValueOrDefault(Name);
}
}
GlobalHost is gone. You need to inject IHubContext<THub> like in this sample.
This can be a bug in SignalR alpha1. Can you file an issue on https://github.com/aspnet/signalr and include a simplified repro?

How to pursuade the ApiExplorer to create documentation for ExpandoObject?

I've created a very neat way of implementing a PATCH method for my Web.API project by making use of an ExpandoObject as a parameter. As illustrated below:
[HttpPatch, Route("api/employee/{id:int}")]
public IHttpActionResult Update(int id, [FromBody] ExpandoObject employee)
{
var source = Repository.FindEmployeeById(id);
Patch(employee, source);
Repository.SaveEmployee(source);
return Ok(source);
}
However, when generating documentation ApiExplorer is at a loss as to what to do with the ExpandoObject, which is totally understandable. Would anyone have any ideas on how to manipulate the ApiExplorer to provide some sensible documentation?
My idea was to maybe introduce an new attribute which points to the actual Type that is expected:
public IHttpActionResult Update(int id, [FromBody, Mimics(typeof(Employee))] ExpandoObject employee)
{
...
}
But I have no idea where to start, any ideas or suggestions are welcome.
So this has been the source of some late evenings in order to get the Api Explorer to play along with our developed Http Patch mechanism. Truth be told, I'd probably should do a bit of a proper write up to full explain the mechanics behind the whole idea. But for those of you who landed on this page because you want the Api explorer to use a different type in the documentation, this is where you need to look:
Open HelpPageConfigurationExtensions.cs and locate the following method:
//File: Areas/HelpPage/HelpPageConfigurationExtensions.cs
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
....
}
this is the location where the parameter information is available to you and also provides you with the ability to replace/substitute parameter information with something else. I ended up doing the following to handle my ExpandoObject parameter issue:
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
// do something different when dealing with parameters
// of type ExpandObject.
if (parameterType == typeof(ExpandoObject))
{
// if a request-type-attribute is defined, assume the parameter
// is the supposed to mimic the type defined.
var requestTypeAttribute = apiParameter.ParameterDescriptor.GetCustomAttributes<RequestTypeAttribute>().FirstOrDefault();
if (requestTypeAttribute != null)
{
parameterType = requestTypeAttribute.RequestType;
}
}
}
Just, note that the RequestTypeAttribute is something I devised. My WebApi endpoint looks like this now:
public IHttpActionResult Update(int id,
[FromBody, RequestType(typeof(Employee))] ExpandoObject employee)
Thank you to everyone who took time to look into the problem.

use camel case serialization only for specific actions

I've used WebAPI for a while, and generally set it to use camel case json serialization, which is now rather common and well documented everywhere.
Recently however, working on a much larger project, I came across a more specific requirement: we need to use camel case json serialization, but because of backward compatibility issues with our client scripts, I only want it to happen for specific actions, to avoid breaking other parts of the (extremely large) website.
I figure one option is to have a custom content type, but that then requires client code to specify it.
Is there any other option?
Thanks!
Try this:
public class CamelCasingFilterAttribute : ActionFilterAttribute
{
private JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();
public CamelCasingFilterAttribute()
{
_camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
if (content != null)
{
if (content.Formatter is JsonMediaTypeFormatter)
{
actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, _camelCasingFormatter);
}
}
}
}
Apply this [CamelCasingFilter] attribute to any action you want to camel-case. It will take any JSON response you were about to send back and convert it to use camel casing for the property names instead.

javafx - how to disable events fired not from the user

i have a little problem with javafx. i added a change listener like this:
private final ChangeListener<String> pageItemSelected = new ChangeListener<String>()
{
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
pageGotSelected(newValue);
}
};
now to the problem: if i change an page item like this:
guiPageList.setValue(model.getCurrentTargetPage());
the event gets also(as it get by selecting something with the mouse or key) fired. is there a way to disable the event firing or another way?
i need the event only, if the element got selected by the user and not if i change it with the setValue() function...
perhaps consuming the event, but i donĀ“t know what kind of event this would be.
thanks in advance!!!
You can temporarily remove the listener and add it again:
guiPageList.getSelectionModel().selectedItemProperty().removeListener(pageItemSelected);
guiPageList.setValue(model.getCurrentTargetPage());
guiPageList.getSelectionModel().selectedItemProperty().addListener(pageItemSelected);
Alternatively you could decorate the listener with another listener implementation, the code would be something like:
class InvalidationListenerEventBlocker implements InvalidationListener {
InvalidationListener decoratedListener;
boolean block;
public void invalidated(Observable observable) {
if(!block) {
decoratedListener.invalidated(observable);
}
}
}
Add a setter for the block boolean and send the listener in through the constructor. Set block to true to stop events.
This is very old question, but I came to some solution I personally use, that's reusable and does not require storing a reference to the listener (but it needs a reference to the exposing/muffling property thou).
So first the concept: we're going to create lambda (InvalidationListener), that is going to be called only if above mentioned exposing/muffling property is set to true/false. For that we are going to define another functional interface that provides described behavior:
#FunctionalInterface
private interface ManageableInvalidationListener
extends InvalidationListener {
public static InvalidationListener exposing(
BooleanProperty expose,
ManageableInvalidationListener listener) {
return ob -> {
if (expose.get()) {
listener.invalidate(ob);
}
};
}
public static InvalidationListener muffling(
BooleanProperty muffle,
ManageableInvalidationListener listener) {
return ob -> {
if (!muffle.get()) {
listener.invalidated(ob);
}
}
}
public abstract void invalidated(Observable ob);
}
This interface defines two static methods we're going to use in our code. We pass a steering property as first argument (it will tell if listener should be called) and actual implementation to be performed, when it will be called. Please note, that there is no need to extend InvalidationListener, but I'd like to keep ManageableInvalidationListener in sync with InvalidationListener.
So we would call exposing if we need to create a (manageabale) listener that would notify the (invalidation) listener if expose property has value of true. In other case we would create the listener with muffling, if true of the steering property would mean, well, to muffle the notification.
How to use it?
//- Let's make life easier and import expose method statically
import static ManageableInvalidationListener.exposing;
// ...
//- This is the steering property.
BooleanProperty notify = new SimpleBooleanProperty(true);
//- This is our main property with the listener.
ObjectProperty<Foobar> foobar = new SimpleObjectProperty<>();
//- Let's say we are going to notify the listener, if the
// notify property is set to true.
foobar.addListener(exposing(notify, ob -> {
//- Here comes the InvalidListener code.
}));
And then somewhere in the code:
//- Listener will be notified as usual.
foobar.set(new Foobar());
//- Now temporarily disable notifications.
notify.set(false);
//- The listener will not get the notification this time.
foobar.set(new Foobar());
//- Re-enable notifications.
notify.set(true);
Hope this somehow helps. You're free to use the code in this post as pleases you.

Resources