How to get car vin info using Car API? - android-automotive

Im currently develop automotive application using car sdk. But cant get vin info from CarPropertyManager. So please give example to get car vi info using Car API

Create a Car object example mCar and call mCar = Car.createCar(this); when the application is loading.
Create a CarPropertyManager object example mCarPropertyManager and instantiate it by writing mCarPropertyManager = car.getCarManager(Car.PROPERTY_SERVICE);.
Create a listener for VIN information event as vinCarPropertyListener.
Register for any event. In your case, its Car VIN.
carPropertyManager.registerCallback(vinCarPropertyListener, VehiclePropertyIds.INFO_VIN)
In onEventChanged(), you will receive the VIN as CarPropertyValue.
override fun onChangeEvent(value: CarPropertyValue<Any>) {
Log.d(TAG, "Received on changed car property event")
// value.value type changes depending on the vehicle property.
Log.d(TAG, "VIN value: ${value.value}")
}
Reference link: CarPropertyExample

Related

Converting UserID to Member object [DISCORD4J]

I currently code a Discord bot in Java with Discord4j. Now, I want to get the mentioned user IDs (already did that) and convert them into Member object, but I don't know how to do it.
That's my code currently:
public static void run(MessageCreateEvent event) {
if(event.getMessage().getUserMentionIds().toString() == "[]") {
Utils.sendMessageToChannel("ERROR: No User got mentioned.", event);
}
Snowflake userMentions = Snowflake.of(event.getMessage().getUserMentionIds().toString());
Member member = new Member(userMentions);
}
Discord4J does not allow the use of constructors on its entities and most objects. This is because all of the entities are built up from data from the cache and/or a rest request to discord.
To get a Member from a user ID you would do the following:
GatewayDiscordClient#getMemberById(guildId, userId).block();
If you just want the user, as Member requires the person be in the guild:
GatwayDiscordClient#getUserById(userId).block();
You can also do this reactively by (flat)mapping the Mono(s).

Bing Maps MVVM in universal app

