Monday, April 25, 2011

Disabling the VB background compiler in VS2008

Does anyone know how to disable the background compiler for VB in VS2008?

For my sins I have to work on a large VB.NET project and it often locks up for 20 seconds at a time whilst doing the very helpful background compilation which is extremely frustrating.

I'd rather work blind between compiles and be able to do some work.

From stackoverflow
  • No there is no way to disable the background compiler.

    Have you installed Visual Studio 2008 SP1. There were several bugs we fixed in the RTM version of VS 2008 which can cause the IDE to hang under certain circumstances.

    We take issues with the background compiler very seriously. If you can give us a repro of the problem it will definitely be investigated. If you can produce such a repro or even send us a memory dump when the IDE is locked please file a bug on Connect: https://connect.microsoft.com/VisualStudio

    A couple of other steps you can take. Do you have any Add-ins installed in VS? If so try uninstalling them 1 at a time. I've seen several cases where 3rd party add-ins caused lock ups in the IDE which were completely unrelated to the C#/VB framework.

    Garry Shutler : I have got VS fully updated. The only add-ins I have installed are Resharper, Gallio and Test-Driven.NET. I have tried running native as I had read about add-ins causing problems and still came across the same problem. I'm using MSTest against a .NETCF 3.5 solution to throw some more into the mix.
    Garry Shutler : I will see if I can find a way to consistently reproduce it but I've only found it on this large solution and I don't think I'd be able to provide you with our source. How would I go about giving you a memory dump from when it's hanging?
    Garry Shutler : Also, do you know what the reasoning behind not providing a way to disable the background compiler? I know it's useful most the time, but just being able to switch it off would be very useful for me right now.
    JaredPar : @Garry, the majority of the IDE features depend on the result of the background compiler. Turning it off would effectively disable the majority of the IDE.
  • I have run into this very same problem with one of my forms that is very control intensive. It takes me a minute to change properties. All the other forms in the solution are pretty snappy.

    The background compiler is now no longer a help and now an active hindrance to my productivity!

    I'm not convinced that the IDE requires the background compiler to function, given that the C# IDE provides all the same features without a background compiler!

    Or can you at least investigate perhaps providing some attributes that can be sprinkled in the code saying something like 'Code in this method is OK. Don't look at it'

Is there an XML literal add-in for C# which can convert an XML literal to a C# object?

Is there an XML literal add-in for C# which can convert an XML literal to a C# object?

From stackoverflow

sIFR load before rest of page?

Hiya,

Is it possible to have sIFR "preload" or load before the rest of the page content? At present it is the last thing to load (due to the text position) and as it's quite an obvious part of the page I get a huge mash-up of text replacement all in a quick flurry which is not very appealing.

It looks like the site is having an epileptic fit. Once loaded, all is fine though :)

Any work-arounds to the load-fitting?

Cheers Hugh

From stackoverflow
  • If I understand the way sIFR works, you need to have created the heading in the DOM before attempting to change it. To be honest, every site I've been to that uses sIFR has that slight flip on loading.

    The answer then in my opinion, is no. I stand under correction though.

    hfidgen : I don't mind the way the text is replaced per se, but i'd just like to have it replaced all in one go rather than word by word, movie by movie. It creates quite a nasty effect. I've experimented with hiding the html text on page load, but you still get "flicker" as all the movies are rendered.
    Raithlin : Have you experimented with the various different libraries that implement sIFR?
    hfidgen : No, not yet actually- I just chose the latest build. Is there an appreciable difference in the way they operate?
    Raithlin : Ha, therein lies the dilemma. I'm not sure, but there are a few different approaches out there. Perhaps one might work better for you.
  • There are a two separate issues here:

    1. Replacing the elements as soon as possible
    2. Making the replacement as painless as possible

    For #1, sIFR by default replaces the elements on document load. However, to make this work in Safari, check out http://wiki.novemberborn.net/sifr3/DetectingCSSLoad.

    For #2, the problem, depending on the font used in Flash, is that the dimensions of the text are different from the HTML text. Check out http://wiki.novemberborn.net/sifr3/Ratio+Calculation to help lessen vertical jumpiness. You may need to tune the letter-spacing of the HTML text to lessen horizontal jumpiness.

    hfidgen : Hmm I can't get it working - the stutter/jitter bug is still too marked. I think the problem is that there are so many different font sizes in the tag cloud that it's extremely hard to adjust it all to fit properly, if I take the "tunes" out, it's even worse. I'll keep playing though ^^
    Mark Wubben : sIFR in a tag cloud? Sounds like a bad idea…

Problem with large solutions and service factory

My team is developing WCF services in Visual Studio 2008 SP1 with the Service Factory Modeling Edition. The problem is that we have so many services to develop and we've put everything in the same solution.

250 projects later, the solution barely loads and adding to it is nearly impossible. We thought it would be good to split out every service into its own solution, but the service factory stuff effectively prevents us from doing that.

