Call to a possibly undefined method setSelection through a reference with static type SelectionManager - tlf

I'm working with an TLF example (older version) and I'm getting errors when I try to run it:
1061: Call to a possibly undefined method setSelection through a reference with static type flashx.textLayout.edit:ISelectionManager.
_textFlow.interactionManager.setSelection(0,0);

I found an updated example here that contains some of the names of the classes that have been renamed:
TextFilter => TextConverter
ChangeElementIdOperation => ApplyElementIDOperation
DisplayObjectContainerController => ContainerController
ChangeElementStyleNameOperation => ApplyElementStyleNameOperation
flashx.textLayout.BuildInfo.kBuildNumber => TextLayoutVersion.getVersionString(TextLayoutVersion.CURRENT_VERSION)
textFlow.interactionManager.setSelection(0,0) =>_textFlow.interactionManager.setRange(0,0)
e.selectedElementRange.paragraphFormat =>
var selectionState:SelectionState = e.selectionState;
var selectedElementRange:ElementRange = ElementRange.createElementRange(selectionState.textFlow,
selectionState.absoluteStart, selectionState.absoluteEnd);
textFlow.computedTextLayoutFormat => textFlow.computedFormat
I found an updated example of this project on the Apache Flex SDK in the directory flex-tlf/sdk/samples/flex/SimpleEditorWithCSS.

Related

Conditonal resource attributes