For a long time i´ve been trying to understand the correct way of dealing with bing Maps in n MVVM scenario.
I might create a map in my XAML-view like this:
<map:Map x:Name="MyMap"
Credentials="MySuperSecretCredentials"/>
I the code behind file I can easily interact with map for eaxmple like this:
private async void FindMe_Clicked()
{
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get the location.
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
MyMap.SetView(new BasicGeoposition() { Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude }, 15);
}
Simply by referencing the MyMap we can do whatever we like with it in the code behind.
But how can I execute the same command my viewModel?
I guess I should start with replacing the FindMe_Clicked with a command calling a method on my viewModel? And have that method execute a method similar to the one in the code-behind. But How do I acess MyMap in the viewModel?
Maybe my VM looks like this:
public class MainViewModel
{
public RelayCommand GetLocation { get; private set; }
public MainViewModel()
{
this.GetLocation = new RelayCommand(this.FindMe());
}
public void FindMe()
{
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get the location.
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
MyMap.SetView(new BasicGeoposition() { Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude }, 15);
}
}
If im not thinking about this problem all wrong what I need to do Is to pass the same instance of MyMap that exists in the view to my viewmodel somehow?
Help with this is appreciated, I would also love to see any examples of how to use bibg maps i portable class libraries or i an Mvvm-pattern if anyone has come across it somewhere. Thanks!
When following the MVVM pattern, you should never try to access elements of the View layer (e.g. the maps control) from within the Viewmodel. Instead, you'd (theoretically) create two public properties CenterLatitude and CenterLongitude and bind them to the maps control directly within XAML code:
<Map Credentials="MySuperSecretCredentials" ZoomLevel="15">
<Map.Center>
<Location Latitude="{Binding CenterLatitude}" Longitude="{Binding CenterLongitude}"/>
</Map.Center>
</Map>
It's ok to have a method FindMe within your Viewmodel, but instead of accessing the MyMapcontrol and calling SetView(...) from within there, you'd just update the two properties CenterLatitude and CenterLongitude and make sure that the PropertyChanged event is raised in order to inform the View about the changed data and to update itself.
BUT: Unfortunately, the bing map control's Center attribute does not support Data Binding - it seems that Microsoft turned this feature off intentionally for performance reasons. If you still want to keep the MVVM pattern, check out this article I've written some time ago that explains how to circumvent this restiction.
(In my experience, this workaround works quite well and does not affect performance. Just make sure that you don't update the Center property too often, meaning several times per second...)

How to implement 'Private Chat' module using akka, scala, websockets in play framework?

I have to implement a Chat module to enable privacy chatting b/w users. I have to do this in Play framework using Scala, Akka and java.net.*
I had got several examples over the net which are demonstrating the use of WebSockets but I didn't got any which can help me implementing Chat module using WebSockets. I have the idea of what i have to do but i am totally confused about what should be the structure of the objects, classes and how Should I start.
Please, if anyone can help me for this or refer me a good article, paper which can help me all the way through the implementation. Thankyou.
I did it in Java. This is what I modified from the exemple :
public class ChatRoom extends UntypedActor {
//Added hashmap to keep references to actors (rooms).
// (might be put in another class)
public static HashMap<String,ActorRef> openedChats=new HashMap<String,ActorRef>();
//Added unique identifier to know which room join
final String chatId;
public ChatRoom(String chatId) {
this.chatId = chatId;
}
public static void join(final User user, final String chatId , WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) throws Exception{
final ActorRef chatRoom;
//Find the good room to bind to in the hashmap
if(openedChats.containsKey(chatId)){
chatRoom = openedChats.get(chatId);
//Or create it and add it to the hashmap
}else{
chatRoom = Akka.system().actorOf(new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
return new ChatRoom(chatId);
}
})
);
openedChats.put(chatId,chatRoom);
}
// Send the Join message to the room
String result = (String)Await.result(ask(chatRoom,new Join(user.getId()+"", out), 10000), Duration.create(10, SECONDS));
// ..... Nothing to do in the rest
It's only the main modifications, you also have to adapt javascript and route file
Feel free to ask questions.
Have a look at the official sample in playframework
https://github.com/playframework/playframework/tree/master/samples/scala/websocket-chat

How to get outArgument WorkflowApplication when wf wait for response(bookmark OR idle) and not complete

Accessing Out Arguments with WorkflowApplication when wf wait for response(bookmark OR idle) and not complete
I also used Tracking to retrieve the values, but instead of saving it to a database I come up with the following solution.
Make a Trackingparticipant and collect the data from an activity.
You can fine tune the tracking participant profile with a spefic tracking query.
I have added a public property Output to set the value of the data from the record.
public class CustomTrackingParticipant : TrackingParticipant
{
//TODO: Fine tune the profile with the correct query.
public IDictionary<String, object> Outputs { get; set; }
protected override void Track(TrackingRecord record, TimeSpan timeout)
{
if (record != null)
{
if (record is CustomTrackingRecord)
{
var customTrackingRecord = record as CustomTrackingRecord;
Outputs = customTrackingRecord.Data;
}
}
}
}
In your custom activity you can set the values you want to expose for tracking with a CustomTrackingRecord.
Here is a sample to give you an idea.
protected override void Execute(NativeActivityContext context)
{
var customRecord = new CustomTrackingRecord("QuestionActivityRecord");
customRecord.Data.Add("Question", Question.Get(context));
customRecord.Data.Add("Answers", Answers.Get(context).ToList());
context.Track(customRecord);
//This will create a bookmark with the display name and the workflow will go idle.
context.CreateBookmark(DisplayName, Callback, BookmarkOptions.None);
}
On the WorklfowApplication instance you can add the Tracking participant to the extensions.
workflowApplication.Extensions.Add(new CustomTrackingParticipant());
On the persistable idle event from the workflowApplication instance I subscribed with the following method.
In the method I get the tracking participant from the extensions.
Because we have set the outputs in the public property we can access them and set them in a member outside the workflow. See the following example.
private PersistableIdleAction PersistableIdle(WorkflowApplicationIdleEventArgs
workflowApplicationIdleEventArgs)
{
var ex = workflowApplicationIdleEventArgs.GetInstanceExtensions<CustomTrackingParticipant>();
Outputs = ex.First().Outputs;
return PersistableIdleAction.Unload;
}
I hope this example helped.
Even simpler: Use another workflow activity to store the value you are looking for somewhere (database, file, ...) before starting to wait for a response!
You could use Tracking.
required steps would be:
define a tracking profile which queries ActivityStates with the state closed
Implement an TrackingParticipant to save the OutArgument in process memory, a database or a file on disk
hook everything together
The link cotains all the information you will need to do this.

