Microsoft Solver Foundation - Register a constraint as string on a root model referencing a submodel variable - ms-solver-foundation

i have this code to solve a simple problem with Msf
var solver = SolverContext.GetContext();
var model = solver.CreateModel();
//define two simple variables
var decisionX = new Decision(Domain.Set(0,1,2,3,4,8), "X" );
var decisionY = new Decision(Domain.IntegerRange(10,15), "Y" );
//Add decisions to model
model.AddDecision(decisionZ);
model.AddDecision(decisionZ1);
//add an example of Implies condition
model.AddConstraint("constraint2", "Implies[X == 2, Y != 13]");
//now create a simple submodel with simple decision
Model submodel = model.CreateSubModel("submodel");
var subDecision = new Decision(Domain.IntegerRange(20, 22), "Z");
submodel.AddDecision(subDecision);
//Create an instance of the model
var subInstance = submodel.CreateInstance("submodel1");
//now add constrain to rootmodel referencing a variable in child model
//THIS WORKS CORRECTLY
model.AddConstraint("constraint3", subInstance[subDecision] != 21);
//THESE BELOW raise parser exceptions
//model.AddConstraint("constraint3", "submodel1[Z] != 21");
//model.AddConstraint("constraint3", "submodel1.Z != 21");
How can i use string to suggest constraint in submodel instances?

Related

How to return all entries from specific date in log.nsf

I need to return all entries (collection) from a specific date from the miscellaneus view in log.nsf using SSJS.
The views first category is "text" and the second category is a "date".
I tried to use the methods getAllEntriesByKey(vector) or createViewNavFromCategory(vector) but I got kind of stuck as the categorized columns contain different data types.
how can I do that?
Here is one thing I tried
var logdb = sessionAsSigner.getDatabase("domino01/....","log.nsf");
var logView = logdb.getView("MiscEvents")
var v = new java.util.Vector()
var nav = logView.createViewNavFromCategory("domino01/...\\2019-02-15")
return nav.getCount()
and here is another
var logdb = sessionAsSigner.getDatabase("domino01/...","log.nsf");
var logView = logdb.getView("MiscEvents")
var v = new java.util.Vector()
v.add("domino01/...")
v.add(session.createDateTime("Today").getDateOnly())
var nav = logView.getAllEntriesByKey(v)
return nav.getCount()
Just remove the getDateOnly call from your 2nd example code.
v.add(session.createDateTime("Today"))

Constraining more than one IntVarArray