We are generating code from our model project into our other projects, but if we try to use multiple solutions, we can't reference the model project because it can't maintain the project mappings it needs in order to generate to the proper location. And we use a couple shared data contracts in our Model Project, so splitting the model project up doesn't seem to make sense either.

We have so many projects now that we can't really turn back and not use the service factory method of doing everything.

What should we do?

From stackoverflow
  • At this point you should break up your 250 projects into groups and create a solution for each of them. My recomendation is to use ~25 projects per solution. Use these mini-solutions for your day to day editting.

    It is still possible to do a full build of the overall solution via msbuild and the command line. But VS was not meant to handle so many projects at the sametime.

    : As I explain in the question, the service factory prevents us from splitting out the projects into various solutions. Do you know of a way to get around that problem?
  • I'm surprised to hear you say this. I used the Service Factory in my previous job, and we created a separate solution for each suite of services. In each solution, we created one or more models in the model project.

    I recommend that you experiment by creating a couple of new SF solutions, adding a couple of models and generating code. See if that causes any problems.

    Have you discussed this or created an issue on CodePlex?

  • I agree with John Saunders. Keep them small. Also, keep a Continuous Integration env running to keep track of your mess-ups during development.

Show Firefox tab tooltips faster

How can I make the tootip/flyover of the tabs appear faster? There is too much reaction time, it takes ages to look through many of them.

I have most of the time 100 tabs open in Firefox (I am using the tab mix plus addon - "tmp").

To see what's in the different browser windows I do not activate them, but I just move the mouse over the tabs.

After some milliseconds a tooltip/flyover appears (a little box at the mouse pointer is drawn above everything below) and it contains information from the header of the web page that belongs to the tab. But there is a pause of some milliseconds before they are shown.

