Search Results

Search found 1151 results on 47 pages for 'lazy'.

Page 4/47 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Entity Framework lazy loading doesn't work from other thread

    - by Thomas Levesque
    Hi, I just found out that lazy loading in Entity Framework only works from the thread that created the ObjectContext. To illustrate the problem, I did a simple test, with a simple model containing just 2 entities : Person and Address. Here's the code : private static void TestSingleThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Console.WriteLine("{0} lives in {1}.", p.Name, p.Address.City); } } } private static void TestMultiThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Person p2 = p; // to avoid capturing the loop variable ThreadPool.QueueUserWorkItem( arg => { Console.WriteLine("{0} lives in {1}.", p2.Name, p2.Address.City); }); } } } The TestSingleThread method works fine, the Address property is lazily loaded. But in TestMultiThread, I get a NullReferenceException on p2.Address.City, because p2.Address is null. It that a bug ? Is this the way it's supposed to work ? If so, is there any documentation mentioning it ? I couldn't find anything on the subject on MSDN or Google... And more importantly, is there a workaround ? (other than explicitly calling LoadProperty from the worker thread...) Any help would be very appreciated PS: I'm using VS2010, so it's EF 4.0. I don't know if it was the same in the previous version of EF...

    Read the article

  • Haskell lazy I/O and closing files

    - by Jesse
    I've written a small Haskell program to print the MD5 checksums of all files in the current directory (searched recursively). Basically a Haskell version of md5deep. All is fine and dandy except if the current directory has a very large number of files, in which case I get an error like: <program>: <currentFile>: openBinaryFile: resource exhausted (Too many open files) It seems Haskell's laziness is causing it not to close files, even after its corresponding line of output has been completed. The relevant code is below. The function of interest is getList. import qualified Data.ByteString.Lazy as BS main :: IO () main = putStr . unlines =<< getList "." getList :: FilePath -> IO [String] getList p = let getFileLine path = liftM (\c -> (hex $ hash $ BS.unpack c) ++ " " ++ path) (BS.readFile path) in mapM getFileLine =<< getRecursiveContents p hex :: [Word8] -> String hex = concatMap (\x -> printf "%0.2x" (toInteger x)) getRecursiveContents :: FilePath -> IO [FilePath] -- ^ Just gets the paths to all the files in the given directory. Are there any ideas on how I could solve this problem? The entire program is available here: http://haskell.pastebin.com/PAZm0Dcb

    Read the article

  • Eager/Lazy loaded member always empty with JPA one-to-many relationship

    - by Kaleb Pederson
    I have two entities, a User and Role with a one-to-many relationship from user to role. Here's what the tables look like: mysql> select * from User; +----+-------+----------+ | id | name | password | +----+-------+----------+ | 1 | admin | admin | +----+-------+----------+ 1 row in set (0.00 sec) mysql> select * from Role; +----+----------------------+---------------+----------------+ | id | description | name | summary | +----+----------------------+---------------+----------------+ | 1 | administrator's role | administrator | Administration | | 2 | editor's role | editor | Editing | +----+----------------------+---------------+----------------+ 2 rows in set (0.00 sec) And here's the join table that was created: mysql> select * from User_Role; +---------+----------+ | User_id | roles_id | +---------+----------+ | 1 | 1 | | 1 | 2 | +---------+----------+ 2 rows in set (0.00 sec) And here's the subset of orm.xml that defines the tables and relationships: <entity class="User" name="User"> <table name="User" /> <attributes> <id name="id"> <generated-value strategy="AUTO" /> </id> <basic name="name"> <column name="name" length="100" unique="true" nullable="false"/> </basic> <basic name="password"> <column length="255" nullable="false" /> </basic> <one-to-many name="roles" fetch="EAGER" target-entity="Role" /> </attributes> </entity> <entity class="Role" name="Role"> <table name="Role" /> <attributes> <id name="id"> <generated-value strategy="AUTO"/> </id> <basic name="name"> <column name="name" length="40" unique="true" nullable="false"/> </basic> <basic name="summary"> <column name="summary" length="100" nullable="false"/> </basic> <basic name="description"> <column name="description" length="255"/> </basic> </attributes> </entity> Yet, despite that, when I retrieve the admin user, I get back an empty collection. I'm using Hibernate as my JPA provider and it shows the following debug SQL: select user0_.id as id8_, user0_.name as name8_, user0_.password as password8_ from User user0_ where user0_.name=? limit ? When the one-to-many mapping is lazy loaded, that's the only query that's made. This correctly retrieves the one admin user. I changed the relationship to use eager loading and then the following query is made in addition to the above: select roles0_.User_id as User1_1_, roles0_.roles_id as roles2_1_, role1_.id as id9_0_, role1_.description as descript2_9_0_, role1_.name as name9_0_, role1_.summary as summary9_0_ from User_Role roles0_ left outer join Role role1_ on roles0_.roles_id=role1_.id where roles0_.User_id=? Which results in the following results: +----------+-----------+--------+----------------------+---------------+----------------+ | User1_1_ | roles2_1_ | id9_0_ | descript2_9_0_ | name9_0_ | summary9_0_ | +----------+-----------+--------+----------------------+---------------+----------------+ | 1 | 1 | 1 | administrator's role | administrator | Administration | | 1 | 2 | 2 | editor's role | editor | Editing | +----------+-----------+--------+----------------------+---------------+----------------+ 2 rows in set (0.00 sec) Hibernate obviously knows about the roles, yet getRoles() still returns an empty collection. Hibernate also recognized the relationship sufficiently to put the data in the first place. What problems can cause these symptoms?

    Read the article

  • Approaches for generic, compile-time safe lazy-load methods

    - by Aaronaught
    Suppose I have created a wrapper class like the following: public class Foo : IFoo { private readonly IFoo innerFoo; public Foo(IFoo innerFoo) { this.innerFoo = innerFoo; } public int? Bar { get; set; } public int? Baz { get; set; } } The idea here is that the innerFoo might wrap data-access methods or something similarly expensive, and I only want its GetBar and GetBaz methods to be invoked once. So I want to create another wrapper around it, which will save the values obtained on the first run. It's simple enough to do this, of course: int IFoo.GetBar() { if ((Bar == null) && (innerFoo != null)) Bar = innerFoo.GetBar(); return Bar ?? 0; } int IFoo.GetBaz() { if ((Baz == null) && (innerFoo != null)) Baz = innerFoo.GetBaz(); return Baz ?? 0; } But it gets pretty repetitive if I'm doing this with 10 different properties and 30 different wrappers. So I figured, hey, let's make this generic: T LazyLoad<T>(ref T prop, Func<IFoo, T> loader) { if ((prop == null) && (innerFoo != null)) prop = loader(innerFoo); return prop; } Which almost gets me where I want, but not quite, because you can't ref an auto-property (or any property at all). In other words, I can't write this: int IFoo.GetBar() { return LazyLoad(ref Bar, f => f.GetBar()); // <--- Won't compile } Instead, I'd have to change Bar to have an explicit backing field and write explicit getters and setters. Which is fine, except for the fact that I end up writing even more redundant code than I was writing in the first place. Then I considered the possibility of using expression trees: T LazyLoad<T>(Expression<Func<T>> propExpr, Func<IFoo, T> loader) { var memberExpression = propExpr.Body as MemberExpression; if (memberExpression != null) { // Use Reflection to inspect/set the property } } This plays nice with refactoring - it'll work great if I do this: return LazyLoad(f => f.Bar, f => f.GetBar()); But it's not actually safe, because someone less clever (i.e. myself in 3 days from now when I inevitably forget how this is implemented internally) could decide to write this instead: return LazyLoad(f => 3, f => f.GetBar()); Which is either going to crash or result in unexpected/undefined behaviour, depending on how defensively I write the LazyLoad method. So I don't really like this approach either, because it leads to the possibility of runtime errors which would have been prevented in the first attempt. It also relies on Reflection, which feels a little dirty here, even though this code is admittedly not performance-sensitive. Now I could also decide to go all-out and use DynamicProxy to do method interception and not have to write any code, and in fact I already do this in some applications. But this code is residing in a core library which many other assemblies depend on, and it seems horribly wrong to be introducing this kind of complexity at such a low level. Separating the interceptor-based implementation from the IFoo interface by putting it into its own assembly doesn't really help; the fact is that this very class is still going to be used all over the place, must be used, so this isn't one of those problems that could be trivially solved with a little DI magic. The last option I've already thought of would be to have a method like: T LazyLoad<T>(Func<T> getter, Action<T> setter, Func<IFoo, T> loader) { ... } This option is very "meh" as well - it avoids Reflection but is still error-prone, and it doesn't really reduce the repetition that much. It's almost as bad as having to write explicit getters and setters for each property. Maybe I'm just being incredibly nit-picky, but this application is still in its early stages, and it's going to grow substantially over time, and I really want to keep the code squeaky-clean. Bottom line: I'm at an impasse, looking for other ideas. Question: Is there any way to clean up the lazy-loading code at the top, such that the implementation will: Guarantee compile-time safety, like the ref version; Actually reduce the amount of code repetition, like the Expression version; and Not take on any significant additional dependencies? In other words, is there a way to do this just using regular C# language features and possibly a few small helper classes? Or am I just going to have to accept that there's a trade-off here and strike one of the above requirements from the list?

    Read the article

  • Expected time for lazy evaluation with nested functions?

    - by Matt_JD
    A colleague and I are doing a free R course, although I believe this is a more general lazy evaluation issue, and have found a scenario that we have discussed briefly and I'd like to find out the answer from a wider community. The scenario is as follows (pseudo code): wrapper => function(thing) { print => function() { write(thing) } } v = createThing(1, 2, 3) w = wrapper(v) v = createThing(4, 5, 6) w.print() // Will print 4, 5, 6 thing. v = create(7, 8, 9) w.print() // Will print 4, 5, 6 because "thing" has now been evaluated. Another similar situation is as follows: // Using the same function as above v = createThing(1, 2, 3) v = wrapper(v) w.print() // The wrapper function incestuously includes itself. Now I understand why this happens but where my colleague and I differ is on what should happen. My colleague's view is that this is a bug and the evaluation of the passed in argument should be forced at the point it is passed in so that the returned "w" function is fixed. My view is that I would prefer his option myself, but that I realise that the situation we are encountering is down to lazy evaluation and this is just how it works and is more a quirk than a bug. I am not actually sure of what would be expected, hence the reason I am asking this question. I think that function comments could express what will happen, or leave it to be very lazy, and if the coder using the function wants the argument evaluated then they can force it before passing it in. So, when working with lazy evaulation, what is the practice for the time to evaluate an argument passed, and stored, inside a function?

    Read the article

  • Haskell Lazy Evaluation and Reuse

    - by Jonathan Sternberg
    I know that if I were to compute a list of squares in Haskell, I could do this: squares = [ x ** 2 | x <- [1 ..] ] Then when I call squares like this: print $ take 4 squares And it would print out [1.0, 4.0, 9.0, 16.0]. This gets evaluated as [ 1 ** 2, 2 ** 2, 3 ** 2, 4 ** 2 ]. Now since Haskell is functional and the result would be the same each time, if I were to call squares again somewhere else, would it re-evaluate the answers it's already computed? If I were to re-use squares after I had already called the previous line, would it re-calculate the first 4 values? print $ take 5 squares Would it evaluate [1.0, 4.0, 9.0, 16.0, 5 ** 2]?

    Read the article

  • Thread safe lazy contruction of a singleton in C++

    - by pauldoo
    Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..) Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being the answer). There appears to be two broad solutions: Use static initialisation (as opposed to dynamic initialisation) of a POD static varible, and implementing my own mutex with that using the builtin atomic instructions. This was the type of solution I was hinting at in my question, and I believe I knew already. Use some other library function like pthread_once or boost::call_once. These I certainly didn't know about - and am very grateful for the answers posted.

    Read the article

  • IconDownloader, problem with lazy downloading

    - by Junior B.
    My problem is simple to be described but it seems to be hard to solve. The problem is loading icons, with a custom class like IconDownloader.m provided by an official example from Apple, avoiding crashes if I release the view. I've added the IconDownloader class to my app, but it's clear that this approach is good only if the tableview is the root. The big problem is when the view is not the root one. F.e: if I start to scroll my second view (the app now load the icons) and, without leaving it the time to finish the download, I go back to root, the app crash because the view that have to be updated with new icons doesn't exist anymore. One possible solution could be implement an OperationQueue in the view, but with this approach I've to stop the queue when I change the view and restart it when I come back and the idea to have N queues don't make me enthusiastic. Anyone found a good solution for this problem?

    Read the article

  • How to lazy load a data structure (python)

    - by Anton Geraschenko
    I have some way of building a data structure (out of some file contents, say): def loadfile(FILE): return # some data structure created from the contents of FILE So I can do things like puppies = loadfile("puppies.csv") # wait for loadfile to work kitties = loadfile("kitties.csv") # wait some more print len(puppies) print puppies[32] In the above example, I wasted a bunch of time actually reading kitties.csv and creating a data structure that I never used. I'd like to avoid that waste without constantly checking if not kitties whenever I want to do something. I'd like to be able to do puppies = lazyload("puppies.csv") # instant kitties = lazyload("kitties.csv") # instant print len(puppies) # wait for loadfile print puppies[32] So if I don't ever try to do anything with kitties, loadfile("kitties.csv") never gets called. Is there some standard way to do this? After playing around with it for a bit, I produced the following solution, which appears to work correctly and is quite brief. Are there some alternatives? Are there drawbacks to using this approach that I should keep in mind? class lazyload: def __init__(self,FILE): self.FILE = FILE self.F = None def __getattr__(self,name): if not self.F: print "loading %s" % self.FILE self.F = loadfile(self.FILE) return object.__getattribute__(self.F, name) What might be even better is if something like this worked: class lazyload: def __init__(self,FILE): self.FILE = FILE def __getattr__(self,name): self = loadfile(self.FILE) # this never gets called again # since self is no longer a # lazyload instance return object.__getattribute__(self, name) But this doesn't work because self is local. It actually ends up calling loadfile every time you do anything.

    Read the article

  • ExtJS (4.0) dynamic / lazy loading

    - by Paul
    Given a border layout with a west (navigation) and a center region. Let say I click on topic A in the west region, I want to replace (replace as in 'delete last topic') the center region with 'extjs' program code named topic_a.js I succeed in loading with this code: dynamicPanel = new Ext.Component({ loader: { url: '/www/file.htm', renderer: 'html', autoLoad: true, scripts: true } }); var oMainContainer = Ext.getCmp('maincontainer'); oMainContainer.show(); oMainContainer.add(dynamicPanel); But calling this the second time 'adds' things up in the center region and of course fails short in 'deleting', what would be a good approach?

    Read the article

  • C#: System.Lazy&lt;T&gt; and the Singleton Design Pattern

    - by James Michael Hare
    So we've all coded a Singleton at one time or another.  It's a really simple pattern and can be a slightly more elegant alternative to global variables.  Make no mistake, Singletons can be abused and are often over-used -- but occasionally you find a Singleton is the most elegant solution. For those of you not familiar with a Singleton, the basic Design Pattern is that a Singleton class is one where there is only ever one instance of the class created.  This means that constructors must be private to avoid users creating their own instances, and a static property (or method in languages without properties) is defined that returns a single static instance. 1: public class Singleton 2: { 3: // the single instance is defined in a static field 4: private static readonly Singleton _instance = new Singleton(); 5:  6: // constructor private so users can't instantiate on their own 7: private Singleton() 8: { 9: } 10:  11: // read-only property that returns the static field 12: public static Singleton Instance 13: { 14: get 15: { 16: return _instance; 17: } 18: } 19: } This is the most basic singleton, notice the key features: Static readonly field that contains the one and only instance. Constructor is private so it can only be called by the class itself. Static property that returns the single instance. Looks like it satisfies, right?  There's just one (potential) problem.  C# gives you no guarantee of when the static field _instance will be created.  This is because the C# standard simply states that classes (which are marked in the IL as BeforeFieldInit) can have their static fields initialized any time before the field is accessed.  This means that they may be initialized on first use, they may be initialized at some other time before, you can't be sure when. So what if you want to guarantee your instance is truly lazy.  That is, that it is only created on first call to Instance?  Well, there's a few ways to do this.  First we'll show the old ways, and then talk about how .Net 4.0's new System.Lazy<T> type can help make the lazy-Singleton cleaner. Obviously, we could take on the lazy construction ourselves, but being that our Singleton may be accessed by many different threads, we'd need to lock it down. 1: public class LazySingleton1 2: { 3: // lock for thread-safety laziness 4: private static readonly object _mutex = new object(); 5:  6: // static field to hold single instance 7: private static LazySingleton1 _instance = null; 8:  9: // property that does some locking and then creates on first call 10: public static LazySingleton1 Instance 11: { 12: get 13: { 14: if (_instance == null) 15: { 16: lock (_mutex) 17: { 18: if (_instance == null) 19: { 20: _instance = new LazySingleton1(); 21: } 22: } 23: } 24:  25: return _instance; 26: } 27: } 28:  29: private LazySingleton1() 30: { 31: } 32: } This is a standard double-check algorithm so that you don't lock if the instance has already been created.  However, because it's possible two threads can go through the first if at the same time the first time back in, you need to check again after the lock is acquired to avoid creating two instances. Pretty straightforward, but ugly as all heck.  Well, you could also take advantage of the C# standard's BeforeFieldInit and define your class with a static constructor.  It need not have a body, just the presence of the static constructor will remove the BeforeFieldInit attribute on the class and guarantee that no fields are initialized until the first static field, property, or method is called.   1: public class LazySingleton2 2: { 3: // because of the static constructor, this won't get created until first use 4: private static readonly LazySingleton2 _instance = new LazySingleton2(); 5:  6: // Returns the singleton instance using lazy-instantiation 7: public static LazySingleton2 Instance 8: { 9: get { return _instance; } 10: } 11:  12: // private to prevent direct instantiation 13: private LazySingleton2() 14: { 15: } 16:  17: // removes BeforeFieldInit on class so static fields not 18: // initialized before they are used 19: static LazySingleton2() 20: { 21: } 22: } Now, while this works perfectly, I hate it.  Why?  Because it's relying on a non-obvious trick of the IL to guarantee laziness.  Just looking at this code, you'd have no idea that it's doing what it's doing.  Worse yet, you may decide that the empty static constructor serves no purpose and delete it (which removes your lazy guarantee).  Worse-worse yet, they may alter the rules around BeforeFieldInit in the future which could change this. So, what do I propose instead?  .Net 4.0 adds the System.Lazy type which guarantees thread-safe lazy-construction.  Using System.Lazy<T>, we get: 1: public class LazySingleton3 2: { 3: // static holder for instance, need to use lambda to construct since constructor private 4: private static readonly Lazy<LazySingleton3> _instance 5: = new Lazy<LazySingleton3>(() => new LazySingleton3()); 6:  7: // private to prevent direct instantiation. 8: private LazySingleton3() 9: { 10: } 11:  12: // accessor for instance 13: public static LazySingleton3 Instance 14: { 15: get 16: { 17: return _instance.Value; 18: } 19: } 20: } Note, you need your lambda to call the private constructor as Lazy's default constructor can only call public constructors of the type passed in (which we can't have by definition of a Singleton).  But, because the lambda is defined inside our type, it has access to the private members so it's perfect. Note how the Lazy<T> makes it obvious what you're doing (lazy construction), instead of relying on an IL generation side-effect.  This way, it's more maintainable.  Lazy<T> has many other uses as well, obviously, but I really love how elegant and readable it makes the lazy Singleton.

    Read the article

  • Hidden divs for "lazy javascript" loading? Possible security/other issues?

    - by xyld
    I'm curious about people's opinion's and thoughts about this situation. The reason I'd like to lazy load javascript is because of performance. Loading javascript at the end of the body reduces the browser blocking and ends up with much faster page loads. But there is some automation I'm using to generate the html (django specifically). This automation has the convenience of allowing forms to be built with "Widgets" that output content it needs to render the entire widget (extra javascript, css, ...). The problem is that the widget wants to output javascript immediately into the middle of the document, but I want to ensure all javascript loads at the end of the body. When the following widget is added to a form, you can see it renders some <script>...</script> tags: class AutoCompleteTagInput(forms.TextInput): class Media: css = { 'all': ('css/jquery.autocomplete.css', ) } js = ( 'js/jquery.bgiframe.js', 'js/jquery.ajaxQueue.js', 'js/jquery.autocomplete.js', ) def render(self, name, value, attrs=None): output = super(AutoCompleteTagInput, self).render(name, value, attrs) page_tags = Tag.objects.usage_for_model(DataSet) tag_list = simplejson.dumps([tag.name for tag in page_tags], ensure_ascii=False) return mark_safe(u'''<script type="text/javascript"> jQuery("#id_%s").autocomplete(%s, { width: 150, max: 10, highlight: false, scroll: true, scrollHeight: 100, matchContains: true, autoFill: true }); </script>''' % (name, tag_list,)) + output What I'm proposing is that if someone uses a <div class=".lazy-js">...</div> with some css (.lazy-js { display: none; }) and some javascript (jQuery('.lazy-js').each(function(index) { eval(jQuery(this).text()); }), you can effectively force all javascript to load at the end of page load: class AutoCompleteTagInput(forms.TextInput): class Media: css = { 'all': ('css/jquery.autocomplete.css', ) } js = ( 'js/jquery.bgiframe.js', 'js/jquery.ajaxQueue.js', 'js/jquery.autocomplete.js', ) def render(self, name, value, attrs=None): output = super(AutoCompleteTagInput, self).render(name, value, attrs) page_tags = Tag.objects.usage_for_model(DataSet) tag_list = simplejson.dumps([tag.name for tag in page_tags], ensure_ascii=False) return mark_safe(u'''<div class="lazy-js"> jQuery("#id_%s").autocomplete(%s, { width: 150, max: 10, highlight: false, scroll: true, scrollHeight: 100, matchContains: true, autoFill: true }); </div>''' % (name, tag_list,)) + output Nevermind all the details of my specific implementation (the specific media involved), I'm looking for a consensus on whether the method of using lazy-loaded javascript through hidden a hidden tags can pose issues whether security or other related? One of the most convenient parts about this is that it follows the DRY principle rather well IMO because you don't need to hack up a specific lazy-load for each instance in the page. It just "works". UPDATE: I'm not sure if django has the ability to queue things (via fancy template inheritance or something?) to be output just before the end of the </body>?

    Read the article

  • NHibernate Pitfalls: Lazy Scalar Properties Must Be Auto

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports lazy properties not just for associations (many to one, one to one, one to many, many to many) but also for scalar properties. This allows, for example, only loading a potentially large BLOB or CLOB from the database if and when it is necessary, that is, when the property is actually accessed. In order for this to work, other than having to be declared virtual, the property can’t have an explicitly declared backing field, it must be an auto property: 1: public virtual String MyLongTextProperty 2: { 3: get; 4: set; 5: } 6:  7: public virtual Byte [] MyLongPictureProperty 8: { 9: get; 10: set; 11: } All lazy scalar properties are retrieved at the same time, when one of them is accessed.

    Read the article

  • Creating a Lazy Sequence of Directory Descendants in C#

    My dear friend Craig Andera posted an implementation of a function that descends into a directory in a "lazy" manner, i.e. you get the first descendant back right away and not after all descendants have been calculated. His implementation was in Clojure, a Lisp variant that runs on the Java VM: (import [java.io File])(defn dir-descendants [dir]  (let [children (.listFiles (File. dir))]    (lazy-cat      (map (memfn getPath) (filter (memfn isFile) children))...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Stop lazy loading or skip loading a property in NHibernate? Proxy cannot be serialized through WCF

    - by HelloSam
    Consider I have a parent, child relationship class and mapping. I am using NHibernate to read the object from the database, and intended to use WCF to send the object across the wire. Goal For reading the parent object, I want to selectively, at different execution path, decide when I would want to load the child object. Because I don't want to read more than what I needed. Those partially loaded object must be able to sent through WCF. When I mean I don't load it, neither side will access such property. Problem When such partially loaded object is being sent through WCF, as those property is marked as [DataContract], it cannot be serialized as the property is lazy load proxy instead of real known type. What I want to archive, or solution that I can think of lazy=false or lazy=true doesn't work. Former will eagerly fetch all the relationships, latter will create a proxy. But I want nothing instead - a null would be the best. I don't need lazy load. I hope to get a null for those references that I don't want to fetch. A null, but not just a proxy. This will makes WCF happy, and waste less time to have a lazy-load proxy constructed. Like could I have a null proxy factory? -OR- Or making WCF ignoring those property that's a proxy instead of real. I tried the IDataContractSurrogate solution, but only parent is passed to GetObjectToSerialize, I never observe an proxy being passed through GetObjectToSerialize, leaving no chance to un-proxy it. Edit After reading the comments, more surfing on the Internet... It seems to me that DTO would shift major part of the computation to the server side. But for the project I am working on, 50% of time the client is "smarter" than the server and the server is more like a data store with validation and verification. Though I agree the server is not exactly dumb - I have to decide when to fetch the extra references already, and DTO will make this very explicit. Maybe I should just take the pain. I didn't know http://automapper.codeplex.com/ before, this motivates me a little more to take the pain. On the other hand, I found http://trentacular.com/2009/08/how-to-use-nhibernate-lazy-initializing-proxies-with-web-services-or-wcf/, which seems to be working with IDataContractSurrogate.GetObjectToSerialize.

    Read the article

  • Lazy coding is fun

    - by Anthony Trudeau
    Every once in awhile I get the opportunity to write an application that is important enough to do, but not important enough to do the right way -- meaning standards, best practices, good architecture, et al.  I call it lazy coding.  The industry calls it RAD (rapid application development). I started on the conversion tool at the end of last week.  It will convert our legacy data to a completely new system which I'm working on piece by piece.  It will be used in the future, but only the new parts because it'll only be necessary to convert the individual pieces of the data once.  It was the perfect opportunity to just whip something together, but it was still functional unlike a prototype or proof of concept.  Although I would never write an application like this for a customer (internal or external) this methodology (if you can call it that) works great for something like this. I wouldn't be surprised if I get flamed for equating RAD to lazy coding or lacking standards, best practice, or good architecture.  Unfortunately, it fits in the current usage.  Although, it's possible to create a good, maintainable application using the RAD methodology, it's just too ripe for abuse and requires too much discipline for someone let alone a team to do right. Sometimes it's just fun to throw caution to the wind and start slamming code.

    Read the article

  • what's the alternative to readonlycollection when using lazy="extra"?

    - by Kunjan
    I am trying to use lazy="extra" for the child collection of Trades I have on my Client object. The trades is an Iset<Trade Trades, exposed as ReadOnlyCollection<Trade because I do not want anyone to modify the collection directly. As a result, I have added AddTrade and RemoveTrade methods. Now I have a Client Search page where I need to show the Trade Count. and on the Client details page I have a tab where I need to show all the trades for the Client in paged gridview. What I want to achieve is, for the search when I say on the client object as client.Trades.Count, nHibernate should only fire a select count(*) query. Hence I am using lazy="extra". But because I am using a ReadOnlyCollection, nHibernate fires a count query & a separate query to load the child collection trades completely. Also, I cannot include the Trades in my initial search request as this would disturb the paging because a counterparty can have n trades which would result in n rows, when I am searching clients only. So the child collections have to be loaded lazily. The second problem is that on the client details page -- Trades grid view, I have enabled paging for performance reasons. But by nature nHibernate loads the entire collection of trades as the user goes from one page to another. Ideally I want to control this by getting only trades specific to the page the user is on. How can I achieve this? I came across this very good article. http://stackoverflow.com/questions/876976/implementing-ipagedlistt-on-my-models-using-nhibernate But I am not sure if this will work for me, as lazy=extra currently doesnt work as expected with the ReadOnlyCollection. So, if I went ahead and implemented the solution this way and further enhanced it by making the List/Set Immutable, will lazy=extra give me the same problem as with ReadOnlyCollections?

    Read the article

  • Any way to define getters for lazy variables in Javascript arrays?

    - by LLer
    I'm trying to add elements to an array that are lazy-evaluated. This means that the value for them will not be calculated or known until they are accessed. This is like a previous question I asked but for objects. What I ended up doing for objects was Object.prototype.lazy = function(var_name, value_function) { this.__defineGetter__(var_name, function() { var saved_value = value_function(); this.__defineGetter__(var_name, function() { return saved_value; }); return saved_value; }); } lazy('exampleField', function() { // the code that returns the value I want }); But I haven't figured out a way to do it for real Arrays. Arrays don't have setters like that. You could push a function to an array, but you'd have to call it as a function for it to return the object you really want. What I'm doing right now is I created an object that I treat as an array. Object.prototype.lazy_push = function(value_function) { if(!this.length) this.length = 0; this.lazy(this.length++, value_function); } So what I want to know is, is there a way to do this while still doing it on an array and not a fake array?

    Read the article

  • Lazy Processing of Streams

    - by Giorgio
    I have the following problem scenario: I have a text file and I have to read it and split it into lines. Some lines might need to be dropped (according to criteria that are not fixed). The lines that are not dropped must be parsed into some predefined records. Records that are not valid must be dropped. Duplicate records may exist and, in such a case, they are consecutive. If duplicate / multiple records exist, only one item should be kept. The remaining records should be grouped according to the value contained in one field; all records belonging to the same group appear one after another (e.g. AAAABBBBCCDEEEFF and so on). The records of each group should be numbered (1, 2, 3, 4, ...). For each group the numbering starts from 1. The records must then be saved somewhere / consumed in the same order as they were produced. I have to implement this in Java or C++. My first idea was to define functions / methods like: One method to get all the lines from the file. One method to filter out the unwanted lines. One method to parse the filtered lines into valid records. One method to remove duplicate records. One method to group records and number them. The problem is that the data I am going to read can be too big and might not fit into main memory: so I cannot just construct all these lists and apply my functions one after the other. On the other hand, I think I do not need to fit all the data in main memory at once because once a record has been consumed all its underlying data (basically the lines of text between the previous record and the current record, and the record itself) can be disposed of. With the little knowledge I have of Haskell I have immediately thought about some kind of lazy evaluation, in which instead of applying functions to lists that have been completely computed, I have different streams of data that are built on top of each other and, at each moment, only the needed portion of each stream is materialized in main memory. But I have to implement this in Java or C++. So my question is which design pattern or other technique can allow me to implement this lazy processing of streams in one of these languages.

    Read the article

  • In Haskell, will calling length on a Lazy ByteString force the entire string into memory?

    - by me2
    I am reading a large data stream using lazy bytestrings, and want to know if at least X more bytes is available while parsing it. That is, I want to know if the bytestring is at least X bytes long. Will calling length on it result in the entire stream getting loaded, hence defeating the purpose of using the lazy bytestring? If yes, then the followup would be: How to tell if it has at least X bytes without loading the entire stream? EDIT: Originally I asked in the context of reading files but understand that there are better ways to determine filesize. Te ultimate solution I need however should not depend on the lazy bytestring source.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >