Search Results

Search found 1806 results on 73 pages for 'lazy evaluation'.

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

  • Understanding evaluation of expressions containing '++' and '->' operators in C.

    - by Leif Ericson
    Consider this example: struct { int num; } s, *ps; s.num = 0; ps = &s; ++ps->num; printf("%d", s.num); /* Prints 1 */ It prints 1. So I understand that it is because according to operators precedence, -> is higher than ++, so the value ps->num (which is 0) is firstly fetched and then the ++ operator operates on it, so it increments it to 1. struct { int num; } s, *ps; s.num = 0; ps = &s; ps++->num; printf("%d", s.num); /* Prints 0 */ In this example I get 0 and I don't understand why; the explanation of the first example should be the same for this example. But it seems that this expression is evaluated as follows: At first, the operator ++ operates, and it operates on ps, so it increments it to the next struct. Only then -> operates and it does nothing because it just fetches the num field of the next struct and does nothing with it. But it contradicts the precedence of operators, which says that -> have higher precedence than ++. Can someone explain this behavior? Edit: After reading two answers which refer to a C++ precedence tables which indicate that a prefix ++/-- operators have lower precedence than ->, I did some googling and came up with this link that states that this rule applies also to C itself. It fits exactly and fully explains this behavior, but I must add that the table in this link contradicts a table in my own copy of K&R ANSI C. So if you have suggestions as to which source is correct I would like to know. Thanks.

    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

  • Unsure of how to get the right evaluation order

    - by Matt Fenwick
    I'm not sure what the difference between these two pieces of code is (with respect to x), but the first one completes: $ foldr (\x y -> if x == 4 then x else x + y) 0 [1,2 .. ] 10 and the second one doesn't (at least in GHCi): $ foldr (\x (y, n) -> if x == 4 then (x, n) else (x + y, n + 1)) (0, 0) [1,2 .. ] ....... What am I doing wrong that prevents the second example from completing when it hits x == 4, as in the first one? I've tried adding bang-patterns to both the x and to the x == 4 (inside a let) but neither seems to make a difference.

    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

  • Sharepoint 2010 web application development suitability evaluation/assessment

    - by Robert Koritnik
    I would like to know what kind of applications are suitable to be developed on top of Sharepoint 2010 and which should not be built on to of it. So when to embrace/avoid Sharepoint 2010 as a development platform for new web applications. Addendum Would you as a sharepoint development specialist choose it as a platform for your next enterprise application with these characteristics: processor intensive lots of various screens for entering and managing data many complex business processes no need to change the UI (ie. reposition parts) ERP integration etc. I'm an Asp.net MVC (former web forms) developer and would like to know if usual multi-page semi complex web applications (intra/extra-net) should be built on top of Sharepoint 2010 and why (if yes or if no).

    Read the article

  • Evaluation of (de)reference operators

    - by Micha
    I have an (uncommented...) source file which I'm trying to understand. static const Map *gCurMap; static std::vector<Map> mapVec; then auto e = mapVec.end(); auto i = mapVec.begin(); while(i!=e) { // ... const Map *map = gCurMap = &(*(i++)); // ... } I don't understand what &(*(i++)) does. It does not compile when just using i++, but to me it looks the same, because I'm "incrementing" i, then I'm requesting the value at the given address and then I'm requesting the address of this value?!

    Read the article

  • NDepend Evaluation: Part 3

    - by Anthony Trudeau
    NDepend is a Visual Studio add-in designed for intense code analysis with the goal of high code quality. NDepend uses a number of metrics and aggregates the data in pleasing static and active visual reports. My evaluation of NDepend will be broken up into several different parts. In the first part of the evaluation I looked at installing the add-in.  And in the last part I went over my first impressions including an overview of the features.  In this installment I provide a little more detail on a few of the features that I really like. Dependency Matrix The dependency matrix is one of the rich visual components provided with NDepend.  At a glance it lets you know where you have coupling problems including cycles.  It does this with number indicating the weight of the dependency and a color-coding that indicates the nature of the dependency. Green and blue cells are direct dependencies (with the difference being whether the relationship is from row-to-column or column-to-row).  Black cells are the ones that you really want to know about.  These indicate that you have a cycle.  That is, type A refers to type B and type B also refers to Type A. But, that’s not the end of the story.  A handy pop-up appears when you hover over the cell in question.  It explains the color, the dependency, and provides several interesting links that will teach you more than you want to know about the dependency. You can double-click the problem cells to explode the dependency.  That will show the dependencies on a method-by-method basis allowing you to more easily target and fix the problem.  When you’re done you can click the back button on the toolbar. Dependency Graph The dependency graph is another component provided.  It’s complementary to the dependency matrix, but it isn’t as easy to identify dependency issues using the window. On a positive note, it does provide more information than the matrix. My biggest issue with the dependency graph is determining what is shown.  This was not readily obvious.  I ended up using the navigation buttons to get an acceptable view.  I would have liked to choose what I see. Once you see the types you want you can get a decent idea of coupling strength based on the width of the dependency lines.  Double-arrowed lines are problematic and are shown in red.  The size of the boxes will be related to the metric being displayed.  This is controlled using the Box Size drop-down in the toolbar.  Personally, I don’t find the size of the box to be helpful, so I change it to Constant Font. One nice thing about the display is that you can see the entire path of dependencies when you hover over a type.  This is done by color-coding the dependencies and dependants.  It would be nice if selecting the box for the type would lock the highlighting in place. I did find a perhaps unintended work-around to the color-coding.  You can lock the color-coding in by hovering over the type, right-clicking, and then clicking on the canvas area to clear the pop-up menu.  You can then do whatever with it including saving it to an image file with the color-coding. CQL NDepend uses a code query language (CQL) to work with your code just like it was a database.  CQL cannot be confused with the robustness of T-SQL or even LINQ, but it represents an impressive attempt at providing an expressive way to enumerate and interrogate your code. There are two main windows you’ll use when working with CQL.  The CQL Query Explorer allows you to define what queries (rules) are run as part of a report – I immediately unselected rules that I don’t want in my results.  The CQL Query Edit window is where you can view or author your own rules.  The explorer window is pretty self-explanatory, so I won’t mention it further other than to say that any queries you author will appear in the custom group. Authoring your own queries is really hard to screw-up.  The Intellisense-like pop-ups tell you what you can do while making composition easy.  I was able to create a query within two minutes of playing with the editor.  My query warns if any types that are interfaces don’t start with an “I”. WARN IF Count > 0 IN SELECT TYPES WHERE IsInterface AND !NameLike “I” The results from the CQL Query Edit window are immediate. That fact makes it useful for ad hoc querying.  It’s worth mentioning two things that could make the experience smoother.  First, out of habit from using Visual Studio I expect to be able to scroll and press Tab to select an item in the list (like Intellisense).  You have to press Enter when you scroll to the item you want.  Second, the commands are case-sensitive.  I don’t see a really good reason to enforce that. CQL has a lot of potential not just in enforcing code quality, but also enforcing architectural constraints that your enterprise has defined. Up Next My next update will be the final part of the evaluation.  I will summarize my experience and provide my conclusions on the NDepend add-in. ** View Part 1 of the Evaluation ** ** View Part 2 of the Evaluation ** Disclaimer: Patrick Smacchia contacted me about reviewing NDepend. I received a free license in return for sharing my experiences and talking about the capabilities of the add-in on this site. There is no expectation of a positive review elicited from the author of NDepend.

    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

  • Why is the order of evaluation for function parameters undefined in c++?

    - by kunj2aan
    The standard doesn't specify the order of evaluation of arguments with this line: The order of evaluation of arguments is unspecified. What does Better code can be generated in the absence of restrictions on expression evaluation order imply? What is the drawback in asking all the compilers to evaluate the function arguments Left to Right for example? What kinds of optimizations do compilers perform because of this undefined spec?

    Read the article

  • understanding evaluation function

    - by mish
    I am developing a chess program. And have made use of an alpha beta algorithm and a static evaluation function. I have successfully implemented both but I want to improve the evaluation function by automatically tuning the weights assigned to its features. At this point am totally confused about the policy suitable for updating the weights of the function. One policy I have in mind is to check whether a move is good or bad before updating weights but I really know how to implement it. Thus I need ideas and pseudo code please.

    Read the article

  • Software Architecture and Software Architecture Evaluation

    How many of us have worked at places where the concept of software architecture was ridiculed for wasting time and money? Even more ridiculous to them was the concept of evaluating software architecture. I think the next time that I am in this situation again, and I hope that I never am I will have to push for this methodology in the software development life cycle. I have spent way too many hours/days/months/years working poorly architected systems or systems that were just built ADHOC. This in software development must stop. I can understand why systems get like this due to overzealous sales staff, demanding management that wants everything yesterday, and project managers asking if things are done yet before the project has even started. But seriously, some time must be spent designing the applications that we write along with evaluating the architecture so that it will integrate will within the existing systems of an origination. If placed in this situation again, I will strive to gain buying from key players within the business, for example: Senior Software Engineers\Developers, Software Architects, Project Managers, Software Quality Assurance, Technical Services, Operations, and Finance in order for this idea to succeed with upper management. In order to convince these key players I will have to show them the benefits of architecture and even more benefits of evaluating software architecture on a system wide level. Benefits of Software Architecture Evaluation Places Stakeholders in the Same Room to Communicate Ensures Delivery of Detailed Quality Goals Prioritizes Conflicting Goals Requires Clear Explication Improves the Quality of Documentation Discovers Opportunities for Cross-Project Reuse Improves Architecture Practices Once I had key player buy in then and only then would I approach upper management about my plan regarding implementing the concept of software architecture and using evaluation to ensure that the software being designed is the proper architecture for the project. In addition to the benefits listed above I would also show upper management how much time is being wasted by not doing these evaluations. For example, if project X cost us Y amount, then why do we have several implementations in various forms of X and how much money and time could we have saved if we just reused the existing code base to give each system the same functionality that was already created? After this, I would mention what would happen if we had 50 instances of this situation? Then I would show them how the software architecture evaluation process would have prevented this and that the optimization could have leveraged its existing code base to increase the speed and quality of its development. References:Carnegie Mellon Software Engineering Institute (2011). Architecture Tradeoff Analysis Method from http://www.sei.cmu.edu/architecture/tools/evaluate/atam.cfm

    Read the article

  • How to write an R function that evaluates an expression within a data-frame

    - by Prasad Chalasani
    Puzzle for the R cognoscenti: Say we have a data-frame: df <- data.frame( a = 1:5, b = 1:5 ) I know we can do things like with(df, a) to get a vector of results. But how do I write a function that takes an expression (such as a or a > 3) and does the same thing inside. I.e. I want to write a function fn that takes a data-frame and an expression as arguments and returns the result of evaluating the expression "within" the data-frame as an environment. Never mind that this sounds contrived (I could just use with as above), but this is just a simplified version of a more complex function I am writing. I tried several variants ( using eval, with, envir, substitute, local, etc) but none of them work. For example if I define fn like so: fn <- function(dat, expr) { eval(expr, envir = dat) } I get this error: > fn( df, a ) Error in eval(expr, envir = dat) : object 'a' not found Clearly I am missing something subtle about environments and evaluation. Is there a way to define such a function?

    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

  • Deferred execution and eager evaluation

    - by babu M
    Hi Could you please give me an example for Deferred execution with eager evaluation in C#? I read from MSDN that deferred execution in LINQ can be implemented either with lazy or eager evaluation...i could find examples in the internet for Deferred execution with lazy evaluation ,however i could not find any example for Deferred execution with eager evaluation....please help me....its urgent... Moreover,how deferred execution differs from lazy evaluation?In my point of view,both are looking same.Could you please provide any example for this too?

    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

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