Resolving dependency based on custom criteria

My app relies on multiple event bus objects which are basic publish/subscribe notification model (http://caliburn.codeplex.com/wikipage?title=The%20Event%20Aggregator).
What I want to do is share certain an instance of aggregators with a groups of components. Say component I have a single event bus that's shared between component A, B, and C, and then another event bus that's shared between D,E,F.
I essentially want to declare the event busses as singleton and inject them based on some criteria. I kinda wanna avoid subtyping the event busses just for the purposes of distinguishing resolution.
I've used Google Guice IoC in java which allows metadata resolution for a parameter. Aka in java it allowed me to something equivalent to this.
Example:
public A([SpecialUseAggregator]IEventAggregator something)
public B([SpecialUseAggregator]IEventAggregator something)
public E([AnotherUseAggregator]IEventAggregator something)
public F([AnotherUseAggregator]IEventAggregator something)
Any suggestions?
Autofac does not have/use attributes for the registration. One solution is to use the Named/Keyed registration feature.
So you need to need to register you two EventAggreator with different names/keys and when registering your consumer types A,B, etc you can use the WithParameter to tell Autofac which IEventAggreator it should use for the given instance:
var contianerBuilder = new ContainerBuilder();
contianerBuilder.Register(c => CreateAndConfigureSpecialEventAggregator())
.Named<IEventAggreator>("SpecialUseAggregator");
contianerBuilder.Register(c => CreateAndConfigureAnotherUseAggregator())
.Named<IEventAggreator>("AnotherUseAggregator");
contianerBuilder.RegisterType<A>).AsSelf()
.WithParameter(ResolvedParameter
.ForNamed<IEventAggreator>("SpecialUseAggregator"));
contianerBuilder.RegisterType<B>().AsSelf()
.WithParameter(ResolvedParameter
.ForNamed<IEventAggreator>("SpecialUseAggregator"));
contianerBuilder.RegisterType<C>).AsSelf()
.WithParameter(ResolvedParameter
.ForNamed<IEventAggreator>("AnotherUseAggregator"));
contianerBuilder.RegisterType<D>().AsSelf()
.WithParameter(ResolvedParameter
.ForNamed<IEventAggreator>("AnotherUseAggregator"));
var container = contianerBuilder.Build();
I you still would like to use attributes then you can do it with Autofac because it has all the required extension points it just requires some more code to teach Autofac about your attribute and use it correctly.
If you are registering your types with scanning you cannot use the easily use the WithParameter registration however you use the Metadata facility in Autofac:
Just create an attribute which will hold your EventAggreator key:
public class EventAggrAttribute : Attribute
{
public string Key { get; set; }
public EventAggrAttribute(string key)
{
Key = key;
}
}
And attribute your classes:
[EventAggrAttribute("SpecialUseAggregator")]
public class AViewModel
{
public AViewModel(IEventAggreator eventAggreator)
{
}
}
Then when you do the scanning you need to use the WithMetadataFrom to register the metadata:
contianerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.EndsWith("ViewModel"))
.OnPreparing(Method)
.WithMetadataFrom<EventAggrAttribute>();
And finally you need the OnPreparing event where you do the metadata based resolution:
private void Method(PreparingEventArgs obj)
{
// Metadata["Key"] is coming from the EventAggrAttribute.Key
var key = obj.Component.Metadata["Key"].ToString();
ResolvedParameter resolvedParameter =
ResolvedParameter.ForNamed<IEventAggreator>();
obj.Parameters = new List<Parameter>() { resolvedParameter};
}
Here is gist of a working unit test.