How to get property in iPOJO - ipojo

I have a simple component as follows:
#Component (name="Test")
#Instantiate
public class Test {
#Property(name="foo", value="my-instance-2")
String buffer = "abcbuffer";
public Test() {
System.out.println("test running");
}
}
i use the "instance iTest" i have the result
g! instance iTest
instance name="iTest" state="valid" bundle="31" component.type="Test"
handler name="org.apache.felix.ipojo:properties" state="valid"
property name="foo" value="abcbuffer"
handler name="org.apache.felix.ipojo:callback" state="valid"
handler name="org.apache.felix.ipojo:architecture" state="valid"
object name="test.Test#637a91a"
How to i get "buffer" property via "introspection" from another component? i want to get the "abcbuffer" value.
Thanks,

And to update dynamically the buffer value, we use:
ComponentInstance ci = (ComponentInstance) factory.getInstances().get(0);
Properties props = new Properties();
String newbuffer = new String("newValue");
props.put("buffer", newbuffer);
ci.reconfigure(props);

In order to respond this question, i do as follows:
for (Factory factory : factories) {
if (factory.getName().equals("Test")) { //Test is default name of a component name
InstanceManager im = (InstanceManager) factory.getInstances().get(0);
String buffer = (Strig) im.getFieldValue("buffer");
System.out.println(buffer);
}
}

All iPOJO component are wrapped with an architecture handler.
You can track this architecture handler,through the Architecture service, and use it to introspect the component. It is currently what the instance command do if I remember.

Related

Create Contactor with paramater for ExternalAction

How I can create Contactor in code effect for ExternalAction ,
I have this code
[ExternalAction(typeof(Service), "SendEmail")]
And I want send email when success Evaluate but without write send code in SendEmail, I want use call interface to send it , like this
private readonly IEmailService email;
public Service(IEmailService emailService)
{
email = emailService;
}
[Action("Send Email", "Send Email to Someone")]
public void SendEmail(Rule Rule, [Parameter(ValueInputType.User, Description = "Output message", DataSourceName = "UserList")] int userId)
{
email.sene(userId);
}
You are trying to use the instance action method. For the engine to be able to invoke such a method it needs to instantiate your type. Your Service class doesn't have an empty (parameterless/default) constructor. Obviously, the engine won't have an instance of your EmailService at evaluation time. Therefore, it can't invoke your instance method. Either add a default constructor to your Service class and find another way to pass EmailService to the Service class or use a static method with value type parameters.

CLSA AddChild Default values

I'm using CSLA latest release and trying to add a row with default items to the collection. What I've noticed is the default constructor of the Foo class is called instead of the AddNewCore in the FooList Class. I am unable to get the AddNewCore or the Child_Create methods to get invoked when a new row is added in a XamDataGrid row. (A row is added, but it is from the default constructor of the FooLine Class--i.e. no default values and no MarkAsChild attribute.) Here is the code snippet that is in the FooList class:
protected override FooItem AddNewCore()
{
var item = DataPortal.CreateChild<FooItem>();
MarkAsChild();
Add(item);
return base.AddNewCore();
}
protected override void Child_Create()
{
var item = DataPortal.CreateChild<FooItem>();
MarkAsChild();
Add(item);
base.Child_Create();
}
What am I doing wrong?
AddNewCore() method exists in client side CSLA class 'ExtendedBindingList' with 'void' return type and same method is exists in server side class 'ObservableBindingList' with return type 'ListClass'. So we required to call run time client side method from server side.
Please refer below code for the same.
#if SILVERLIGHT
protected override void AddNewCore()
{
var item = DataPortal.CreateChild<FooItem>();
Add(item);
}
#endif
For information: The reason the above code does not work has to do with the way WPF invokes the New method. Typically, in other frameworks it is possible to hook on to that event, intercept it, and return with default data. With WPF, it is necessary to check the RecordAdding, or RecordAdded trigger events and process the invocations by hand.
In my case, the WPF would look like:
<i:Interaction.Triggers>'
i:EventTrigger EventName="RecordAdded">
<ei:CallMethodAction TargetObject="{Binding}"
MethodName="CreateDefaultAddressValuesCommand" />
</i:EventTrigger>
In the view model:
var idx = FooInformation.FooAddressList.Count - 1;
var address = await FooAddress.CreateAsync();
FooListing.FooAddressList[idx] = address;

Entity Framework execute stored procedure with params

