I'm talking about Ada 2012 here.
I'll let the code speak first:
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash_Case_Insensitive;
with Ada.Strings.Unbounded.Equal_Case_Insensitive;
package Environments is
type Environment is tagged private;
function Variable (
E : in Environment;
Name : in Ada.Strings.Unbounded.Unbounded_String
)
return Ada.Strings.Unbounded.Unbounded_String
with Inline;
procedure Set_Variable (
E : in out Environment;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Value : in Ada.Strings.Unbounded.Unbounded_String
)
with Inline;
private
package Variable_Maps is new Ada.Containers.Hashed_Maps (
Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Ada.Strings.Unbounded.Unbounded_String,
Hash => Ada.Strings.Unbounded.Hash_Case_Insensitive,
Equivalent_Keys => Ada.Strings.Unbounded.Equal_Case_Insensitive,
"=" => Ada.Strings.Unbounded."="
);
type Environment is tagged record
Variables : Variable_Maps.Map;
end record;
end Environments;
What we have here is an example package fairly well illustrating my problem. I'm storing some environment variables in Hashed_Map, but I want to build a abstraction layer over the standard container, so I can in future change the underlaying container without changing any code in my package's customers.
Getting and setting variables is easy - as declared above. The real problem is iterating. I'd like to let my package's customers to iterate over the environment and get both key and value for each element easily.
As I'm using Ada 2012 the best way would be to use iterators, but how? I could return a cursor to the underlaying container, but again, this cursor's interface would be container-dependent.
What's the best way to achieve such abstraction over standard container iteration?
Take a look at Ada Gems #127 and #128, "Iterators in Ada 2012, Parts 1 & 2" for guidance on how to create your own iterators.
Related
i'am using fluent Nhibernate and Envers with this setup
var enversConf = new NHibernate.Envers.Configuration.Fluent.FluentConfiguration();
enversConf.Audit<Segnalazione>()
IRevisionListener revListner = services.GetService<IRevisionListener>();
enversConf.SetRevisionEntity<RevisionEntity>(e => e.Id, e => e.RevisionDate, revListner);
cfg.SetEnversProperty(ConfigurationKey.AuditTableSuffix, "_LOG");
cfg.SetEnversProperty(ConfigurationKey.AuditStrategy, typeof(CustomValidityAuditStrategy));
cfg.IntegrateWithEnvers(enversConf);
i need to change AuditJoinTable naming adding a prefix XXX_
All others table have same prefix and so standard logging table inherits it, only JoinTable hasn't it
i found settings for java version but not for .net one
EDIT:
Now i have table with this naming convention:
XXX_Table1
XXX_Table2
main log table are create with _LOG suffix, so i get
XXX_Table1_LOG
XXX_Table2_LOG
while
AuditJoinTable are created as
Table1Table2_LOG
and i need
XXX_Table1Table2_LOG
I am solving this by adding the name to each join table. Could be more generic but it works.
enversConf.Audit<Segnalazione>()
.SetTableInfo(ug => ug.Foo, t => t.TableName = "XXX_Segnalazione_Foo")
Do you mean that cfg.SetEnversProperty(ConfigurationKey.AuditTablePrefix, "XXX_") doesn't work? It should.
IEnversNamingStrategy is used to decide names for tables, default this one is used where ConfigurationKey.AuditTablePrefix is used for "default prefix". You can also inject your own impl of this interface if you want to.
Using SetTableInfo overrides this and surely works but if I understand you correctly you don't need to do that in this case.
Scenario
Imagine that you have a module X whose functionalities are available to the user through a Command Line Interface. Such module doesn't do much in and of itself but it allows for other people to create plugin-like modules they can hook-up to module X. Ideally, the plugins could be used through X's CLI.
Thus my question:
What do you need to do in order to hook-up whatever functionality
a plugin might provide to X's CLI?
This means the plugin would need to provide some structure describing the command, what needs to be called and hopefully a usage message for the plugin. Therefore, when you run X's CLI, the plugin's command and help message shows up in the regular X's CLI's help message.
Example
main.p6:
use Hello;
use Print;
multi MAIN('goodbye') {
put 'goodbye'
}
lib/Hello.pm6:
unit module Hello;
our %command = %(
command => 'hello',
routine => sub { return "Hello" },
help => 'print hello.'
);
lib/Print.pm6:
unit module Print;
our %command = %(
command => 'print',
routine => sub { .print for 1..10 },
help => 'print numbers 1 through 10.'
);
The program main.p6 is a simplified version of this scenario. I'd like to integrate the information provided by both Hello.pm6 and Print.pm6 through
their respective %command variables into two new MAIN subs in main.p6.
Is this possible? If so, how would I go about achieving it?
This looks kinda specific for a StackOverflow question, but I will give it a try anyway. There are a couple of issues here. First one is to register the commands as such, so that MAIN can issue a message saying "this does that", and second is to actually perform the command. If both can be known at compile time, this can probably be fixed. But let's see how the actual code would go. I'll just do the first part, and I leave the rest as an exercise.
The first thing is that %command needs somehow to be exported. You can't do it the way you are doing it now. First, because it's not explicitly exported; if it were, you would end up with several symbols with the same name in the outer scope. So we need to change that to a class, so that the actual symbols are lexical to the class, and don't pollute the outer scope.
unit class Hello;
has %.command = %(
command => 'hello',
routine => sub { return "Hello" },
help => 'print hello.'
);
(Same would go for Print)
As long as we have that, the rest is not so difficult, only we have to use introspection to know what's actually there, as a small hack:
use Hello;
use Print;
my #packages= MY::.keys.grep( /^^<upper> <lower>/ );
my #commands = do for #packages -> $p {
my $foo = ::($p).new();
$foo.command()<command>
};
multi MAIN( $command where * eq any(#commands) ) {
say "We're doing $command";
}
We check the symbol table looking for packages that start with a capital letter, followed by other non-capital letter. It so happens that the only packages are the ones we're interested in, but of course, if you would want to use this as a plugin mechanism you should just use whatever pattern would be unique to them.
We then create instances of these new packages, and call the command auto-generated method to get the name of the command. And that's precisely what we use to check if we're doing the correct command in the MAIN subroutine, by using the where signature to check if the string we're using is actually in the list of known commands.
Since the functions and the rest of the things are available also from #packages, actually calling them (or giving an additional message or whatever) is left as an exercise.
Update: you might want to check out this other StackOveflow answer as an alternative mechanism for signatures in modules.
crosspost: https://orchard.codeplex.com/discussions/459007
First question I have is what would be the repercussions of having 2 PartHandlers for the same Part in 2 different modules?
I got into this predicament because I have to run a method once a specific Content Type is created. It would be as easy to hook onto OnCreated for the part, however, here is my scenario:
Module A contains the part and the original handler
Module B contains the service where the method is
Module B has a reference to Module A
Therefore, I am unable to reference Module B within Module A (circular reference). So what I did was to copy the exact same PartHandler in Module A and placed it in Module B.
Would anything be wrong with that?
Then comes my second question, which I think could solve all these problems: Can we create a PartHandler for the Content Item's default Content Part? (i.e. the part where all custom fields are attached to)
This would definately make things easier as I could consolidate stuff that need to run there.
UPDATE 1 (to better explain question 2)
ContentDefinitionManager.AlterPartDefinition("EventItem",
builder => builder
.WithField("StartDate", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("Start Date")
.WithSetting("DateTimeFieldSettings.Display", "DateOnly")
.WithSetting("DateTimeFieldSettings.Required", "true"))
.WithField("StartTime", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("Start Time")
.WithSetting("DateTimeFieldSettings.Display", "TimeOnly"))
.WithField("EndDate", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("End Date")
.WithSetting("DateTimeFieldSettings.Display", "DateOnly"))
.WithField("EndTime", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("End Time")
.WithSetting("DateTimeFieldSettings.Display", "TimeOnly"))
.WithField("Intro", cfg => cfg
.OfType("TextField")
.WithDisplayName("Intro")
.WithSetting("TextFieldSettings.Flavor", "textarea"))
ContentDefinitionManager.AlterTypeDefinition(
"EventItem"
, cfg =>
cfg
.DisplayedAs("Event Item")
.WithPart("TitlePart")
.WithPart("EventItem")
.WithPart("LocationPart")
.WithPart("AutoroutePart", builder => builder
.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
.WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false")
.WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: 'learn/events/{Content.Slug}', Description: 'learn/events/event-title'}]")
.WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))
.WithPart("CommonPart")
.Draftable()
.Creatable()
);
I'm talking about creating a ContentHandler for the EventItem part which holds all the custom fields. How can I go about it when EventItemPart is not defined in any class in the solution?
The following below won't work since it can't find the class EventItemPart:
OnCreated<EventItemPart>((context, keynotes) =>
questionService.SetDefaultQuestions(context.ContentItem));
Cross-answer as well.
Bertrand's perfectly right. Why do you need to reference B in A in first place? If the service from B needs A and A needs this service, then it belongs to A (at least the interface - contract).
You can always split interface and actual implementation for your service, having one in different module than another. If implementation of your service requires stuff from B, then put the interface in A, but actual implementation in B. This way A doesn't even need to know about the existence of B, but still be able to use the service via it's interface - it's the beauty of IoC pattern and Orchard modularity:)
You may use ContentPart or IContent as a type argument in handler generic methods. It's perfectly valid. This way you'd be able to plug in to events on all items, and perform custom filtering afterwards (based on type name, some field existence etc.). In your case it may look like:
OnCreated<ContentPart>((context, part) =>
{
if(part.ContentItem.ContentType != "EventItem") return;
questionService.SetDefaultQuestions(context.ContentItem);
});
Update: no need to do this: .WithPart("EventItem"). This 'fake' part will be automatically added by framework.
Cross-answer:
none
However, repeating yourself is almost always wrong, especially if it's done for a bad reason. Why is are the service and the part in two different modules? Why does A need B? A circular reference indicates tight coupling. If the tight coupling is justified, then it should happen in a single module. If it's not, then you need to re-do your design to remove it.
You can create a handler for anything, but your explanation of your scenario is way to vague and abstract to give any useful advice.
All,
I have a requirement to hide my EF implementation behind a Repository. My simple question: Is there a way to execute a 'find' across both a DbSet AND the DbSet.Local without having to deal with them both.
For example - I have standard repository implementation with Add/Update/Remove/FindById. I break the generic pattern by adding a FindByName method (for demo purposes only :). This gives me the following code:
Client App:
ProductCategoryRepository categoryRepository = new ProductCategoryRepository();
categoryRepository.Add(new ProductCategory { Name = "N" });
var category1 = categoryRepository.FindByName("N");
Implementation
public ProductCategory FindByName(string s)
{
// Assume name is unique for demo
return _legoContext.Categories.Where(c => c.Name == s).SingleOrDefault();
}
In this example, category1 is null.
However, if I implement the FindByName method as:
public ProductCategory FindByName(string s)
{
var t = _legoContext.Categories.Local.Where(c => c.Name == s).SingleOrDefault();
if (t == null)
{
t = _legoContext.Categories.Where(c => c.Name == s).SingleOrDefault();
}
return t;
}
In this case, I get what I expect when querying against both a new entry and one that is only in the database. But this presents a few issues that I am confused over:
1) I would assume (as a user of the repository) that cat2 below is not found. But it is found, and the great part is that cat2.Name is "Goober".
ProductCategoryRepository categoryRepository = new ProductCategoryRepository();
var cat = categoryRepository.FindByName("Technic");
cat.Name = "Goober";
var cat2 = categoryRepository.FindByName("Technic");
2) I would like to return a generic IQueryable from my repository.
It just seems like a lot of work to wrap the calls to the DbSet in a repository. Typically, this means that I've screwed something up. I'd appreciate any insight.
With older versions of EF you had very complicated situations that could arise quite fast due to the required references. In this version I would recomend not exposing IQueryable but ICollections or ILists. This will contain EF in your repository and create a good seperation.
Edit: furthermore, by sending back ICollection IEnumerable or IList you are restraining and controlling the queries being sent to the database. This will also allow you to fine tune and maintain the system with greater ease. By exposing IQueriable, you are exposing yourself to side affects which occur when people add more to the query, .Take() or .Where ... .SelectMany, EF will see these additions and will generate sql to reflect these uncontrolled queries. Not confining the queries can result in queries getting executed from the UI and is more complicated tests and maintenance issues in the long run.
since the point of the repository pattern is to be able to swap them out at will. the details of DbSets should be completly hidden.
I think that you're on a good path. The only thing I probaly ask my self is :
Is the context long lived? if not then do not worry about querying Local. An object that has been Inserted / Deleted should only be accessible once it has been comitted.
if this is a long lived context and you need access to deleted and inserted objects then querying the Local is a good idea, but as you've pointed out, you may run into difficulties at some point.
I have a jruby rails app with a ruby module in lib that is name-spacing my java objects so I don't have conflicts.
I'm wondering what the difference is between including the specific classes in that module and including the package. I've included the sample code below.
In the console, for example 1 when I say MyMod:: and hit tab, it has (for example) 101 methods and class options with MyMod::MyClass being one of them.
For example 2, when I hit MyMod:: and tab, it only has 100 method/class options and it doesn't contain MyClass. If I then go and reference MyMod::MyClass, then run that MyMod:: tab again, I now have 101 options and MyClass is listed.
Here's my question. What's the difference between referencing these classes immediately in my module à la example 1 vs having them load on demand like example 2. If I have a package with about 20 classes that I use, is it preferred to have them loaded on demand or up front, and is there any overhead to loading this on demand, à la example 2
Sample Code:
example 1
module MyMod
MyClass = Java::my.package.MyClass
....
end
vs
example 2
module MyMod
include_package "my.package"
end
If you really are going to use a class, it is going to cost you something at some point. It doesn't matter whether loading it specifically or on-demand. I think for your 2 examples, if you do use MyClass, then there's no difference. On the other hand, if MyClass is never used, then example 1 is clearly wasting something.
Also, include_package does not really pull the whole package in, but kind of like establishing a search scope when needing a class. Generally it is not recommended to use include_package. See JRUBY-2376 for problems it has.
I got slightly different results. Perhaps you're using a different auto-completer?
irb(main):001:0> module MyMod;MyClass = Java::JavaUtil::Date;end
=> Java::JavaUtil::Date
irb(main):002:0> module OtherMod;include_package "Java.Util";end
=> nil
irb(main):003:0> MyMod.methods.size
=> 109
irb(main):004:0> OtherMod.methods.size
=> 109
irb(main):005:0> require 'irb/completion'
=> true
irb(main):006:0> MyMod::
Display all 110 possibilities? (y or n)
irb(main):006:0> OtherMod::
Display all 109 possibilities? (y or n)
irb(main):006:0> OtherMod::
irb(main):007:0*
As to your question, I don't know for sure. But if I had to guess, d'd say that as ruby is dynamic, neither approach loads anything up-front.