If there is not a specific about:config variable I would also be interested how to change firefox code (as I assume this is not built into tmp, I didn't find it in the options)

I do not use the tmp feature "select tab by pointing after xxx ms", which could probably interfere.

Thank You

Karl

From stackoverflow
  • The tooltip delay variable isn't in Firefox's about:config because it is a system-wide variable. If you are using OS X you can change it using these commands in terminal:

    // make the change global (applies to all apps)
    defaults write -g NSInitialToolTipDelay -int 500 
    
    // just for firefox
    defaults write org.mozilla.firefox NSInitialToolTipDelay -int 500
    

    I don't know how this can be done under windows. (maybe a registry key or something

    EDIT: I just found this / wikipedia. Maybe you can give it a try?

    Karl Thorwald : Thank you, it is really an insight for me that this setting is system-wide. If no one tells me the registry setting I will have to install the powertoys/tweakui, although I'd prefer to do it myself
  • I believe that Tweak UI from Microsoft PowerToys has a setting to change this on Windows. Look for the download on the right of the page about halfway down.

jquery validation plugin not working in modalbox

i am trying to validate fields in modalbox however its not working below is my validation code

$("#formapplication").validate({
rules: {
  tb_name:{ required: true },
  tb_url: {required: true},
  tb_tag: {required: true},
  tb_desc: {required: true},
  tb_catg: {required: true}
  },
messages:{
  tb_name:{ required: "Please Enter Full name" },
  tb_url: {required: "Please Enter URL"},
  tb_tag: {required: "Please Enter Tag."},
  tb_desc: {required: "Please Enter Description."},
  tb_catg: {required: "Please Select Category."}
  }
 });

jquery validation plugin support modalbox but its simple html i write on same page not calling using ajax any idea pelase help.

below is xhtml

<div id="submitapplication" style="display:none">
<form action="" id="formapplication" name="formapplication" method="post">
<div class="submitapplicationbox">
<label>Name<input type="text" name="tb_name" id="tb_name" /></label>
<label>Url<input type="text" name="tb_url" id="tb_url" /></label>
<label>Tags<input type="text" name="tb_tag" id="tb_tag" /></label>
<label>Category<select name="select" id="tb_catg">
  <option value=""></option>
  </select></label>
<label>Description
<textarea cols="" rows="" name="tb_desc" id="tb_desc" ></textarea></label>
</div>
<div class="twiteraccountinfobox">
<label>Name<input type="text" name="tb_twaccount" id="tb_twaccount" /></label>
<div style="margin-top:20px;"><input type="button" id="submitapp" value="Submit Application" /></div>
<div id="response" style="display:none;"></div>
</div>

From stackoverflow
  • Ah, first off, add a # to your form action so it's form action="#". The # doesn't fix it, but I have run into IE issues before without a hash in forms.

    Also, try adding a line underneath your validation:

    $("#formapplication").valid();
    
    Yasir : Thanks Steerpike acutally i was missing class required on all my input
    Steerpike : That's perculiar, as between your methodology and the documentation I had presumed that was intended behaviour. I assumed you were using the 'rules' option to bypass the class required
    Yasir : how i can use rules to bypass the class required ? would you please tell me i don't know i did't change rules but add required class to markup n it start woriking
  • i was missting class required on all my inputs that i am using for validation

    <input type="text" id="tb_name" class="required" />
    
    1. First, as Seb said, you need quotes around your field names.
    2. Second, as I understand the rules and messages hashes from the documentation, you need to refer to elements by the the name attribute, not the id attribute. So instead of "tb_catg": {required: true} I think you want "select": {required: true} since your HTML says <select name="select" id="tb_catg">

using hyperlink column in gridview and getting 'does not exist in the current context' error in page_load

HI, I have a HyperLink column in a gridview that when clicked should navigate the user to another page. I pass parameters to the page using a querystring. I am implemeting this action in the grid's onrowdatabound event. here is the code:

            HyperLink btnDetails = (HyperLink)ea.Row.FindControl("btnDetails");
            btnDetails.NavigateUrl = "ManageFlaggedSecurities.aspx?portfolioID=" + obPortfolioId.ToString() + "&testID=" + obTstId.ToString();

I can set a breakpoint in my page_load event of the ManageFlaggedSecurities page but when I want to check the values of some string parameters i set I get 'does not exist in the current context' on the variables. I even tried something simple like

string strTest = "testing";

and got the error. What am I doing wrong?

Mike

From stackoverflow
  • It sounds like you are trying to access variables declared inside the event handler while having a break point on Page_Load, hence having them out of scope, or trying to access variables that were declared in the caller up the stack.

    Show some code...

    MikeD : protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string strPortID = "testing 1"; string strTestID = "testing 2";
    Ruslan : Well this looks normal. And you are saying that if you set a break point on strPortID = "testing 1", it stops there, but the debugger won't show its value in the watch or quick view?
    MikeD : I think you are right about breaking in page_load and trying to view local vars defined in page_load in the immediate window. Codes working fine - I just can't debug at that point.
  • Read this

    LinkButton in GridView and QueryString Parameters to pass variable

Why does ASP.NET re-compile (re-JIT) everything when only one thing changes?

I have an ASP.NET 2.0 application (installed on IIS 6.0 from an MSI) which was compiled as a "web site", and precompiled/packaged using a web deployment project, in Visual Studio 2005. (I have put in a request to the developers to consider changing to a web application for the next version, but it won't change for this version).

Whenever the application is recycled (e.g. a change is made to the web.config), on first hit, ASP.NET JITs the application. As part of this, it takes all the assemblies required for the login page and compiles them into native code in the Temporary ASP.NET Files 'assembly\dl3' directory, which takes between 20 and 60 seconds. This only happens on a recycle, which happens infrequently — but when it does, it causes the page to take much longer to load, and I believe it may be possible to optimize this.

There appear to be 122 DLLs that it needs to consider, some of which are the precompiled code-behind, others are third party components for the web site (for example, NHibernate.dll, reporting components, etc.)

Why does it recompile/re-JIT everything? Why does it not detect that most of the assemblies have not changed, and not attempt to change them? Can I prove it's not batch compilation that is causing the problem? (I have <compilation debug="false"> set in the web.config.)

Other questions suggest NGEN might be useful but I read it's not possible to use it on ASP.NET 1.x; we are using 2.0 and I can't find a clean answer either way.

From stackoverflow
  • Are you running IIS? I'm fairly certain that if you restart your site in IIS it will pick up any changes to configs without copying the dlls.

    crb : Yes, the application is running under IIS 6.0. The action of changing the config causes it to re-copy all the DLLs; I'm not sure if you make the change with IIS stopped, what the output is.
    Matt Grande : Hmm, really. Well then, nevermind. (I have very little IIS experience, and have only used IIS7)
  • It's strange that only copying the dll takes 20 seconds. I would suggest to do another check and make sure where the bottleneck is.

    crb : It's not one DLL, it's 122 of them. 26MB worth. That will always take some time; my point was I'd rather not do it if they have not changed!
    Albert : In a standard HD 26MB should be copied in 2-3 seconds. I guess the problem is the pre-compilation of the application and all the initialization code you may have in application startup.
    crb : You're right, it did copy the directory in about that time. However, I can't tell what else it is doing at the time, from anything other than the Process Monitor output, so I'm interested in other ideas...
    Albert : I don't think you can do much about it, unless you have some heavy code in Application_Start() and you can improve it...
  • You may be able to improve your recycle time by installing common DLLs that change infrequently -- such as NHibernate or reporting tools -- into the GAC. That should prevent them from being re-jitted.

    How to: Install an Assembly into the Global Assembly Cache

  • From my personal experience slow recycle is often caused by NHibernate/ActiveRecord if you have lots of entities. See http://nhforge.org/blogs/nhibernate/archive/2009/03/13/an-improvement-on-sessionfactory-initialization.aspx for explanation + possible solution.

    crb : Nice find, +1. I'm trying to find a patch for NH (we don't use Castle) to see if we can get the gain here also. Might you happen to have one?
    felixg : Unfortunately no, but I'll try to add it to Fluent NHibernate soon. No promises though.
    crb : Heh. All these fixes in newer NH patterns that I can't use in the old version of our commercial product. I much prefer the OSS quick-update world :)
  • How can you be certain that everything is in the proper state without recycling/resetting (or whatever happens) the AppDomain? Imaging that you have something in application start (global.asax) which sets the value of a static field based on a config value. Unless you reset the entire AppDomain you cannot be sure.

    Another reason: There is no way to unload a .NET dll once its loaded, so you have to recreate the app domain when something is updated.

Why does ant think I have an old version of Java?

I am trying to build Groovy from source (on RH Linux) using ant, but for some reason it thinks that my Java version is 1.4, and not 1.6, and thus it won't compile. The offending lines seem to be

<condition property="groovy.build.vm5">
    <not>
        <contains string="${ant.java.version}" substring="1.4"/>
    </not>
</condition>

in build.xml.

When I type javac -version on the command line, it displays "javac 1.6.0_11". Any ideas?

From stackoverflow
  • Check the value of the environment variables JDK_HOME and JAVA_HOME.

    EDIT: "which java" will tell you which Java you're getting when you run java from the command line. If this tells you, for example, that you're getting "/usr/lib/jvm/java-6-sun/bin/java", you can set "JAVA_HOME" to "/usr/lib/jvm/java-6-sun"

    Eyvind : I don't have those. Suppose I could add them, if they really are needed.
    Aaron Digulla : Do that. This way, you can be sure which java version ant will pick up.
    Aaron Digulla : Don't forget to look into .antrc!
  • I would check PATH environment variable.

    What do you get when you on a clean shell (recently started) execute:

    $ java -version

    Ant probably thinks you are trying to user OpenJDK's JVM and compiler (I think it comes installed with RH). Try uninstalling that too.

    Eyvind : java -version prints java version "1.6.0_11" Java(TM) SE Runtime Environment (build 1.6.0_11-b03) Java HotSpot(TM) 64-Bit Server VM (build 11.0-b16, mixed mode) I cannot uninstall anything, as this is a computer provided by the faculty
    Leonel : Wrong. Ant does not care about $PATH, instead it uses $JAVA_HOME to find the compiler and VM executables. If $JAVA_HOME is empty, it will guess the executables from the VM that is running Ant.
  • The answer of Jon Bright hints in a good direction: Possibly your installation of ant uses another java-version than the one you access via 'java -version'. This is influenced by the environment-variables JDK_HOME and JAVA_HOME.

    EDIT: If these variables are not present, then ant should find the Java from the installation that called ant. But if you set these variables, ant will pick these. So setting this variables to the installation of JDK1.6 should be worth a try. On Linux your Java could be on a subdirectory of /usr/lib/jvm.

    Eyvind : As i wrote in a comment to Jon as well: those variables are not present in my system. I guess I could set them, though. What would be the correct values? Just "/local/bin/java"?
    Mnementh : If these variables are not present, then ant should find the Java from the installation that called ant. But if you set these variables, ant will pick these. So setting this variables to the installation of JDK1.6 should be woth a try. On Linux your Java could be on a subdirectory of /usr/lib/jvm.

What well-architectured weblog package(s) do you recommend?

I'm looking for some weblog software to use/extend, but all the ones I've looked at so far are terribly written - attempting to work with them is far too effortful and depressing.

I'm looking for something that is well architectured and easy to change - modular code, distinct Model-View-Controller layers, sensible data structure, and so on.

The key is that the core engine must be easily modifiable - I am not looking for software which might have lots of plugins if the core code is terrible.

Also, please only recommend software if you are familiar with the source, and do not simply post what you happen to use for your own blog.

It must be Free Software / Open-Source, and runnable via Linux on Apache HTTP or Tomcat, but otherwise language can be anything sensible.


Whilst I can build my own blog software, I'd prefer to hit the ground running with an existing package, rather than spending time re-inventing the wheel.
(Assuming, that is, that there are any suitable existing wheels!)

From stackoverflow
  • Django is a web applications framework.

    The tutorial is a blog application -- feel free to start there and roll your own.

    There are sites like Django Pluggables and Django-Apps that have reusable Django apps available.

    Peter Boughton : I'm not looking to roll my own (unless I'm forced to), I want to 'hit the ground running'. Also, the tutorial looks to be a poll app, not a blog?
    Steve Claridge : I have a problem with all these "create a blog in 20 mins" tutorials. What comes out after 20 mins is nothing like a blog - it's simply reading a few fields from a DB and putting them onto a page. Still, nice in 20 mins but it is not a blog.
    S.Lott : Keep reading. More importantly keep looking at the Django community projects. Much of what you want has already been done and the source is easy to work with.
    Peter Boughton : Do you know, specifically, that there are Django blogs with good structure, or is this more of a general recommendation/guess that there might be some?
    Peter Boughton : I've gone and looked at a few of them, and whilst they're not as painful as many of what I've looked at already, I haven't found any that come close to making me think "yay, a developer who knows what they're doing!" :(
    S.Lott : Since "good structure" is undefined (and possibly undefinable) I can only say "no" -- nothing you are likely to call "good". However, since Django is so easy to work with, you can write something that you would call "good".
    Peter Boughton : Well yeah, good structure can be a matter of opinion, but there are plenty of opinionated developers here. ;) And I didn't want to be too specific/restrictive for fear of limiting answers (heh). ...
    Peter Boughton : If I'm writing it myself, I'll use what I'm most familiar with - but it's generatelly easier to learn syntax with good structure than it is to forge structure from spaghetti. ...
    Peter Boughton : As a quick summary, I want a good database; sensible variable & method names; a UI layer distinct from the logic; good decoupling, etc. But I'll update the question later to give more details on what I consider 'good'. (I hate this dumb comment character limit!)
    Amit Kumar : I don't understand why this post got -2. I upped it by 1.
  • Zine seems to be coming together quite nicely.

    Wadih M. : That Zine project looks a bit like WordPress
  • I like Typo. It's a Rails app. The source is clean and easy to read (once you figure out the Rails directory structure) and it has some of the extras like comment spam prevention that many of the smaller packages don't.

    Rails deployment used to be fairly difficult, but in the last year it's gotten easier. It runs well on Linux with Apache and Phusion Passenger (mod_rails redone). Here's a recent SO post on best practices for Rails deployment that might be helpful.

  • Have you looked at Wordpress 2.7? It really is a fantastic piece of work. I haven't looked deep in the core but from what I've seen of the code it looks well crafted.

    I personally have moved to Django and am done with PHP though - so I personally would consider looking for a Django app since it's such a great framework.

    Django-blog is basically ok but not a full blow system.

    Peter Boughton : I have looked at Wordpress 2.7.1 It really is an absolutely dismal piece of crap. If you think it's well crafted, you need to get help! I started to write an explanation of why Wordpress is so awful, but it's so damned depressing I can't go on.
  • Take a look at BrowserCMS and watch this introduction.

    Peter Boughton : That video is sending me to sleep...