I'm working with several IntVarArray-s in a model in a way that there are cross-dependencies between their elements. Is this the correct way to use them as parameter for the MakePhase method?
var nr = 10;
var fLoc = s.MakeIntVarArray(nr, 0, 1);
var gLoc = s.MakeIntVarArray(nr, 0, 1);
// ... create other arrays
// ... constrain the arrays
// collect them
var decisions = new IntVarVector();
decisions.AddRange(fLoc);
decisions.AddRange(gLoc
//... add other arrays to decisions
// call MakePhase
solver.MakePhase(decisions, ...);
Yes this works.
Please make sure that either the order is the right one, or choose a variable selection strategy that is dynamic like CHOOSE_MIN_SIZE_LOWEST_MIN.

How can I delete a row from a Table in SAPUI5 Application when I used Model as XMLModel?

I have created SAPUI5 application, in that I have loaded data from external .xml file into a table, it was fine. Now, I am trying to delete a specific row from that table.
For this purpose, I use this code:
var oModel = new sap.ui.model.xml.XMLModel();
oModel.loadData("Deployments.xml", "", false);
sap.ui.getCore().setModel(oModel);
oTable.bindRows("/service"); // here "service" is the root element of xml file
var oTable = new sap.ui.commons.Button({
text: "Delete Service",
press: function() {
var idx = oTable.getSelectedIndex();
if (idx !== -1) {
var m = oTable.getModel();
var data = m.getData();
var removed = data.splice(idx, 1); // error showing at this line
m.setData(data);
sap.m.MessageToast.show(JSON.stringify(removed[0]) + 'is removed');
} else {
sap.m.MessageToast.show('Please select a row');
}
}
});
But, I am getting error at the line: var removed = data.splice(idx, 1);. However, the same code is good for when model is JSON. How can I delete a specific row from a table when model XMLModel?
It is a lot easier an more reliable to use a Bindings BindingPath to manipulate data belonging to a particular binding. Here is your adapted sample for a XMLModel:
press: function() {
var iIdx = oTable.getSelectedIndex();
var sPath = oTable.getContextByIndex(iIdx).getPath();
var oObj = oTable.getModel().getObject(sPath);
oObj.remove();
oTable.getModel().refresh();
}
This way you save the hazzle of dealing with the XML structure and furthermore this will scale with any change in the binding path you might introduce in the future.
BR
Chris
var data = m.getData();
data is not an Array. It is a XML document.
To remove an entry from the document:
var root = data.childNodes[0];
var aEntry = root.getElementsByTagName("entry");
root.removeChild(aEntry[idx]);

Testing With A Fake DbContext and Autofixture and Moq

SO follow this example
example and how make a fake DBContex For test my test using just this work fine
[Test]
public void CiudadIndex()
{
var ciudades = new FakeDbSet<Ciudad>
{
new Ciudad {CiudadId = 1, EmpresaId =1, Descripcion ="Santa Cruz", FechaProceso = DateTime.Now, MarcaBaja = null, UsuarioId = 1},
new Ciudad {CiudadId = 2, EmpresaId =1, Descripcion ="La Paz", FechaProceso = DateTime.Now, MarcaBaja = null, UsuarioId = 1},
new Ciudad {CiudadId = 3, EmpresaId =1, Descripcion ="Cochabamba", FechaProceso = DateTime.Now, MarcaBaja = null, UsuarioId = 1}
};
//// Create mock unit of work
var mockData = new Mock<IContext>();
mockData.Setup(m => m.Ciudades).Returns(ciudades);
// Setup controller
var homeController = new CiudadController(mockData.Object);
// Invoke
var viewResult = homeController.Index();
var ciudades_de_la_vista = (IEnumerable<Ciudad>)viewResult.Model;
// Assert..
}
Iam tryign now to use Autofixture-Moq
to create "ciudades" but I cant. I try this
var fixture = new Fixture();
var ciudades = fixture.Build<FakeDbSet<Ciudad>>().CreateMany<FakeDbSet<Ciudad>>();
var mockData = new Mock<IContext>();
mockData.Setup(m => m.Ciudades).Returns(ciudades);
I get this error
Cant convert System.Collections.Generic.IEnumerable(FakeDbSet(Ciudad)) to System.Data.Entity.IDbSet(Ciudad)
cant put "<>" so I replace with "()" in the error message
Implementation of IContext and FakeDbSet
public interface IContext
{
IDbSet<Ciudad> Ciudades { get; }
}
public class FakeDbSet<T> : IDbSet<T> where T : class
how can make this to work?
A minor point... In stuff like:
var ciudades_fixture = fixture.Build<Ciudad>().CreateMany<Ciudad>();
The second type arg is unnecessary and should be:
var ciudades_fixture = fixture.Build<Ciudad>().CreateMany();
I really understand why you need a FakeDbSet and the article is a bit TL;DR... In general, I try to avoid faking and mucking with ORM bits and instead dealing with interfaces returning POCOs to the max degree possible.
That aside... The reason the normal syntax for initialising the list works is that there is an Add (and IEnumerable) in DBFixture. AutoFixture doesn't have a story for that pattern directly (after all it is compiler syntactic sugar and not particularly amenable to reflection or in line with any other conventions) but you can use AddManyTo as long as there is an ICollection in play. Luckily, within the impl of FakeDbSet as in the article, the following gives us an in:-
public ObservableCollection<T> Local
{
get { return _data; }
}
As ObservableCollection<T> derives from ICollection<T>, you should be able to:
var ciudades = new FakeDbSet<Cuidad>();
fixture.AddManyTo(ciudades.Local);
var mockData = new Mock<IContext>();
mockData.Setup(m => m.Ciudades).Returns(ciudades);
It's possible to wire up a customization to make this prettier, but at least you have a way to manage it. The other option is to have something implement ICollection (or add a prop with a setter taking IEnumerable<T> and have AF generate the parent object, causing said collection to be filled in.
Long superseded side note: In your initial question, you effectively have:
fixture.Build<FakeDbSet<Ciudad>>().CreateMany()
The problem becomes clearer then - you are asking AF to generate Many FakeDbSet<Ciudad>s, which is not what you want.
I haven't used AutoFixture in a while, but shouldn't it be:
var ciudades = new FakeDbSet<Ciudad>();
fixture.AddManyTo(ciudades);
for the moment I end doing this, I will keep reading about how use automoq, cause I'm new in this
var fixture = new Fixture();
var ciudades_fixture = fixture.Build<Ciudad>().CreateMany<Ciudad>();
var ciudades = new FakeDbSet<Ciudad>();
foreach (var item in ciudades_fixture)
{
ciudades.Add(item);
}
var mockData = new Mock<IContext>();
fixture.Create<Mock<IContext>>();
mockData.Setup(r => r.Ciudades).Returns(ciudades);

Programmatically creating an Assign in a Flowchart Workflow

I need to programmatically define a serializable flowchart Windows Workflow that accepts input arguments and returns a result. I understand how to create these workflows using a designer, but I need to do it in code and have the flowchart workflow be serializable (so no lambda expressions).
I'm having trouble getting the "To" field of the Assign. The code below creates a flowchart workflow of a WriteLine followed by an Assign.
var ab = new ActivityBuilder<string> {
Name = "ActivityBuilt",
Implementation = new Flowchart {
StartNode = new FlowStep {
Action = new WriteLine { Text = new VisualBasicValue<string>("greeting") },
Next = new FlowStep {
Action = new Assign {
DisplayName = "Set result",
To = new OutArgument<string>(new VisualBasicReference<string> {
ExpressionText = "results"}),
Value = new VisualBasicValue<string>("bye")
}
}
}
}
};
ab.Properties.Add(new DynamicActivityProperty {
Name = "greeting",
Type = typeof (InArgument<string>),
Value = "hello"});
ab.Properties.Add(new DynamicActivityProperty {
Name = "results",
Type = typeof (OutArgument<string>),
Value = "bye"});
// Convert the ActivityBuilder to a callable activity
using (var sw = new StringWriter()) {
using (var xw = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(sw, new XamlSchemaContext()))) {
XamlServices.Save(xw, LastCreated);
}
using (var sr = new StringReader(sw.ToString())) {
var wf = ActivityXamlServices.Load(sr);
return wf;
}
}
The above code fails when I try to convert from ActivityBuilder to Activity saying "Failed to create a 'OutArgument' from the text 'bye'." This works fine if I don't use the OutArgument and just pass things in.
My question is what to put in the To property? How do I reference the OutArgument I add to the ActivityBuilder.Properties? A VisualBasicReference isn't an OutArgument. Am I making this more difficult than it needs to be?
Thanks for any hints!
Edit: I want to create a workflow programmatically. The workflow needs to have input arguments and return results (output arguments).
I understand how to create the workflow and how to declare and use input arguments. I'm using an ActivityBuilder to create the workflow and to set the InArgument via the ActivityBuilder's properties. I create the workflow from the ActivityBuilder by serializing to XAML and then deserializing using ActivityXamlServices.Load.
What I don't understand is how to get a result from the workflow. I assume it involves an OutArgument. How/where do I add an OutArgument to the workflow? I thought the code snippet I gave would assign a value to an OutArgument, but the call to ActivityXamlServices.Load fails with a complaint that it is unable to create the OutArgument.
Is the approach of using ActivityBuilder correct?
Is the "To" field of the Assign action properly referencing an OutArgument?
How do I make the ActivityBuilder aware of the OutArgument and still be able to convert to an Activity / workflow?
Hope this clarifies my problem.
There are atleast 3 problems with the code:
The Value of the Assign needs to be an InArgument().
The value you are trying to read from is named "greeting" not "bye".
The OutArgument named "results" can't have a default value.
Try the following code:
var ab = new ActivityBuilder<string>
{
Name = "ActivityBuilt",
Implementation = new Flowchart
{
StartNode = new FlowStep
{
Action = new WriteLine { Text = new VisualBasicValue<string>("greeting") },
Next = new FlowStep
{
Action = new Assign
{
DisplayName = "Set result",
To = new OutArgument<string>(new VisualBasicReference<string>
{
ExpressionText = "results"
}),
Value = new InArgument<string>(new VisualBasicValue<string>("greeting"))
}
}
}
}
};
ab.Properties.Add(new DynamicActivityProperty
{
Name = "greeting",
Type = typeof(InArgument<string>),
Value = "hello"
});
ab.Properties.Add(new DynamicActivityProperty
{
Name = "results",
Type = typeof(OutArgument<string>)
});
// Convert the ActivityBuilder to a callable activity
using (var sw = new StringWriter())
{
using (var xw = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(sw, new XamlSchemaContext())))
{
XamlServices.Save(xw, ab);
}
using (var sr = new StringReader(sw.ToString()))
{
var wf = ActivityXamlServices.Load(sr);
WorkflowInvoker.Invoke(wf);
}
}