The question of why there are no friends in C# has been extensively discussed.
I have the following design problems.
I have a class that has only one public function AddOrder(Order ord). Clients are allowed to call only this function. All other logic must be hidden. Order class is listening to
market events and must call other other function of TradingSystem ExecuteOrder, so I have to make it public as well. Doing that I will allow clients of Trading system to call this function and I don't want that.
class TradingSystem
{
// Trading system stores list of orders
List<Order> _orders;
// this function is made public so that Order can call ir
public ExecuteOrder(Order ord)
{
}
// this function is made public for external clients
public AddOrder(OrderRequest ordreq)
{
// create order and pass it this
order.OnOrderAdded(this);
}
}
class Order
{
TradingSystem _ts;
public void OnOrderAdded(TradingSystem ts)
{
_ts = ts;
}
void OnMarketEvent()
{
_ts.ExecuteOrder()
}
}
I'm trying to setup something like Aspect Oriented Programming in Actionscript 3, basically the only thing I need to be able to do is something like this:
SomeClass.getMethod("methodName").addEventListener(afterMethodExecuted, function() {
//run code
});
This way I can run code after (or before) any method in any class has run, allowing numerous new possibilities.
How should I implement this?
I was reading an article on Batch Processing in java over at JDJ http://java.sys-con.com/node/415321 . The article mentioned using a persistence queue as a Batch Updater instead of immediately sending an individual insert or update to the database. The author doesn't give a concrete example of this concept so I googled Persistence Queue but that didn't come up with much. Does anyone know of a good example of this?
I am creating an abstract class. I want each of my derived classes to be forced to implement a specific signature of constructor. As such, I did what I would have done has I wanted to force them to implement a method, I made an abstract one.
public abstract class A
{
abstract A(int a, int b);
}
However I get a message saying the abstract modifier is invalid on this item. My goal was to force some code like this.
public class B : A
{
public B(int a, int b) : base(a, b)
{
//Some other awesome code.
}
}
This is all C# .NET code. Can anyone help me out?
Update 1
I wanted to add some things. What I ended up with was this.
private A() { }
protected A(int a, int b)
{
//Code
}
That does what some folks are saying, default is private, and the class needs to implement a constructor. However that doesn't FORCE a constructor with the signature A(int a, int b).
public abstract class A
{
protected abstract A(int a, int b)
{
}
}
Update 2
I should be clear, to work around this I made my default constructor private, and my other constructor protected. I am not really looking for a way to make my code work. I took care of that. I am looking to understand why C# does not let you do this.
I have 3 Tables in my DataBase
CmsMasterPages
CmsMasterPagesAdvSlots (Pure Juction Table)
CmsAdvSlots
Here a Picture of my EDM:
I need find out all objects CmsAdvSlot connected with a CmsMasterPage (it is working in my code posted belove),
and DELETE the result (CmsAdvSlot) from the DataBase.
My Problem is I am not able to DELETE this Objects when I found theme.
Error: The object cannot be deleted because it was not found in the ObjectStateManager.
int findMasterPageId = Convert.ToInt32(uxMasterPagesListSelector.SelectedValue);
CmsMasterPage myMasterPage = context.CmsMasterPages.FirstOrDefault(x => x.MasterPageId == findMasterPageId);
var resultAdvSlots = myMasterPage.CmsAdvSlots;
// It is working until here
foreach (var toDeleteAdv in resultAdvSlots)
{
context.DeleteObject(myMasterPage.CmsAdvSlots.Any()); // ERORR HERE!!
context.SaveChanges();
}
Any idea how to solve it? Thanks for your time! :-)
Hi,
I have a Tour object which has many Place objects. For the list of tours, I want to show some info of the tour, the number of places of the tour, and three Place's images. Right one my SQL queries are (i'm using Doctrine with Symfony on MySQL)
get Tour
get Tour 1 places
get Tour 2 places
get Tour 3 places
...
get Tour n places
If I have a three Tour list, it's not so bad; but I'm sure it can get bad if I do a 10-20 tour-list. So, thinking on how to improve the queries I've thought of several measures:
Having a place count cache
Storing the urls of three images on a new tour field.
The problem with 2. is that if I change the image, I have to check all the tours to update that image for another one.
What solution do you think is best to scale the system in a near future? Any other suggestion.
thanks!
I have a custom CALayer - UIProgressLayer - for simulating a progress bar. There is a dispatched GC timer involved to animate its intermediate state. So thats the layer I'm talking about here, although i don't think the problem is restricted to this particular subclass because a CALayer with only the -release and -dealloc overridden produces the same outcome.
The problem is when i send this layer, for instance, a
theLayer.opacity = 0.5f
a -release message is sent to the layer, thus deallocating my layer. Why is this happening? Has it something to do with how the whole CA system works? But it still has to obey the object ownership rules right?
I was thinking maybe it creates a copy of that layer for the fading, but that's not the case.
Let's say I'm defining a game class that implements two different views:
interface IPlayerView {
void play();
}
interface IDealerView {
void deal();
}
The view that a game sees when playing the game, and a view that the dealer sees when dealing the game (this is, a player can't make dealer actions and a dealer can't make player actions). The game definition is as following:
class Game : IPlayerView, IDealerView {
void play() { ... }
void deal() { ... }
}
Now assume I want to make it possible for the players to play the game, but not to deal it. My original idea was that instead of having
public Game GetGame() { ... }
I'd have something like
public IPlayerView GetGame() { ... }
But after some tests I realized that if I later try this code, it works:
IDealerView dealerView = (IDealerView)GameClass.GetGame();
this works as lets the user act as the dealer.
Am I worrying to much? How do you usually deal with this patterns? I could instead make two different classes, maybe a "main" class, the dealer class, that would act as factory of player classes. That way I could control exactly what I would like to pass on the the public. On the other hand, that turns everything a bit more complex than with this original design.
Thanks
I have two tables:
Job
job_id, <other data>
Job_Link
job_link_id, job_id, start_timestamp, end_timestamp, <other data>
There may be multiple records in Job_Link specifying the same job_id with the start_timestamp and end_timestamps to indicate when those records are considered "current", it is guaranteed that start_timestamp and end_timestamp will not overlap.
We have entities for both the Job and Job_Link tables and defining a one-to-many relationship to load all the job_links wouldn't be a problem. However we'd like to avoid that and have a single job_link item in the Job entity that will contain only the "current" Job_Link object.
Is there any way to achive that?
hello,
i have the following switch case:
switch (appModel.currentPage){
case "Programma":
case "Winkelwagen":
case "Films":
case "Contact":
if (page){
removeChild(page);
}
//here i would like to create a new object page that has the type of the switch.
i mean this: var page: getDefinitionByName(appModel.currentPage+"Page");
this doesnt work thou but it should be something like: "FilmsPage or ContactPage or ...".
addChild(page);
break;
Does anyone know how to do this?
Hi, first post here.In Django, I want to have many files be associated with a particular model, so I'm doing a seperate model called files and have model 'A' 'have many' files. But I want my files to be saved in director named by model 'A'. So For example I want something like this:
class Show(models.Model):
name = models.CharField()
showfolder = models.FilePathField()
class Episode(models.Model):
show = models.ForeignKey(Show)
name = models.CharField()
files = models.ManyToManyField(mp3)
class Mp3(models.Model):
file = FileField(upload_to=Episode.show.showfolder)
So hopefully that last line expresses what I WANT it to do(get the folder name from Show object associated with the episode). The question is how would I really write that?(besides jumping through hoops in the controller.)
Thanks.
I understand that we can export data matrices to csv or xlsx files.
What about complex objects like lm? For example, in my work I might have a list of length 1000, each with a single lm() object. Each time I load R I have to wait a long time to populate the 1000 length list with these lm objects with a for loop or a lapply.
I would rather just save the list somewhere on my HDD at the end of a session and open it at the start of the next session.
I have a Perl module and I'd like to be able to pick out the parameters that my my module's user passed in the "use" call. Whichever ones I don't recognize I'd like to pass on. I tried to do this by overriding the "import" method but I'm not having much luck.
EDIT:
To clarify, as it is, I can use my module like this:
use MyModule qw/foo bar/;
which will import the foo and bar methods of MyModule. But I want to be able to say:
use MyModule qw/foo doSpecialStuff bar/;
and look for doSpecialStuff to check if I need to do some special stuff at the beginning of the program, then pass qw/foo bar/ to the Exporter's import
Consider the following analogy:
If we have a class: "Car" we might expect it to have an instance of "Engine" in it. As in: "The car HAS-A engine". Similarly, in the "Engine" class we would expect an instance of "Starting System" or "Cooling System" which each have their appropriate sub-components.
By the nature of encapsulation, is it not true that the car "HAS-A" "radiator hose" in it as well as the engine?
Therefore, is it appropriate OO to do something like this:
public class Car {
private Engine _engine;
public Engine getEngine() {
return _engine;
}
// is it ok to use 'convenience' methods of inner classes?
// are the following 2 methods "wrong" from an OO point of view?
public RadiatorHose getRadiatorHose() {
return getCoolingSystem().getRadiatorHose();
}
public CoolingSystem getCoolingSystem() {
return _engine.getCoolingSystem();
}
}
public class Engine {
private CoolingSystem _coolingSystem;
public CoolingSystem getCoolingSystem() {
return _coolingSystem;
}
}
public class CoolingSystem {
private RadiatorHose _radiatorHose;
public RadiatorHose getRadiatorHose() {
return _radiatorHose;
}
}
public class RadiatorHose {//...
}
There is a main class containing 2 sub-class(with some prop). If I create an obj of main class, will have access to sub-Class as well b/c we have property defined in main class.
Is thr any way where I pass Main class.SubClass name then it will return that object only ?
can we use indexer ?
MainClass obj = new MainClass();
obj.SubClass1 or obj.SubClass2 ??? Thanks in adv...
class MainClass
{
SubClass1 objSubclass1 = null;
SubClass2 objSubclass2 = null;
public MainClass()
{
objSubclass1 = new SubClass1();
objSubclass2 = new SubClass2();
}
public SubClass1 SubClass1 {get {return objSubclass1;} }
public SubClass2 SubClass2 {get {return objSubclass2;} }
}
Class SubClass1
{
Some properties here...
}
Class SubClass2
{
Some properties here...
}
In the following code, Foo::add calls a function via a function object:
struct Plus {
inline int operator()(int x, int y) const {
return x + y;
}
};
template<class Fct>
struct Foo {
Fct fct;
Foo(Fct f) : fct(f) {}
inline int add(int x, int y) {
return fct(x,y); // same efficiency adding directly?
}
};
Is this the same efficiency as calling x+y directly in Foo::add? In other words, does the compiler typically directly replace fct(x,y) with the actual call, inlining the code, when compiling with optimizations enabled?
This question came to my mind quite a few times.
Let my explain my question through an example.
Say I've got two classes:
1- Grid.
2- Cell.
Now the location of the cell 'should' be stored in the grid class, not in the cell class itself. Say that the cell wanted to get its location through a method in the grid.
How can it do that? Keep in mind that the cell was created/initialised by the Grid class.
What good OO approach to solve this problem?
Thank you
Hi all,
Anybody know how can I add multiple email addresses in Outlook field "To" via C#?
foreach (var to in mailTo)
newMail.To += to + "; ";
When I try do it how I described this above I receive next kind of string:
[email protected]@[email protected]
class MyWriter:
def __init__(self, stdout):
self.stdout = stdout
self.dumps = []
def write(self, text):
self.stdout.write(smart_unicode(text).encode('cp1251'))
self.dumps.append(text)
def close(self):
self.stdout.close()
writer = MyWriter(sys.stdout)
save = sys.stdout
sys.stdout = writer
I use self.dumps list to store geted data from prints. Is it exists more convinient object for storing string lines in memory? ideally i want dump it to one big string. I can get it like this "\n".join(self.dumps) from code above. Mb it's better to just concat strings - self.dumps += text ?
I am trying to add time to a Date object in javascript but am not getting the results that I am expecting. I am trying to pull a timer off of the page and add it to the current time to get the unix timestamp value of when the timer will hit zero. The time on the page is displayed as " HH:MM:SS ". This is what I have:
time=getTimerText.split(":");
seconds=(time[0]*3600+time[1]*60+time[2])*1000;
to convert the time into milliseconds.
fDate=new Date();
fDate.setTime(fDate.getTime()+seconds);
add the milliseconds to the javascript timestamp
alert(Math.round(fDate.getTime() / 1000));
convert the javascript timestamp to a unix timestamp
Since the timer is counting down I should get the same result every time i run the script, but I don't. Can anyone see what I might be doing wrong here?
Is there a framework which can be used in your application, to make it expose internal objects on some port for inspection.
for.e.g. after i start my application in this case a GUI Application, and then say launch http://localhost:9100 then it should show me the statistics of the app.
I played a bit with HttpListener accepting connections and then outputting raw HTML, it works fine for simple tasks, but there is too much worked involved if i have make a proper object browser.
Thanks in Advance.
Hello,
I'm developing a "script generator" to automatize some processes at work.
It has a Rails application running on a server that stores all data needed to make the script and generates the script itself at the end of the process.
The problem I am having is how to export the data from the ActiveRecord format to Plain Old Ruby Objects (POROs) so I can deal with them in my script with no database support and a pure-ruby implementation.
I tought about YAML, CSV or something like this to export the data but it would be a painful process to update these structures if the process changes. Is there a simpler way?
Ty!
im trying to understand the factory design pattern.
i dont understand why it's good to have a middleman between the client and the product (object that the client wants).
example with no factory:
$mac = new Mac();
example with a factory:
$appleStore = new AppleStore();
$mac = $appleStore->getProduct('mac');
how does the factory pattern decouple the client from the product?
could someone give an example of a future code change that will impact on example 1 negative, but positive in example 2 so i understand the importance of decoupling?
thanks
I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row.
Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator.
Here's what I have:
def times(self, n, *args, **kwargs):
for _ in range(n):
self.__call__(*args, **kwargs)
import new
def repeatable(func):
func.times = new.instancemethod(times, func, func.__class__)
@repeatable
def threeArgs(one, two, three):
print one, two, three
threeArgs.times(7, "one", two="rawr", three="foo")
When I run the program, I get the following exception:
Traceback (most recent call last):
File "", line 244, in run_nodebug
File "C:\py\repeatable.py", line 24, in
threeArgs.times(7, "one", two="rawr", three="foo")
AttributeError: 'NoneType' object has no attribute 'times'
So I suppose the decorator didn't work? How can I fix this?