What are those pipe symbols for in Ruby?

Hi,

Apologies if this is an overly elementary question, but what are the pipe symbols for in Ruby?

I'm learning Ruby and RoR, coming from a PHP and Java background, but I keep coming across code like this:

def new 
  @post = Post.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml { render :xml => @post }
  end
end

What is the |format| part doing? What's the equivalent syntax of these pipe symbols in PHP/Java?

Thanks in advance.

From stackoverflow
  • The code between the first vertical bar and the end defines a Ruby block. The word format is a parameter to the block. The block is passed along with the method call, and the called method can yield values to the block.

    See any text on Ruby for details, this is a core feature of Ruby that you will see all the time.

    rampion : No, the code between the do and the end is a ruby block. The terms between the vertical bars are parameters to that block.
    John Topley : IIRC, the pipe syntax is borrowed from Smalltalk.
    Chuck : Yep, except Smalltalk just used one pipe.
  • The equivalent in Java would be something like

    // Prior definitions
    
    interface RespondToHandler
    {
        public void doFormatting(FormatThingummy format);
    }
    
    void respondTo(RespondToHandler)
    {
        // ...
    }
    
    // Equivalent of your quoted code
    
    respondTo(new RespondToHandler(){
        public void doFormatting(FormatThingummy format)
        {
            format.html();
            format.xml();
        }
    });
    
    Brent.Longborough : Hmmmm, no comment.
    Jon Bright : Brent, if you mean by that, that the Java version is verbose and wordy - yep, I'd agree with you. But then again, this is a less idiomatic construction in Java. Ruby uses it all the time, Java less so.
    jonnii : the format.html(); format.xml(); part would probably be more like a switch statement, as you'd be switching on the format that was requested.
  • I found a great explanation here: Rails for PHP Developers - Ruby Block Scope

  • Parameters for a block sit between the | symbols.

  • They are the variables yielded to the block.

    def this_method_takes_a_block
      yield(5)
    end
    
    this_method_takes_a_block do |num|
      puts num
    end
    

    Which outputs "5". A more arcane example:

    def this_silly_method_too(num)
      yield(num + 5)
    end
    
    this_silly_method_too(3) do |wtf|
      puts wtf + 1
    end
    

    The output is "9".