Ok, hope to not get too many flags, but it's to annoying.
I have a method in my controller which calls a method from another class:
offerForCreate.Rating = CalculateRating.CreateRating(addOffer);
and entire called class :
public class CalculateRating
{
private readonly DataContext mainContext;
public CalculateRating(DataContext mainContext)
{
this.mainContext = mainContext;
}
// calcul rating oferte noi
public decimal CreateRating(OfferForCreate offer)
{
decimal rating = mainContext.Database.FromSql<decimal>("RatingCalculator", offer.locationId, offer.typeId);
return rating;
}
}
I get an error when try to execute this procedure:
Error CS1061: 'DatabaseFacade' does not contain a definition for 'FromSql' and no extension method 'FromSql' accepting a first argument of type 'DatabaseFacade' could be found
and another if I don't create an instance of CalculateRating class in my controller :
Controllers\AnnouncesController.cs(127,37): error CS0120: An object reference is required for the non-static field, method, or property 'CalculateRating.CreateRating(OfferForCreate)
Everywhere I see must specify the entity, but what entity I can specify if my stored procedure use multiple tables?
Asp.Net Core Web API
You can execute stored proc like this:
using (var command = mainContext.Database.GetDbConnection().CreateCommand())
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "dbo.RatingCalculator";
var locationIdParam = new System.Data.SqlClient.SqlParameter("#locationId", System.Data.SqlDbType.Int);
locationIdParam .Value = offer.locationId;
//DO same for typeId parameter
//Params to Parameters collection
command.Parameters.Add(locationIdParam);
command.Connection.Open();
return (double)command.ExecuteScalar();
}
Controllers\AnnouncesController.cs(127,37): error CS0120: An object reference is required for the non-static field, method, or property 'CalculateRating.CreateRating(OfferForCreate)
This error is occuring because if you declare CalculateRating as static you can not reference in non-static field mainContext.
You should create an instance of your CalculateRating class using Dependency Injection. Here are steps:
Create an interface ICalculateRating
public interface ICalculateRating {
decimal CreateRating(OfferForCreate offer);
}
Update CalculateRating class to implement ICalculateRating
Register the DBContext and ICalculateRating mappings in ConfigureServices method of Startup.cs file like this:
services.AddDbContext<DbContext>(opts=> { opts.UseSqlServer("sqlserver conntection string") }, ServiceLifetime.Scoped);
services.AddTransient<ICalculateRating, CalculateRating>();
In your controller constructor, input an argument of type ICalculateRating which will be injected by Microsoft Dependency Injection framework at runtime:
private readonly ICalculateRating _calculateRating;
public MyController(ICalculateRating calculateRating) {
_calculateRating = calculateRating;
}
You can then call the method like this:
offerForCreate.Rating = _calculateRating.CreateRating(addOffer);

vertx 2: vertx.eventBus().send(ClassName.ADDRESS, ....) why does it init a new class?

I work on a project based on Vertx the following line:
vertx.eventBus().send(MyClass.ADDRESS, requestBody, new Handler<Message<Object>>() {
....
}
public class MyClass implements Handler<Message<JsonObject>> {
public static final String ADDRESS = "coupons.api.manager";
...
#Override
public void handle(Message<JsonObject> msg) {
...
}
}
Whereas MyClass.ADDRESS is a static field of type string in the class MyClass, I found out that the line vertx.eventBus(...) creates an object of MyClass and then runs the handle() function.
My question is why? MyClass.ADDRESS is a string, and a static one. How does vertx "know" that it has to create an object from a class that this string is an attribute of?
I looked at the documentation of the send() function: http://vertx.io/docs/apidocs/io/vertx/core/eventbus/EventBus.html#send-java.lang.String-java.lang.Object-io.vertx.core.eventbus.DeliveryOptions-io.vertx.core.Handler-
and it says that the first argument in the function is "the address to send it to". OK. But, who said that the address means instantiating this class?
I made a small research, and yes. Vertx, behind the curtains, connects all the classes that implement Handler> to the string value they have in the attribute ClassName.ADDRESS.
When the statement:
vertx.eventBus().send(MyClass.ADDRESS, requestBody, new Handler<Message<Object>>() {
....
}
is invoked, a new thread is created and runs the handle method in the class MyClass.

AutoFac IRegistrationBuilder

I am new to Autofac and IOC concept. I have following code which I am not getting or understanding what it is doing.
`
public void AddComponentInstance<TService>(object instance, string key = "", ComponentLifeStyle lifeStyle = ComponentLifeStyle.Singleton)
{
AddComponentInstance(typeof(TService), instance, key, lifeStyle);
}
public void AddComponentInstance(Type service, object instance, string key = "",ComponentLifeStyle lifeStyle = ComponentLifeStyle.Singleton)
{
UpdateContainer(x =>
{
var registration = x.RegisterInstance(instance).Keyed(key, service).As(service).PerLifeStyle(lifeStyle);
});
}
public void UpdateContainer(Action<ContainerBuilder> action)
{
var builder = new ContainerBuilder();
action.Invoke(builder);
builder.Update(_container);
}
public static class ContainerManagerExtensions
{
public static Autofac.Builder.IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> PerLifeStyle<TLimit, TActivatorData, TRegistrationStyle>(this Autofac.Builder.IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> builder, ComponentLifeStyle lifeStyle)
{
switch (lifeStyle)
{
case ComponentLifeStyle.LifetimeScope:
return HttpContext.Current != null ? builder.InstancePerHttpRequest() : builder.InstancePerLifetimeScope();
case ComponentLifeStyle.Transient:
return builder.InstancePerDependency();
case ComponentLifeStyle.Singleton:
return builder.SingleInstance();
default:
return builder.SingleInstance();
}
}
}
`
From above code what I understood is that, We are registering the Singleton Instance in Container and we are updating the container. I searched online For IRegistrationBuilder interface example but I could not get any satisfying answer.
Can anyone please help me to understand the concept of IRegistrationBuilder.
I am referring this code from NopCommerce application.
Thanks in Advance.
IRegistrationBuilder is application of builder design pattern within autofac. Look at the line:
x.RegisterInstance(instance).Keyed(key, service).As(service).PerLifeStyle(lifeStyle);
this chain of methods defines registration of istance of certain object. Each of the methods used sets properties used for proper registration. Each of the methods returns builder object which implements IRegistrationBuilder - it holds all those properties. Because PerLifeStyle accepts as first parameter IRegistrationBuilder you can use it in chain above to change builder properties - in case of PerLifeStyle to affect instantiation of the object. Because PerLifeStyle returns IRegistrationBuilder you may use it in the middle of methods invokation chain like:
x.RegisterInstance(instance).PerLifeStyle(lifeStyle).Keyed(key, service).As(service)