To install packages, I feed in data from Hiera into a for loop. Some packages require additional arguments. For packages that do not require an argument, I've set the value to undef, however, Chocolatey reads undef and complains.
How do I get the package resource to ignore the install_options attribute when it is blank or undef?
Hiera snippet:
profile::business::packages:
office365business:
version: latest
provider: chocolatey
arguments: ['/productid:O365BusinessRetail']
xmind:
version: latest
provider: chocolatey
arguments: undef
slack:
version: latest
provider: chocolatey
arguments: undef
Class example:
class profile::business(
Hash $packages,
){
if $::kernel == 'windows' {
$packages.each | $key, $value | {
package { "install_${key}" :
name => $key,
ensure => $value['version'],
provider => $value['provider'],
install_options => $value['arguments'],
notify => Reboot['after_profile_business'],
}
}
reboot { 'after_profile_business' :
apply => finished,
message => 'Reboot: Business profile applied.'
}
}
}
The best I can come up with is using an if clause to apply different instances of the package resource with or without install_options, depending on the value of arguments:
$packages.each | $key, $value | {
if $value['arguments'] != 'undef' {
package { "install_${key}" :
name => $key,
ensure => $value['version'],
provider => $value['provider'],
install_options => $value['arguments'],
notify => Reboot['after_profile_admin'],
}
} else {
package { "install_${key}" :
name => $key,
ensure => $value['version'],
provider => $value['provider'],
notify => Reboot['after_profile_admin'],
}
}
}
However, this seems rather clunky and I'm hoping someone might be able to show me a better way?
I've seen the Puppet Selector condition example, but I do not know if this will work for me.
T.I.A
This YAML fragment ...
arguments: undef
... sets the value of the 'arguments' key to the string 'undef'. That doesn;t mean the same thing on the Puppet side as the Puppet literal undef.
There are solutions. All of the best, IMO, revolve around representing absence of data via bona fide absence of data. That avoids any need for special reserved words. So suppose your data looked like this, instead:
profile::business::packages:
office365business:
version: latest
provider: chocolatey
arguments: ['/productid:O365BusinessRetail']
xmind:
version: latest
provider: chocolatey
slack:
version: latest
provider: chocolatey
Note that there is no entry bearing the arguments key where there are in fact no arguments to specify. If you have been rigorous and thorough about defining data types, then you may need to adjust your data type for these data to accommodate that, but so much the better because that would better describe the actual data semantics. That data modification probably resolves your issue by itself, because looking up a key that does not exist in a hash that does exist should yield undef (and there's also dig() if the undefinedness can occur at a higher level of a deep data structure).
Consider also, however, that Puppet has a shortcut for declaring that resource property values are drawn from a hash. That won't quite fit your present data because your keys are not the same as the needed property names, but you could either change the keys in your data or map them at the Puppet level. The latter might look like this:
# Defining the key / property name mappings here makes them clear, and is easy to
# change if you need to update the mappings
$mappings = { 'version' => 'ensure', 'arguments' => 'install_options' }
$packages.each |$package, $properties| {
# map the keys appearing in the data to Puppet property names, based on
# the hash defined above
$filtered_props = $properties.reduce({}) |$memo, $pair| {
$mapped_key = $pair[0] in $mappings ? { true => $mappings[$pair[0]], default => $pair[0] }
$memo + { $mapped_key => $pair[1] }
}
# one declaration covering all cases
package { "install_${package}" :
name => $package,
provider => $value['provider'],
notify => Reboot['after_profile_admin'],
* => $filtered_props,
}
}

Iterating over controllers in solution

I am trying to get a list of all public methods that return an ActionResult from any controller in my solution using reflection but I am experiencing some strange behavior.
Assembly asm = Assembly.GetAssembly(typeof(MyDLL.MvcApplication));
var controllerActionList = asm.GetTypes().ToList();
If I run the above code I get a list of all my types including all my models and controllers etc. just like I would expect. However, if I modify it and run the below code my results list comes back empty. Any idea what's going on here? I would think this should filter the types down so I get a list of all the controllers right?
Assembly asm = Assembly.GetAssembly(typeof(MyDLL.MvcApplication));
var controllerActionList = asm.GetTypes()
.Where(type => typeof(Controller).IsAssignableFrom(type)).ToList();
I got it working by using the code below. I think the direct type comparison is failing for me because I believe I have two different .net versions between these 2 projects.
Assembly asm = Assembly.GetAssembly(typeof(SCCView.MvcApplication));
var controllerActionList = asm.GetTypes()
.Where(type => type.BaseType.Name == "Controller")
.SelectMany(type => type.GetMethods())
.Where(
m => m.IsPublic && m.ReturnType.Name == "ActionResult")
.Select(x => new {Controller = x.DeclaringType.Name, Action = x.Name})
.OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
The above will give you a paired list of every public method in a controller that returns an ActionResult

Using FluentValidation's WithMessage method with parameters with a WarningMessage

I am new at FluentValidation in general. I am writing a validator, and I can't seem to figure out how to do a .WithMessage with a WarningMessage instead of an ErrorMessage and use params.
I can do this:
RuleFor(x => x.Endorsement)
.Must((coverage, endorsement) => HaveCoveragePerAcreOverMinimum(_coverage, coverage))
.When(x => (!HaveSpecialRequest(_coverage) && !HavePermissionsToOverrideLimits()))
.WithMessage("Some error message {0}", x => x.MyError);
But that sets it as an ErrorMessage and I need a Warning Message. I tried this but no dice:
RuleFor(x => x.Endorsement)
.Must((coverage, endorsement) => HaveCoveragePerAcreOverMinimum(_coverage, coverage))
.When(x => (!HaveSpecialRequest(_coverage) && !HavePermissionsToOverrideLimits()))
.WithMessage(new WarningMessage("Some warning message {0}", x => x.MyError));
There's no direct implementation of Warning message in FluentValidation (or Mvc's ModelState).
In FluentValidation, you've got a
WithState() extension method that you can use for this purpose.
First, you can create an enum
public enum ValidationErrorLevel
{
Error,
Warning
}
Then, you can write a few extension methods, in a static class, to use warnings and errors.
One to use in your Validator classes
public static IRuleBuilderOptions<T, TProperty> AsWarning<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule)
{
return rule.WithState<T, TProperty>(x => ValidationErrorLevel.Warning);
}
You can use it this way
RuleFor(x => x.Endorsement)
.Must((coverage, endorsement) => HaveCoveragePerAcreOverMinimum(_coverage, coverage))
.When(x => (!HaveSpecialRequest(_coverage) && !HavePermissionsToOverrideLimits()))
.WithMessage("Some error message {0}", x => x.MyError)
.AsWarning();
Few other to use to manage your validation results
public static IList<ValidationFailure> GetWarnings(this ValidationResult result)
{
return result.Errors.Where(m => m.CustomState != null && Convert.ToInt32(m.CustomState) == (int)ValidationErrorLevel.Warning).ToList();
}
public static IList<ValidationFailure> GetErrors(this ValidationResult result)
{
return result.Errors.Except(result.GetWarnings()).ToList();
}
Then, you should use
validator.Validate(<someclass>)
instead of
validator.ValidateAndThrow(<someclass>)
var results = validator.Validate(<someclass>);
You can then put errors in ModelState, for example
foreach (var error in result.GetErrors()) {
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
and do something else for Warnings, for example put it in TempData
TempData["warnings"] = new List<string>();
((List<string>)TempData[WarningMessageKey]).AddRange(result.GetWarnings().Select(warning => warning.ErrorMessage));
Then you can display them like any other TempData.
Validation (in general) attaches errors to the ModelState - which in itself is an object so if you put a break point on the if(ModelState.IsValid) line you can look at the other properties of the ModelState.
The thing with errors (and error messages) they are either there or not. If there is no issue there is no error message and if there is an issue an error message will be added.
If I were you, if the model state is not valid in your controller I would get all error messages using
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
and then iterate over each one and decide what you want to do with it.
I hope this answers or at least helps as I am not totally sure what you are asking / trying to get to.

Using Split in RavenDB index

I'd like to use a couple of regexes in an index. This is a simplified example:
Map =
books =>
books.Select(x => new {Sentences = Regex.Split(x.Description, "<br>")})
.Select(x => new {Results = x.Sentences.Where(y => Regex.IsMatch(y, "foo"))})
.Where(x => x.Results.Any())
.Select(x => new {});
However, the following exception is thrown:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'System.Array' does not contain a definition for 'Where'
I've tried .AsEnumerable() but to no avail. Can this be done?
To fix this, you need to call .AsEnumerable() on the thing you're .Select'ing off.
So instead of Regex.Split(...).Select(...), use Regex.Split(...).AsEnumerable().Select(...)
RavenDB relies on an internal class that knows how to map common extension methods.
Sometimes, however, it may not be able to dynamically resolve the extension methods. To help dynamic resolution, call the .AsEnumerable(), then the extension methods will be found.
Your code should look something like this:
Map =
books =>
books.Select(x => new {Sentences = Regex.Split(x.Description, "<br>")})
.AsEnumerable()
.Select(x => new {Results = x.Sentences.Where(y => Regex.IsMatch(y, "foo"))})
.Where(x => x.Results.Any())
.Select(x => new {});

NHibernate mapping error in legacy mapping

I've inherited a large set of NHibernate mappings that live in an existing, functional application. I've branched this application to develop some new features, and while I do so I'm also extending the testing infrastructure to allow for a more TDD-like approach. But now I've hit a wall in one of my integration tests...
I have a class with test data, which I insert prior to the integration test. In the method that inserts these, I get the following exception:
NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of Domain.Entities.Project ---> System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'Domain.Entities.ProjectModules'.
and I can't figure out why. I have two Project instances that I try to persist in the database on setup, both defined like this:
new Project("2023", "projeName", "projaddr")
{
PrincipalOwner = UserOne, // UserOne and Office are other properties
Office = Office,
// I've tried just not instantiating this too - gave the same exception
ProjectModules = new ProjectModules
{
HasModuleOne = false,
HasModuleTwo = false
});
});
The (relevant part of the) Fluent NHibernate mapping looks like this:
Component(m => m.ProjectModules, c =>
{
c.LazyLoad();
c.Map(x => x.HasModuleOne)
.Column("ModuleOne").Not.Nullable().Default("0");
c.Map(x => x.HasModuleTwo)
.Column("ModuleTwo").Not.Nullable().Default("0");
});
I've solved this - for some reason, NHibernate didn't like when the component mapping was specified inline in the mapping for Projects, but if I moved the mapping to a separate class ComponentMap<T> it worked. So I changed the problematic lines to
Component(p => p.ProjectModules);
and added the following class to my mappings assembly:
public class ProjectModulesMap : ComponentMap<ProjectModules>
{
LazyLoad.Always();
Map(pm => pm.ModuleOne);
Map(pm => pm.ModuleTwo);
}
Then everything worked as I would have expected it to from the start.