Copy constructor vs. return value optimization

In a previous question, it appeared that a plain return-by-value function always copies its return argument into the variable being assigned from it.

Is this required by the standard, or can the function be optimized by constructing the 'assigned to' variable even within the function body?

struct C { int i; double d; };

C f( int i, int d ) {
    return C(i,d); // construct _and_ copy-construct?
}

int main() {
    C c = f( 1, 2 ); 
}
From stackoverflow
  • The standard says that the copy constructor need not be used - see section 12.8/15:

    15 Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cv-unqualified type, an implementation is permitted to treat the original and the copy as two different ways of referring to the same object and not perform a copy at all, even if the class copy constructor or destructor have side effects.

    And much more in a similar vein.

    Mykola Golubyev : 12.5 in my 1998 standard is "Free store" do you refer to some else standard?
    anon : Should have been 12.8/15
  • The standard allows any level of copy omission here:

    • construct a local temporary, copy-construct it into a return value, and copy-construct the return value into the local "c". OR
    • construct a local temporary, and copy-construct that into "c". OR
    • construct "c" with the arguments "i,d"
    Mykola Golubyev : Could you provide with the section number from the standard please?
  • There's one very simple and good way to avoid such considerations completely - you can consider returning a boost::shared_ptr to the created object - it will be practically the same when it comes to usability but your object will surely not be copied unnecessarily - and it will be true also if you return it though a couple layers of function calls.

    Mykola Golubyev : it is not a good to shared_ptr std::string or std::pair or std::vector.
    xtofl : To avoid copy-construction, I could use heap i.s.o. stack storage. I know that :)/ But I wanted to know if I can trust the compiler i.e. the standard to _guarantee_ calling my copy constructor. Which I can't.
    anon : of course, the shared_pointer itself has a copy constructor
    RnR : @Mykola - why do you think it's not good? It's exactly this kind of return values that it may be very good to share_ptr the result and avoid a huge vector or a long string copied numerous times as you return it from some inner methods.
    xtofl : @Iraimbilanja: this question rose to me when the 'other' question's answers said the copy constructor would always be called on return. I doubted that. My question was a bit rhetorical, I must admit :).
  • Way not pass parameter by reference and assign result to it?

    xtofl : Or when you need multiple return values (a status and a value for instance)

