I using the serialization library (https://pub.dartlang.org/packages/serialization) to persiste and recover complex objects.
An excellent library to convert complex objects (also converts to JSON!). Congratulations to Google people!
However, necessary to transform dart in js (dart2js) and I'm not succeeding in using MirrorUsed. I would like to reduce the code size!
When I use #MirrorUsed like following, serialization does not work more.
main_app.dart
#MirrorsUsed(targets: 'serialization.serialization_mirrors.Serialization', override: '*')
import 'dart:mirrors';
import 'package:serialization/serialization_mirrors.dart';
// [..other imports..]
#PolymerRegister('main-app')
class MainApp extends PolymerElement {
var serializationProdutos;
#property
List produtos = new List();
void ready() {
Produto p = new Produto()..descricao = "SUPER TESTE"..unidade = "Unitário";
Produto p2 = new Produto()..descricao = "SUPER TESTE 2"
..ehComposto = true
Map m = new Map()
..putIfAbsent("expandir", () => true)..putIfAbsent(
"produto", () => p);
Map mm = new Map()
..putIfAbsent("expandir", () => true)..putIfAbsent(
"produto", () => p2);
(mm['produto'] as Produto).componentes.add(new ProdutoComponente()..produtoComponente = p);
add('produtos', m);
add('produtos', mm);
}
#reflectable
salvarDados(Event e, [_]) {
serializationProdutos = new Serialization();
serializationProdutos.addRuleFor(Produto);
serializationProdutos.addRuleFor(ProdutoComponente);
var jsonProdutos = JSON.encode(serializationProdutos.write(produtos));
window.localStorage['precoMi_produtos'] = jsonProdutos;
}
#reflectable
carregarDados(Event e, [_]) {
var jsonProdutos = window.localStorage['precoMi_produtos'];
if (jsonProdutos != null) {
try {
serializationProdutos = new Serialization();
serializationProdutos.addRuleFor(Produto);
serializationProdutos.addRuleFor(ProdutoComponente);
List pro = serializationProdutos.read(JSON.decode(jsonProdutos));
addAll('produtos', pro);
} catch (e) {
window.console.log(
'Error local storage. ${e}');
}
}
Am I using #MirrorUsed correctly?
If you're using Polymer, then it's using the Reflectable package, which is much easier to optimize than MirrorsUsed, and I'm not even sure that the two will work nicely together. Really, the Serialization package needs to be updated to enable this.
As a short-term workaround, what I'd suggest is using non-mirrored serialization rules. You can write these by hand, which is more work for you in terms of maintenance, but if the number of classes is not too large, it's probably acceptable, and it should produce quite small code without any extra effort on your part. Or, if your classes are relatively simple (no complex constructors, ordering dependencies) you can use the serialization transformer to generate them. Unfortunately there's a bug where dartdocs is not showing the library comments, so you'd have to look at the comments on e.g. https://github.com/google/serialization.dart/blob/master/lib/transformer.dart and https://github.com/google/serialization.dart/blob/master/lib/serialization.dart
Related
We have a collection of Microsoft Windows Workflows (.xaml files) that I need to go through and inventory the variables. The workflows are complicated with variables scoped at many levels so I can't simply open up the Workflow xaml and look at the Variables tab at the top level; I need to dig through each level, sequence, etc. to find all possible variable definitions.
Can I automate this process? Can Visual Studio aid in this process?
One solution, I could write some code to read the workflow file, look for variables, grab any default values, and check if the variable is assigned, thus overriding the default. Technically, this is possible from C#. But is this solution really necessary to get the information?
You can use a recursive function like this:
List<Variable> Variables;
private void GetVariables(DynamicActivity act)
{
Variables = new List<Variable>();
InspectActivity(act);
}
private void InspectActivity(Activity root)
{
IEnumerator<Activity> activities = WorkflowInspectionServices.GetActivities(root).GetEnumerator();
while (activities.MoveNext())
{
PropertyInfo propVars = activities.Current.GetType().GetProperties().FirstOrDefault(p => p.Name == "Variables" && p.PropertyType == typeof(Collection<Variable>));
if (propVars != null)
{
try
{
Collection<Variable> variables = (Collection<Variable>)propVars.GetValue(activities.Current, null);
variables.ToList().ForEach(v =>
{
Variables.Add(v);
});
}
catch
{
}
}
InspectActivity(activities.Current);
}
}
And should be called like this:
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xamlData)))
{
XamlXmlReaderSettings readerSettings = new XamlXmlReaderSettings()
{
LocalAssembly = Assembly.GetExecutingAssembly()
};
var xamlReader = new XamlXmlReader(stream, readerSettings);
Activity activity = ActivityXamlServices.Load(xamlReader);
DynamicActivity root = activity as DynamicActivity;
GetVariables(root);
}
Credit to: https://stackoverflow.com/a/11429284/593609
My question is similar to question about DI for NserviceBus Handler for testing (Handler).
As a solution, you can use constructor injection by using the following syntax:
Test.Handler<YourMessageHandler>(bus => new YourMessageHandler(dep1, dep2))
I couldn't find a way to use the same approach for Saga testing.
There is a support for property injecting, which would look something like this:
var saga = Test.Saga<MySaga>()
.WithExternalDependencies(DependenciesSetUp);
private void DependenciesSetUp(MySaga saga)
{
saga.M2IntegrationService = M2IntegrationService.Object;
saga.ProcessLogService = ProcessLogService.Object;
saga.Log = Log.Object;
}
However, this approach requires making my dependencies public properties. And I want to try to avoid it.
Is there a way to use construction dependency injection for Saga testing?
You can work around this like:
Have a saga that has a constructor with parameters (in addition to a default empty constructor, which is required).
This is how your test can look like:
Test.Initialize();
var injected = new InjectedDependency() {Id = Guid.NewGuid(), SomeText = "Text"};
var testingSaga = new MySaga(injected);
var saga = Test.Saga(testingSaga);
saga.WhenReceivesMessageFrom("enter code here")
Will this work for you?
Yes it is also supported:
var saga = new MySaga(new MyFirstDep(), new MySecondDep());
Test.Saga(saga)
.ExpectSend<ProcessOrder>(m => m.Total == 500)
.ExpectTimeoutToBeSetIn<SubmitOrder>((state, span) => span == TimeSpan.FromDays(7))
.When(s => s.Handle(new SubmitOrder
{
Total = 500
}));
I am developing a game where I'd like to have multiple scripts that all implement the same structure. Each script would need to be run in its own scope so that code doesn't overlap other scripts. For example:
structure.js
function OnInit() {
// Define resources to load, collision vars, etc.
}
function OnLoop() {
// Every loop
}
function ClickEvent() {
// Someone clicked me
}
// Other fun functions
Now, lets say I have: "BadGuy.js", "ReallyReallyBadGuy.js", "OtherBadGuy.js" - They all look like the above in terms of structure. Within the game whenever an event takes place, I'd like to invoke the appropriate function.
The problem comes down to efficiency and speed. I found a working solution by creating an engine for each script instance (using getEngineByName), but that just doesn't seem ideal to me.
If there isn't a better solution, I'll probably resort to each script having its own unique class / function names. I.e.
BadGuy.js
var BadGuy = new Object();
BadGuy.ClickEvent = function() {
}
I don't think you need to create a new ScriptEngine for every "Guy". You can manage them all in one engine. So with advance apologies for butchering you game scenario.....
Get one instance of the Rhino engine.
Issue eval(script) statements to add new JS Objects to the engine, along with the different behaviours (or functions) that you want these Objects to support.
You have a couple of different choices for invoking against each one, but as long as each "guy" has a unique name, you can always reference them by name and invoke a named method against it.
For more performance sensitive operations (perhaps some sort of round based event loop) you can precompile a script in the same engine which can then be executed without having to re-evaluate the source.
Here's a sample I wrote in Groovy.
import javax.script.*;
sem = new ScriptEngineManager();
engine = sem.getEngineByExtension("js");
engine.getBindings(ScriptContext.ENGINE_SCOPE).put("out", System.out);
eventLoop = "for(guy in allGuys) { out.println(allGuys[guy].Action(action)); }; "
engine.eval("var allGuys = []");
engine.eval("var BadGuy = new Object(); allGuys.push(BadGuy); BadGuy.ClickEvent = function() { return 'I am a BadGuy' }; BadGuy.Action = function(activity) { return 'I am doing ' + activity + ' in a BAD way' }");
engine.eval("var GoodGuy = new Object(); allGuys.push(GoodGuy); GoodGuy.ClickEvent = function() { return 'I am a GoodGuy' }; GoodGuy.Action = function(activity) { return 'I am doing ' + activity + ' in a GOOD way' }");
CompiledScript executeEvents = engine.compile(eventLoop);
println engine.invokeMethod(engine.get("BadGuy"), "ClickEvent");
println engine.invokeMethod(engine.get("GoodGuy"), "ClickEvent");
engine.getBindings(ScriptContext.ENGINE_SCOPE).put("action", "knitting");
executeEvents.eval();
I've been using NH Validator for some time, mostly through ValidationDefs, but I'm still not sure about two things:
Is there any special benefit of using ValidationDef for simple/standard validations (like NotNull, MaxLength etc)?
I'm worried about the fact that those two methods throw different kinds of exceptions on validation, for example:
ValidationDef's Define.NotNullable() throws PropertyValueException
When using [NotNull] attribute, an InvalidStateException is thrown.
This makes me think mixing these two approaches isn't a good idea - it will be very difficult to handle validation exceptions consistently. Any suggestions/recommendations?
ValidationDef is probably more suitable for business-rules validation even if, having said that, I used it even for simple validation. There's more here.
What I like about ValidationDef is the fact that it has got a fluent interface.
I've been playing around with this engine for quite a while and I've put together something that works quite well for me.
I've defined an interface:
public interface IValidationEngine
{
bool IsValid(Entity entity);
IList<Validation.IBrokenRule> Validate(Entity entity);
}
Which is implemented in my validation engine:
public class ValidationEngine : Validation.IValidationEngine
{
private NHibernate.Validator.Engine.ValidatorEngine _Validator;
public ValidationEngine()
{
var vtor = new NHibernate.Validator.Engine.ValidatorEngine();
var configuration = new FluentConfiguration();
configuration
.SetDefaultValidatorMode(ValidatorMode.UseExternal)
.Register<Data.NH.Validation.User, Domain.User>()
.Register<Data.NH.Validation.Company, Domain.Company>()
.Register<Data.NH.Validation.PlanType, Domain.PlanType>();
vtor.Configure(configuration);
this._Validator = vtor;
}
public bool IsValid(DomainModel.Entity entity)
{
return (this._Validator.IsValid(entity));
}
public IList<Validation.IBrokenRule> Validate(DomainModel.Entity entity)
{
var Values = new List<Validation.IBrokenRule>();
NHibernate.Validator.Engine.InvalidValue[] values = this._Validator.Validate(entity);
if (values.Length > 0)
{
foreach (var value in values)
{
Values.Add(
new Validation.BrokenRule()
{
// Entity = value.Entity as BpReminders.Data.DomainModel.Entity,
// EntityType = value.EntityType,
EntityTypeName = value.EntityType.Name,
Message = value.Message,
PropertyName = value.PropertyName,
PropertyPath = value.PropertyPath,
// RootEntity = value.RootEntity as DomainModel.Entity,
Value = value.Value
});
}
}
return (Values);
}
}
I plug all my domain rules in there.
I bootstrap the engine at the app startup:
For<Validation.IValidationEngine>()
.Singleton()
.Use<Validation.ValidationEngine>();
Now, when I need to validate my entities before save, I just use the engine:
if (!this._ValidationEngine.IsValid(User))
{
BrokenRules = this._ValidationEngine.Validate(User);
}
and return, eventually, the collection of broken rules.
I have Googled a bit, and cannot seem to find any examples of Xaml-fying Activities - good, bad, or otherwise!
public static string ToXaml (this Activity activity)
{
// i would use ActivityXamlServices to go from Xaml
// to activity, but how to go other way? documentation
// is slim, and cannot infer proper usage of
// ActivityXamlServices from Xml remarks :S
string xaml = string.Empty;
return xaml;
}
Hints, tips, pointers would be welcome :)
NOTE: so found this. Will work through and update once working. Anyone wanna beat me to the punch, by all means. Better yet, if you can find a way to be rid of WorkflowDesigner, seems odd it is required.
Alright, so worked through this forum posting.
You may Xaml-fy [ie transform an instance to declarative Xaml] a well-known Activity via
public static string ToXaml (this Activity activity)
{
StringBuilder xaml = new StringBuilder ();
using (XmlWriter xmlWriter = XmlWriter.Create (
xaml,
new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, }))
using (XamlWriter xamlWriter = new XamlXmlWriter (
xmlWriter,
new XamlSchemaContext ()))
using (XamlWriter xamlServicesWriter =
ActivityXamlServices.CreateBuilderWriter (xamlWriter))
{
ActivityBuilder activityBuilder = new ActivityBuilder
{
Implementation = activity
};
XamlServices.Save (xamlServicesWriter, activityBuilder);
}
return xaml.ToString ();
}
Your Xaml may contain certain artifacts, such as references to System.Activities.Presentation namespace appearing as xmlns:sap="...". If this presents an issue in your solution, read the source link above - there is a means to inject directives to ignore unrecognized namespaces.
Will leave this open for a while. If anyone can find a better solution, or improve upon this, please by all means :)
How about XamlServices.Save(filename, activity)?
Based on the other solution (for VS2010B2) and some Reflectoring, I found a solution for VS2010RC. Since XamlWriter is abstract in the RC, the new way to serialize an activity tree is this:
public static string ToXaml (this Activity activity)
{
var xamlBuilder = new StringBuilder();
var xmlWriter = XmlWriter.Create(xamlBuilder,
new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true });
using (xmlWriter)
{
var xamlXmlWriter =
new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
using (xamlXmlWriter)
{
XamlWriter xamlWriter =
ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);
using (xamlWriter)
{
var activityBuilder =
new ActivityBuilder { Implementation = sequence };
XamlServices.Save(xamlWriter, activityBuilder);
}
}
}
return xamlBuilder.ToString();
}