How do you find the last element of an array while iterating using a foreach loop in php ?

I am writing a sql query creator using some parameters. While doing that ,I came across this problem. In java , Its very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length.

for(int i=0; i< arr.length;i++){

     boolean isLastElem = i== (arr.length -1) ? true : false;        

}

php has some different fashion. They have non integer indexes to access arrays. So you must iterate over an array using foreach loop. But it becomes very problematic when you need to take some decision (in my case to append or/and parameter while building query).

I am sure there must be some standard way of doing this.

How do you solve this problem normally in php ?

From stackoverflow
  • you can do a count().

    for ($i=0;$i<count(arr);$i++){
        $i == count(arr)-1 ? true : false;
    }
    

    or if you're looking for ONLY the last element, you can use end().

    end(arr);
    

    returns only the last element.

    and, as it turns out, you CAN index php arrays by integers. It's perfectly happy with

    arr[1];
    
  • It sounds like you want something like this:

    $numItems = count($arr);
    $i = 0;
    foreach($arr as $key=>$value) {
      if($i == $numItems) {
        echo "last index!";
      }
      $i++;
    }
    

    That being said, you don't -have- to iterate over an "array" using foreach in php.

    Vaibhav Kamble : I think I will go for this solution as it is almost similar to the code I posted. Even Jeremy's answer is well fit but I think it got little complex compared to this one. I have not ran any tests but I guess this answer shall be faster as it is not extracting array of keys.This shall have O(1) speed
    Paul Sheldrake : Shouldn't $i = 1 because Count starts at 1 and not 0?
  • You could get the value of the last key of the array using end(array_keys($array)) and compare it to the current key:

    $last_key = end(array_keys($array));
    foreach ($array as $key => $value) {
        if ($key == $last_key) {
            // last element
        } else {
            // not last element
        }
    }
    
    Patrick Daryll Glandien : +1 I agree - the other solutions rely on the array having numeric indexes.
    Richard Levasseur : In my own defense, my answer doesn't rely on the array having numeric keys :)
    OIS : string comparison is slower then integers, and not always accurate when comparing strings to integers (you should at least have used ===). Im voting this down.
  • You can still use that method with associative arrays:

    $keys = array_keys($array);
    for ($i = 0, $l = count($array); $i < $l; ++$i) {
        $key = $array[$i];
        $value = $array[$key];
        $isLastItem = ($i == ($l - 1));
        // do stuff
    }
    
    // or this way...
    
    $i = 0;
    $l = count($array);
    foreach ($array as $key => $value) {
        $isLastItem = ($i == ($l - 1));
        // do stuff
        ++$i;
    }
    
  • $toEnd = count($arr);
    foreach($arr as $key=>$value) {
      if (0 === --$toEnd) {
        echo "last index! $value";
      }
    }
    

    or the best way is probably this if you still execute the other loop code

    foreach($arr as $key=>$value) {
      //something
    }
    echo "last index! $key => $value";
    
    Sohnee : In this example, it will perform the --$toEnd in every iteration in the loop, so I would recommend moving that outside of the foreach loop so you can perform a direct comparison on an already calculated value.
    OIS : Of course it will perform the --$toEnd for every iteration, thats the point. If I moved it outside the loop, it would not work anymore.
  • You could also do something like this:

    $endKey = key(end( $elements ));
    foreach ($elements as $key => $value)
    {
         if ($key == $endKey) // -- this is the last item
         {
              // do something
         }
    
         // more code
    }
    
    OIS : end returns the value not the array, so the way you made it doesnt work. string comparison is also slower then integer.
    KOGI : You are right. it should be end($elements); $endKey = key($elements);
  • no your all wrong its this

    public boolean add(int num) {
    int index = data.length; if(index < this.count) { data[index +1] = num; return true;

  • Here's another way you could do it:

    $arr = range(1, 10);
    
    $end = end($arr);
    reset($arr);
    
    while( list($k, $v) = each($arr) )
    {
        if( $n == $end )
        {
         echo 'last!';
        }
        else
        {
         echo sprintf('%s ', $v);
        }
    }
    
  • why so complicated?

    foreach($input as $key => $value) {
        $ret .= "$value";
        if (next($input)==true) $ret .= ",";
    }
    

    This will add a , behind every value except the last one!

  • If you need to do something for every element except either the first or the last and only if there is more than one element in the array, I prefer the following solution.

    I know there are many solutions above and posted months/one year before mine, but this is something I feel is fairly elegant in its own right. The check every loop is also a boolean check as opposed to a numeric "i=(count-1)" check, which may allow for less overhead.

    The structure of the loop may feel awkward, but you can compare it to the ordering of thead (beginning), tfoot (end), tbody (current) in HTML table tags.

    $first = true;
    foreach($array as $key => $value) {
        if ($first) {
            $first = false;
            // Do what you want to do before the first element
            echo "List of key, value pairs:\n";
        } else {
            // Do what you want to do at the end of every element
            // except the last, assuming the list has more than one element
            echo "\n";
        }
        // Do what you want to do for the current element
        echo $key . ' => ' . $value;
    }
    

    For instance, in web development terms, if you want to add a border-bottom to every element except the last in an unordered list (ul), then you can instead add a border-top to every element except the first (the CSS :first-child, supported by IE7+ and Firefox/Webkit supports this logic, whereas :last-child is not supported by IE7).

    You can feel free to reuse the $first variable for each and every nested loop as well and things will work just fine since every loop makes $first false during the first process of the first iteration (so breaks/exceptions won't cause issues).

    $first = true;
    foreach($array as $key => $subArray) {
        if ($first) {
            $string = "List of key => value array pairs:\n";
            $first = false;
        } else {
            echo "\n";
        }
    
        $string .= $key . '=>(';
        $first = true;
        foreach($subArray as $key => $value) {
            if ($first) {
                $first = false;
            } else {
                $string .= ', ';
            }
            $string .= $key . '=>' . $value;
        }
        $string .= ')';
    }
    echo $string;
    

    Example output:

    List of key => value array pairs:
    key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
    key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
    key3=>(v3_key1=>v3_val1)
    
  • Hi, If I understand you, then all you need is to reverse the array and get the last element by a pop command:

       $rev_array = array_reverse($array);
    
       echo array_pop($rev_array);
    
  • How about using "end"? http://php.net/manual/en/function.end.php

Copy Constructor in C++ is called when object is returned from a function?

I understand copy constructor is called on three instances

  1. When instantiating one object and initializing it with values from another object (as in the example above).
  2. When passing an object by value.

3. When an object is returned from a function by value.

I have question with no.3 if copy constructor is called when an object value is returned, shouldn't it create problems if object is declared locally in the function.

i mean the copy constructor is a deep copy one and takes reference of an object as parameter

From stackoverflow
  • No, it calls it before the locals are destroyed. You can test this with an object that logs destruction and copy construction, or by looking at the generated assembly code.

    Kazoom : but what if the copy constructor takes reference as a parameter(deep copy), in that case it would not copy the whole object, right?
    Lou Franco : Depends on the copy constructor. The default one does a member-wise copy construct. Normally, you should implement your copy constructor to not rely on the lifetime of the object that was passed in. You don't have to deep copy, but you need to make sure shared stuff stays around.
  • It's called exactly to avoid problems. A new object serving as result is initialized from the locally-defined object, then the locally defined object is destroyed.

    In case of deep-copy user-defined constructor it's all the same. First storage is allocated for the object that will serve as result, then the copy constructor is called. It uses the passed reference to access the locally-defined object and copy what's necessary to the new object.

  • The copy is done before the called function exits, and copies the then-existing local variable into the return value.

    The called function has access to the memory the return value will occupy, even though that memory is not "in scope" when the copy is being made, it's still available.

    Kazoom : i understand that when object value is being returned, it will first call the copy constructor, but copy constructor is user defined it takes reference as a parameter ClassA(const ClassA&), in that case what would happen? what happens if u just return a reference instead of value going by ur logic
    sharptooth : If the function is declared as returning a reference returning a reference to a local variable is a big no-no to do. You will return a reference to an object that will be discarded on function return. Using this reference will likely cause problem, crushes included.
    Kazoom : yes i understand that, so when a copy constructor which is taking reference as parameter is being called when returning the value, what would happen? shouldn't it crash too?
    sharptooth : What's the problem? The function is about to return. The copy constructor is invoked. It takes a reference to the local variable. It uses this reference to copy everything into the new object that will be used as the return value.
    sharptooth : Added it to my answer.
  • According to an answer to my question, the copy constructor may be called even twice: once to copy a local object onto the return 'object', and once to copy the return object onto the variable it was assigned to.

    However, it needn't be! The compiler can optimize both copy constructions away.

Detaching entity along with referenced entities.

Ok, I am planning to develop a project using Entity Framework. While i was trying to do some R&D before i kick off implementing it, I found this problem, hope some of you people help me find a solution to it.

I have a entity named 'Person' referenced with 'Members' entity with one to many (1:N) relationship. The task would be to query Person entity along with its corresponding Members collection and pass it to the presentation layer to view, modify or delete over it and then the modified entity object will be passed back to the Model layer to attach the entity to the context and save it to the DB.

As far as I Detach/Attach w.r.t. a single entity like 'Person' and save it to the DB every thing works absolutely fine. But, when i try to query an entity (Person) with its referenced entity (Member) and detach so that i can send it to the presentation layer. I find that I get only Person entity collection and the reference Member entity collection is totally removed after detaching it from the context.

Here I am pasting my code snippet for reference:

using (GOLProfessionalEntities context = new GOLProfessionalEntities())
{
     ObjectQuery<Person> query =
        context.Person.Include("Members");

     var person = query.First();
     context.Detach(person);

     return person;
}

I would be really delighted if some one comes out with a solution to this.

Thanks in advance. -ssak32

From stackoverflow
  • I believe you need to detach each Member also:

    using (GOLProfessionalEntities context = new GOLProfessionalEntities()) { ObjectQuery query = context.Person.Include("Members");

     var person = query.First();
    
    
     while (person.Member.Count > 0)
     {
         context.Detach(person.Member.First());
     }
    
    
     context.Detach(person);
    
     return person;
    

    }

    I hope that works.

  • You could set MergeOption on ObjectQuery to NoTracking. This way Person will not be attached to the ObjectContext in the first place.

                using (GOLProfessionalEntities context = new GOLProfessionalEntities())
                {
                    ObjectQuery<Person> query =
                       context.Person.Include("Members");
                    query.MergeOption = MergeOption.NoTracking;// <--
    
                    var person = query.First();
    
                    return person;
                }
    

    I'm so late with the answer by it might help someone.

How to use XML documentation files

  1. When using an external assembly which comes with an XML documentation file, how do I get visual studio to find it?

  2. When having an XML documentation file, is there a program or xml transform file or something I can use to look at it in a nice way? Not necessarily as complex as the msdn documentation viewer thingy, but at least something nicer than the pure xml...

From stackoverflow
  • Answer to your first question: the xml should have the same name as the assembly and be right next to it. So if you have an assembly called Svish.dll then your documentation file should be Svish.xml and be in the same directory.

  • 1: you simply drop it in the same folder as the dll

    2: does it need to be persisted? For "live" use, both the VS IDE and "reflector" allow you to review the documentation (against the types/members/etc). There are tools to transform it, but I've never bothered. Sandcastle may be worth a look, but it was never nice to me ;-p

    Svish : I tried to drop it in the same folder, but it doesn't want to pick it up it seems. I still get no documentation.
    Marc Gravell : The files must be Foo.Bar.dll and Foo.Bar.xml (for example); are you sure that you are referencing the dll from that location? And are you sure it is a comments file?
    Svish : Seems like I had to restart VS for it to work... is there a command to rebuild/reread documentation or something maybe?
    Marc Gravell : Not that I know of...
  • 1) The documentation file must have the same name as the assembly name, with the added extension '.xml', and reside in the same directory as its corresponding assembly. So for example, you have an 'MyCompany.MyNamespace.dll' and a 'MyCompany.MyNamespace.dll.xml' file in the same directory.

    2) NDOC can generate some dirrent formats of documentation.

Custom HttpHandlers and different handler types.

All literature I see on creating custom handlers deals with associating an extension with a handler, e.g. if I wanted a handler for Ajax requests, I could implement the IHttHandler interface in an AjaxHandler class.

Now, to have individual instances of AjaxHandlers, e.g. DocAjaxHander, PersonAjaxHandler etc. how would I derive the base AJAX handling of my AjaxHandler class without registering each individual *.ajax page?

From stackoverflow
  • You can automatically handle AJAX request in a number of ways. Here's how to do it with a web service:

    http://www.asp.net/AJAX/Documentation/Live/Tutorials/ConsumingWebServicesWithAJAXTutorial.aspx

    ProfK : I didn't seem to me like I was asking how to handle AJAX requests. In fact, it seemed, to me, a lot like I was asking Http handlers, using a .ajax handler as an example. I don't want to be rude, but your answer has very little or nothing to with my question.
  • Well, one way to do it would be via query string params...