qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
154,597
<p>Note, I realize that this has been addressed <a href="https://stackoverflow.com/questions/944/unhandled-exception-handler-in-net-11">here</a>. That post discusses exception handling in .NET 1.1 while implying that there is a better solution for >.NET 2.0 so this question is specifically about the more recent .NET versions.</p> <p>I have a windows forms application which is expected to frequently and unexpectedly lose connectivity to the database, in which case it is to reset itself to its initial state.</p> <p>I am already doing error logging, retry connection, etc. through a set of decorators on my custom DBWrapper object. After that is taken care of however, I would like to let the error fall through the stack. Once it reaches the top and is unhandled I would like it to be swallowed and my ApplicationResetter.Reset() method to be executed.</p> <p>Can anyone tell me how to do this?</p> <p>If this is impossible, then is there at least a way to handle this without introducing a dependency on ApplicationResetter to every class which might receive such an error and without actually shutting down and restarting my application (which would just look ugly)?</p>
[ { "answer_id": 154626, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>caveat: not familiar with 3.5 yet, there may be a better answer ...</p>\n\n<p>...but my understanding is that by the time the event gets to the unhandled exception handler, the app is probably going to die - and if it doesn't die, it may be so corrupted that it should die anyway</p>\n\n<p>if you are already handling a db-not-there case and are letting other exceptions pass through, then the app should die as it may be unstable</p>\n" }, { "answer_id": 154656, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 1, "selected": false, "text": "<p>Perhaps the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx\" rel=\"nofollow noreferrer\">Application.ThreadException</a> event will suit your needs:</p>\n\n<pre><code>static void Main()\n{\n Application.ThreadException += Application_ThreadException;\n //...\n }\n\n static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)\n {\n // call ApplicationResetter.Reset() here\n }\n</code></pre>\n" }, { "answer_id": 154665, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 1, "selected": false, "text": "<p>There are the <code>System.Windows.Forms.Application.ThreadException</code> event and the <code>System.AppDomain.CurrentDomain.UnhandledException</code> events.</p>\n\n<p>As mentioned by Steven, these will leave your application in an unknown state. There's really no other way to do this except putting the call that could throw the exception in a try/catch block.</p>\n" }, { "answer_id": 154685, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>A pretty in-depth explanation of unhandled exceptions in the latest MSDN issue:\n<a href=\"http://msdn.microsoft.com/en-us/magazine/cc793966.aspx\" rel=\"nofollow noreferrer\">September 2008</a></p>\n" }, { "answer_id": 154792, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 1, "selected": true, "text": "<p>For Windows Forms threads (which call Application.Run()), assign a ThreadException handler at the beginning of Main(). Also, I found it was necessary to call SetUnhandledExceptionMode:</p>\n\n<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);\nApplication.ThreadException += ShowUnhandledException;\nApplication.Run(...);\n</code></pre>\n\n<p>Here is an example handler. I know it's not what you're looking for, but it shows the format of the handler. Notice that if you want the exception to be fatal, you have to explicitly call Application.Exit(). </p>\n\n<pre><code>static void ShowUnhandledException(object sender, ThreadExceptionEventArgs t)\n{\n Exception ex = t.Exception;\n try {\n // Build a message to show to the user\n bool first = true;\n string msg = string.Empty;\n for (int i = 0; i &lt; 3 &amp;&amp; ex != null; i++) {\n msg += string.Format(\"{0} {1}:\\n\\n{2}\\n\\n{3}\", \n first ? \"Unhandled \" : \"Inner exception \",\n ex.GetType().Name,\n ex.Message, \n i &lt; 2 ? ex.StackTrace : \"\");\n ex = ex.InnerException;\n first = false;\n }\n msg += \"\\n\\nAttempt to continue? (click No to exit now)\";\n\n // Show the message\n if (MessageBox.Show(msg, \"Unhandled exception\", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No)\n Application.Exit();\n } catch (Exception e2) {\n try {\n MessageBox.Show(e2.Message, \"Fatal error\", MessageBoxButtons.OK, MessageBoxIcon.Stop);\n } finally {\n Application.Exit();\n }\n }\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Note, I realize that this has been addressed [here](https://stackoverflow.com/questions/944/unhandled-exception-handler-in-net-11). That post discusses exception handling in .NET 1.1 while implying that there is a better solution for >.NET 2.0 so this question is specifically about the more recent .NET versions. I have a windows forms application which is expected to frequently and unexpectedly lose connectivity to the database, in which case it is to reset itself to its initial state. I am already doing error logging, retry connection, etc. through a set of decorators on my custom DBWrapper object. After that is taken care of however, I would like to let the error fall through the stack. Once it reaches the top and is unhandled I would like it to be swallowed and my ApplicationResetter.Reset() method to be executed. Can anyone tell me how to do this? If this is impossible, then is there at least a way to handle this without introducing a dependency on ApplicationResetter to every class which might receive such an error and without actually shutting down and restarting my application (which would just look ugly)?
For Windows Forms threads (which call Application.Run()), assign a ThreadException handler at the beginning of Main(). Also, I found it was necessary to call SetUnhandledExceptionMode: ``` Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic); Application.ThreadException += ShowUnhandledException; Application.Run(...); ``` Here is an example handler. I know it's not what you're looking for, but it shows the format of the handler. Notice that if you want the exception to be fatal, you have to explicitly call Application.Exit(). ``` static void ShowUnhandledException(object sender, ThreadExceptionEventArgs t) { Exception ex = t.Exception; try { // Build a message to show to the user bool first = true; string msg = string.Empty; for (int i = 0; i < 3 && ex != null; i++) { msg += string.Format("{0} {1}:\n\n{2}\n\n{3}", first ? "Unhandled " : "Inner exception ", ex.GetType().Name, ex.Message, i < 2 ? ex.StackTrace : ""); ex = ex.InnerException; first = false; } msg += "\n\nAttempt to continue? (click No to exit now)"; // Show the message if (MessageBox.Show(msg, "Unhandled exception", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No) Application.Exit(); } catch (Exception e2) { try { MessageBox.Show(e2.Message, "Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { Application.Exit(); } } } ```
154,625
<p>I've noticed that sometimes wrapper scripts will use <code>${1:+"$@"}</code> for the parameters rather than just <code>"$@"</code>.</p> <p>For example, <a href="http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh" rel="noreferrer">http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh</a> uses</p> <pre><code>exec "$binary" $opts ${1:+"$@"} </code></pre> <p>Can anyone break <code>${1:+"$@"}</code> down into English and explain why it would be an advantage over plain <code>"$@"</code>?</p>
[ { "answer_id": 154637, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>From the bash man page:</p>\n\n<pre><code> ${parameter:+word}\n Use Alternate Value. If parameter is null or unset, nothing is\n substituted, otherwise the expansion of word is substituted.\n</code></pre>\n\n<p>So, <code>\"$@\"</code> is substituted unless <code>$1</code> is unset. I can't see why they couldn't have just used <code>\"$@\"</code>.</p>\n" }, { "answer_id": 155044, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 6, "selected": true, "text": "<p>'Hysterical Raisins', aka Historical Reasons.</p>\n\n<p>The explanation from JesperE (or the Bash man page on <a href=\"https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion\" rel=\"noreferrer\">shell parameter expansion</a>) is accurate for what it does:</p>\n\n<ul>\n<li>If <code>$1</code> exists and is not an empty string, then substitute the quoted list of arguments.</li>\n</ul>\n\n<p>Once upon 20 or so years ago, some broken minor variants of the Bourne Shell substituted an empty string <code>\"\"</code> for <code>\"$@\"</code> if there were no arguments, instead of the correct, current behaviour of substituting nothing. Whether any such systems are still in use is open to debate.</p>\n\n<p>[Hmm: that expansion would not work correctly for:</p>\n\n<pre><code>command '' arg2 arg3 ...\n</code></pre>\n\n<p>In this context, the correct notation is:</p>\n\n<pre><code>${1+\"$@\"}\n</code></pre>\n\n<p>This works correctly whether <code>$1</code> is an empty argument or not. So, someone remembered the notation incorrectly, accidentally introducing a bug.]</p>\n" }, { "answer_id": 1601852, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 2, "selected": false, "text": "<p>To quote the relevant portion of <code>man bash</code> for the information that <strong>Jonathan Leffler</strong> referred to in his comment:</p>\n\n<blockquote>\n <p>When not performing substring expansion, bash tests for a parameter that is <em>unset or null</em>; <strong>omitting the colon</strong> results in a test <em>only</em> for a parameter that is <em>unset</em>.</p>\n</blockquote>\n\n<p>(emphasis mine)</p>\n" }, { "answer_id": 73562238, "author": "juj", "author_id": 191096, "author_profile": "https://Stackoverflow.com/users/191096", "pm_score": 0, "selected": false, "text": "<p>Here are some other clues for a more complete answer...</p>\n<p>The usage can concern the shebang line, which has never thoroughly be documented and where a single parameter is often expected.</p>\n<p>Thereby it seems to be a workaround if filename contains spaces or exceed allowed length.</p>\n<p>From <a href=\"https://tecfa.unige.ch/guides/perl/man/pod/perlrun.html\" rel=\"nofollow noreferrer\">Perl man page</a>:</p>\n<blockquote>\n<p>A better construct than <code>$*</code> would be ${1+&quot;$@&quot;}, which handles embedded\nspaces and such in the filenames, but doesn't work if the script is\nbeing interpreted by csh.</p>\n</blockquote>\n<p>From <a href=\"https://www.tcl.tk/man/tcl/UserCmd/tclsh.html\" rel=\"nofollow noreferrer\">TCL man page</a>:</p>\n<blockquote>\n<p>Many UNIX systems do not allow the #! line to exceed about 30\ncharacters in length, so be sure that the tclsh executable can be\naccessed with a short file name.</p>\n</blockquote>\n<p>And finally, some utilities could support <a href=\"https://tldp.org/LDP/abs/html/internalvariables.html#APPREF\" rel=\"nofollow noreferrer\">the abstruse but handy feature</a> of the <code>cat</code> command :</p>\n<blockquote>\n<p>The $@ special parameter finds use as a tool for filtering input into\nshell scripts. The cat &quot;$@&quot; construction accepts input to a script\neither from stdin or from files given as parameters to the script.</p>\n</blockquote>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've noticed that sometimes wrapper scripts will use `${1:+"$@"}` for the parameters rather than just `"$@"`. For example, <http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh> uses ``` exec "$binary" $opts ${1:+"$@"} ``` Can anyone break `${1:+"$@"}` down into English and explain why it would be an advantage over plain `"$@"`?
'Hysterical Raisins', aka Historical Reasons. The explanation from JesperE (or the Bash man page on [shell parameter expansion](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion)) is accurate for what it does: * If `$1` exists and is not an empty string, then substitute the quoted list of arguments. Once upon 20 or so years ago, some broken minor variants of the Bourne Shell substituted an empty string `""` for `"$@"` if there were no arguments, instead of the correct, current behaviour of substituting nothing. Whether any such systems are still in use is open to debate. [Hmm: that expansion would not work correctly for: ``` command '' arg2 arg3 ... ``` In this context, the correct notation is: ``` ${1+"$@"} ``` This works correctly whether `$1` is an empty argument or not. So, someone remembered the notation incorrectly, accidentally introducing a bug.]
154,630
<p>Other than <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall" rel="nofollow noreferrer">-Wall</a>, what other warnings have people found useful?</p> <p><em><a href="http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html" rel="nofollow noreferrer">Options to Request or Suppress Warnings</a></em></p>
[ { "answer_id": 154638, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "<p>It would be the option <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-errors-1\" rel=\"nofollow noreferrer\">-pedantic-errors</a>.</p>\n" }, { "answer_id": 154642, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": false, "text": "<p>I usually compile with &quot;<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-W</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#index-ANSI-support\" rel=\"nofollow noreferrer\">-ansi</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\">-pedantic</a>&quot;.</p>\n<p>This helps ensure maximum quality and portability of the code.</p>\n" }, { "answer_id": 154659, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 4, "selected": false, "text": "<p>I like <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a>. It keeps the code warning free.</p>\n" }, { "answer_id": 154666, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>I also use:</p>\n<blockquote>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-overflow\" rel=\"nofollow noreferrer\">-Wstrict-overflow=5</a></p>\n</blockquote>\n<p>To catch those nasty bugs that <em>may</em> occur if I write code that relies on the overflow behaviour of integers.</p>\n<p>And:</p>\n<blockquote>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a></p>\n</blockquote>\n<p>Which enables some options that are nice to have as well. Most are for C++ though.</p>\n" }, { "answer_id": 154851, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 6, "selected": false, "text": "<p>I routinely use:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual \\\n -Wstrict-prototypes -Wmissing-prototypes\n</code></pre>\n<p>This set catches a lot for people unused to it (people whose code I get to compile with those flags for the first time); it seldom gives me a problem (though <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-qual\" rel=\"nofollow noreferrer\">-Wcast-qual</a> is occasionally a nuisance).</p>\n" }, { "answer_id": 154893, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\">-pedantic</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings\" rel=\"nofollow noreferrer\">-Wno-write-strings</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-unused-parameter\" rel=\"nofollow noreferrer\">-Wno-unused-parameter</a></p>\n<p>For &quot;Hurt me plenty&quot; mode, I leave away the -Wno...</p>\n<p>I like to have my code warning free, especially with C++. While C compiler warnings can often be ignored, many C++ warnings show fundamental defects in the source code.</p>\n" }, { "answer_id": 154923, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wfloat-equal\" rel=\"nofollow noreferrer\">-Wfloat-equal</a>, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wshadow\" rel=\"nofollow noreferrer\">-Wshadow</a>, and -<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-prototypes\" rel=\"nofollow noreferrer\">Wmissing-prototypes</a>.</p>\n" }, { "answer_id": 158535, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 1, "selected": false, "text": "<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wredundant-decls\" rel=\"nofollow noreferrer\">-Wredundant-decls</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wnested-externs\" rel=\"nofollow noreferrer\">-Wnested-externs</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-prototypes\" rel=\"nofollow noreferrer\">-Wstrict-prototypes</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a></li>\n<li>-Werror-implicit-function-declaration</li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wunused\" rel=\"nofollow noreferrer\">-Wunused</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-unused-value\" rel=\"nofollow noreferrer\">-Wno-unused-value</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wreturn-type\" rel=\"nofollow noreferrer\">-Wreturn-type</a></li>\n</ul>\n" }, { "answer_id": 415171, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 4, "selected": false, "text": "<p>I started out with C++, so when I made the switch to learning C I made sure to be extra-anal:</p>\n<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Message-Formatting-Options.html#index-fmessage-length\" rel=\"nofollow noreferrer\">-fmessage-length=0</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#index-ANSI-support\" rel=\"nofollow noreferrer\">-ansi</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\">-pedantic</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#index-std-1\" rel=\"nofollow noreferrer\">-std=c99</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wwrite-strings\" rel=\"nofollow noreferrer\">-Wwrite-strings</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Winit-self\" rel=\"nofollow noreferrer\">-Winit-self</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-align\" rel=\"nofollow noreferrer\">-Wcast-align</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-qual\" rel=\"nofollow noreferrer\">-Wcast-qual</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wpointer-arith\" rel=\"nofollow noreferrer\">-Wpointer-arith</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-aliasing\" rel=\"nofollow noreferrer\">-Wstrict-aliasing</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wformat\" rel=\"nofollow noreferrer\">-Wformat=2</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-declarations\" rel=\"nofollow noreferrer\">-Wmissing-declarations</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-include-dirs\" rel=\"nofollow noreferrer\">-Wmissing-include-dirs</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-unused-parameter\" rel=\"nofollow noreferrer\">-Wno-unused-parameter</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wuninitialized\" rel=\"nofollow noreferrer\">-Wuninitialized</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wold-style-definition\" rel=\"nofollow noreferrer\">-Wold-style-definition</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-prototypes\" rel=\"nofollow noreferrer\">-Wstrict-prototypes</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-prototypes\" rel=\"nofollow noreferrer\">-Wmissing-prototypes</a></li>\n</ul>\n" }, { "answer_id": 669273, "author": "Johan", "author_id": 51425, "author_profile": "https://Stackoverflow.com/users/51425", "pm_score": 2, "selected": false, "text": "<p>Right now I use:</p>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-W</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wconversion\" rel=\"nofollow noreferrer\">-Wconversion</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wshadow\" rel=\"nofollow noreferrer\">-Wshadow</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-qual\" rel=\"nofollow noreferrer\">-Wcast-qual</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wwrite-strings\" rel=\"nofollow noreferrer\">-Wwrite-strings</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a></p>\n<p>I took that list mostly from the book <em>&quot;<a href=\"https://www.goodreads.com/book/show/853267.An_Introduction_to_GCC\" rel=\"nofollow noreferrer\">An Introduction to GCC</a>&quot;</em> (by <a href=\"https://en.wikipedia.org/wiki/Richard_Stallman\" rel=\"nofollow noreferrer\">rms</a>) and then some from <a href=\"http://people.redhat.com/drepper/\" rel=\"nofollow noreferrer\">Ulrich Drepper</a>'s recommendation about <a href=\"https://en.wikipedia.org/wiki/Defensive_programming\" rel=\"nofollow noreferrer\">defensive programming</a> (slides for <em><a href=\"http://people.redhat.com/drepper/Defensive-slides.pdf\" rel=\"nofollow noreferrer\">Defensive Programming</a></em>).</p>\n<p>But I don't have any science behind my list. It just felt like a good list.</p>\n<hr />\n<p>Note: I don't like those pedantic flags though...</p>\n<p>Note: I think that -W and -Wextra are more or less the same thing.</p>\n" }, { "answer_id": 1145590, "author": "Adrian Panasiuk", "author_id": 111160, "author_profile": "https://Stackoverflow.com/users/111160", "pm_score": 0, "selected": false, "text": "<p>I use this option:</p>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wfatal-errors\" rel=\"nofollow noreferrer\">-Wfatal-errors</a></p>\n" }, { "answer_id": 1308599, "author": "amaterasu", "author_id": 158234, "author_profile": "https://Stackoverflow.com/users/158234", "pm_score": 1, "selected": false, "text": "<p>I generally just use</p>\n<pre><code>gcc -Wall -W -Wunused-parameter -Wmissing-declarations -Wstrict-prototypes -Wmissing-prototypes -Wsign-compare -Wconversion -Wshadow -Wcast-align -Wparentheses -Wsequence-point -Wdeclaration-after-statement -Wundef -Wpointer-arith -Wnested-externs -Wredundant-decls -Werror -Wdisabled-optimization -pedantic -funit-at-a-time -o\n</code></pre>\n<p>With references:</p>\n<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-W</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wunused-parameter\" rel=\"nofollow noreferrer\">-Wunused-parameter</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-declarations\" rel=\"nofollow noreferrer\">-Wmissing-declarations</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-prototypes\" rel=\"nofollow noreferrer\">-Wstrict-prototypes</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-prototypes\" rel=\"nofollow noreferrer\">-Wmissing-prototypes</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wsign-compare\" rel=\"nofollow noreferrer\">-Wsign-compare</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wconversion\" rel=\"nofollow noreferrer\">-Wconversion</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wshadow\" rel=\"nofollow noreferrer\">-Wshadow</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-align\" rel=\"nofollow noreferrer\">-Wcast-align</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wparentheses\" rel=\"nofollow noreferrer\">-Wparentheses</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wsequence-point\" rel=\"nofollow noreferrer\">-Wsequence-point</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wdeclaration-after-statement\" rel=\"nofollow noreferrer\">-Wdeclaration-after-statement</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wundef\" rel=\"nofollow noreferrer\">-Wundef</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wpointer-arith\" rel=\"nofollow noreferrer\">-Wpointer-arith</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wnested-externs\" rel=\"nofollow noreferrer\">-Wnested-externs</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wredundant-decls\" rel=\"nofollow noreferrer\">-Wredundant-decls</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wdisabled-optimization\" rel=\"nofollow noreferrer\">-Wdisabled-optimization</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\">-pedantic</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-funit-at-a-time\" rel=\"nofollow noreferrer\">-funit-at-a-time</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-o\" rel=\"nofollow noreferrer\">-o</a></li>\n</ul>\n" }, { "answer_id": 1667035, "author": "Josh Lee", "author_id": 19750, "author_profile": "https://Stackoverflow.com/users/19750", "pm_score": 1, "selected": false, "text": "<p>The warning about uninitialized variables doesn't work unless you specify <code>-O</code>, so I include that in my list:</p>\n<pre class=\"lang-none prettyprint-override\"><code>-g -O -Wall -Werror -Wextra -pedantic -std=c99\n</code></pre>\n<p>Documentation on each warning:</p>\n<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g\" rel=\"nofollow noreferrer\">-g</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O\" rel=\"nofollow noreferrer\">-O</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\">-pedantic</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#index-std-1\" rel=\"nofollow noreferrer\">-std=c99</a></li>\n</ul>\n" }, { "answer_id": 1667079, "author": "DevSolar", "author_id": 60281, "author_profile": "https://Stackoverflow.com/users/60281", "pm_score": 3, "selected": false, "text": "<p>Get the manual for the GCC version you use, find <strong>all warning options available</strong>, and then deactivate <strong>only</strong> those for which you have a <em>compelling</em> reason to do so. (For example, non-modifiable third-party headers that would give you lots of warnings otherwise.) <em>Document those reasons.</em> (In the Makefile or wherever you set those options.) Review the settings at regular intervalls, <em>and whenever you upgrade your compiler.</em></p>\n\n<p>The compiler is your friend. Warnings are your friend. Give the compiler as much chance to tell you of potential problems as possible. </p>\n" }, { "answer_id": 1667114, "author": "pmg", "author_id": 25324, "author_profile": "https://Stackoverflow.com/users/25324", "pm_score": 6, "selected": false, "text": "<h3>As of 2011-09-01, with GCC version 4.6.1</h3>\n<p>My current &quot;development&quot; alias</p>\n<p><code>gcc <a href=\"https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#index-std-1\" rel=\"nofollow noreferrer\">-std=c89</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-1\" rel=\"nofollow noreferrer\">-pedantic</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall\" rel=\"nofollow noreferrer\">-Wall</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-missing-braces\" rel=\"nofollow noreferrer\">-Wno-missing-braces</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wextra\" rel=\"nofollow noreferrer\">-Wextra</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-missing-field-initializers\" rel=\"nofollow noreferrer\">-Wno-missing-field-initializers</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wformat\" rel=\"nofollow noreferrer\">-Wformat=2</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wswitch-default\" rel=\"nofollow noreferrer\">-Wswitch-default</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wswitch-enum\" rel=\"nofollow noreferrer\">-Wswitch-enum</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-align\" rel=\"nofollow noreferrer\">-Wcast-align</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wpointer-arith\" rel=\"nofollow noreferrer\">-Wpointer-arith</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wbad-function-cast\" rel=\"nofollow noreferrer\">-Wbad-function-cast</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-overflow\" rel=\"nofollow noreferrer\">-Wstrict-overflow=5</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-prototypes\" rel=\"nofollow noreferrer\">-Wstrict-prototypes</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Winline\" rel=\"nofollow noreferrer\">-Winline</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wundef\" rel=\"nofollow noreferrer\">-Wundef</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wnested-externs\" rel=\"nofollow noreferrer\">-Wnested-externs</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-qual\" rel=\"nofollow noreferrer\">-Wcast-qual</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wshadow\" rel=\"nofollow noreferrer\">-Wshadow</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Warning-Options.html#index-Wunreachable_002dcode-437\" rel=\"nofollow noreferrer\">-Wunreachable-code</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wlogical-op\" rel=\"nofollow noreferrer\">-Wlogical-op</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wfloat-equal\" rel=\"nofollow noreferrer\">-Wfloat-equal</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wstrict-aliasing\" rel=\"nofollow noreferrer\">-Wstrict-aliasing=2</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wredundant-decls\" rel=\"nofollow noreferrer\">-Wredundant-decls</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wold-style-definition\" rel=\"nofollow noreferrer\">-Wold-style-definition</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-ggdb\" rel=\"nofollow noreferrer\">-ggdb3</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0\" rel=\"nofollow noreferrer\">-O0</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-fomit-frame-pointer\" rel=\"nofollow noreferrer\">-fno-omit-frame-pointer</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-ffloat-store\" rel=\"nofollow noreferrer\">-ffloat-store</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fno-common\" rel=\"nofollow noreferrer\">-fno-common</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-fstrict-aliasing\" rel=\"nofollow noreferrer\">-fstrict-aliasing</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html#index-l\" rel=\"nofollow noreferrer\">-lm</a>\n</code></p>\n<p>The &quot;release&quot; alias</p>\n<p><code>gcc -std=c89 -pedantic <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O3\" rel=\"nofollow noreferrer\">-O3</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-flto\" rel=\"nofollow noreferrer\">-DNDEBUG</a> -lm\n</code></p>\n<h3>As of 2009-11-03</h3>\n<p>&quot;development&quot; alias</p>\n<hr />\n<p><code>gcc -Wall -Wextra -Wformat=2 -Wswitch-default -Wcast-align \\\n     -Wpointer-arith -Wbad-function-cast -Wstrict-prototypes \\\n     -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wwrite-strings\" rel=\"nofollow noreferrer\">-Wwrite-strings</a> -Wconversion -Wunreachable-code \\\n     -Wstrict-aliasing=2 \\\n     -ffloat-store -fno-common -fstrict-aliasing \\\n     -lm -std=c89 -pedantic -O0 -ggdb3 <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-pg\" rel=\"nofollow noreferrer\">-pg</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-coverage\" rel=\"nofollow noreferrer\">--coverage</a>\n</code></p>\n<p>&quot;release&quot; alias</p>\n<p><code>gcc -lm -std=c89 -pedantic -O3 -DNDEBUG <a href=\"https://gcc.gnu.org/onlinedocs/gcc-4.5.4/gcc/Overall-Options.html#index-combine-82\" rel=\"nofollow noreferrer\">--combine</a> \\\n     <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-fwhole-program\" rel=\"nofollow noreferrer\">-fwhole-program</a> <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-funroll-loops\" rel=\"nofollow noreferrer\">-funroll-loops</a>\n</code></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9831/" ]
Other than [-Wall](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall), what other warnings have people found useful? *[Options to Request or Suppress Warnings](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html)*
I routinely use: ```none gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual \ -Wstrict-prototypes -Wmissing-prototypes ``` This set catches a lot for people unused to it (people whose code I get to compile with those flags for the first time); it seldom gives me a problem (though [-Wcast-qual](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-qual) is occasionally a nuisance).
154,636
<p>At the moment we use <a href="http://www.hsqldb.org/" rel="noreferrer">HSQLDB</a> as an embedded database, but we search for a database with less memory footprint as the data volume grows.</p> <p><a href="http://developers.sun.com/javadb/" rel="noreferrer">Derby / JavaDB</a> is not an option at the moment because it stores properties globally in the system properties. So we thought of <a href="http://www.h2database.com/html/main.html" rel="noreferrer">h2</a>.</p> <p>While we used HSQLDB we created a Server-object, set the parameters and started it. This is described <a href="http://hsqldb.org/doc/guide/ch04.html#N10BBC" rel="noreferrer">here</a> (and given as example in the class org.hsqldb.test.TestBase).</p> <p>The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.</p>
[ { "answer_id": 155237, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 6, "selected": true, "text": "<p>From the download, I see that the file tutorial.html has this </p>\n\n<pre><code>import org.h2.tools.Server;\n...\n// start the TCP Server\nServer server = Server.createTcpServer(args).start();\n...\n// stop the TCP Server\nserver.stop();\n</code></pre>\n" }, { "answer_id": 155423, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 6, "selected": false, "text": "<p>Yes, you can run H2 in embedded mode. You just use the JDBC driver and connect to an embedded url like this (their example):</p>\n\n<blockquote>\n <p>This database can be used in embedded\n mode, or in server mode. To use it in\n embedded mode, you need to:</p>\n\n<pre><code>* Add h2.jar to the classpath\n* Use the JDBC driver class: org.h2.Driver\n* The database URL jdbc:h2:~/test opens the database 'test' in your user home directory\n</code></pre>\n</blockquote>\n\n<p>Example of connecting with JDBC to an embedded H2 database (adapted from <a href=\"http://www.h2database.com/javadoc/org/h2/jdbcx/JdbcDataSource.html\" rel=\"noreferrer\">http://www.h2database.com/javadoc/org/h2/jdbcx/JdbcDataSource.html</a> ):</p>\n\n<pre><code>import org.h2.jdbcx.JdbcDataSource;\n// ...\nJdbcDataSource ds = new JdbcDataSource();\nds.setURL(\"jdbc:h2:˜/test\");\nds.setUser(\"sa\");\nds.setPassword(\"sa\");\nConnection conn = ds.getConnection();\n</code></pre>\n\n<p>If you're looking to use H2 in a purely in-memory / embedded mode, you can do that too. See this link for more:</p>\n\n<ul>\n<li><a href=\"http://www.h2database.com/html/features.html#in_memory_databases\" rel=\"noreferrer\">http://www.h2database.com/html/features.html#in_memory_databases</a></li>\n</ul>\n\n<p>You just need to use a special URL in normal JDBC code like \"jdbc:h2:mem:db1\".</p>\n" }, { "answer_id": 3806597, "author": "javydreamercsw", "author_id": 198108, "author_profile": "https://Stackoverflow.com/users/198108", "pm_score": 3, "selected": false, "text": "<p>If for some reason you need an embedded H2 database in server mode you can do it either manually using the API\nat <a href=\"http://www.h2database.com/javadoc/org/h2/tools/Server.html\" rel=\"noreferrer\">http://www.h2database.com/javadoc/org/h2/tools/Server.html</a> - or by\nappending ;AUTO_SERVER=TRUE to the database URL.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13209/" ]
At the moment we use [HSQLDB](http://www.hsqldb.org/) as an embedded database, but we search for a database with less memory footprint as the data volume grows. [Derby / JavaDB](http://developers.sun.com/javadb/) is not an option at the moment because it stores properties globally in the system properties. So we thought of [h2](http://www.h2database.com/html/main.html). While we used HSQLDB we created a Server-object, set the parameters and started it. This is described [here](http://hsqldb.org/doc/guide/ch04.html#N10BBC) (and given as example in the class org.hsqldb.test.TestBase). The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.
From the download, I see that the file tutorial.html has this ``` import org.h2.tools.Server; ... // start the TCP Server Server server = Server.createTcpServer(args).start(); ... // stop the TCP Server server.stop(); ```
154,652
<p>Is anyone out there still using DataFlex? If so, what are you favorite tips and tricks for this venerable 4GL?</p>
[ { "answer_id": 155555, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 3, "selected": true, "text": "<p>It all depends on the version of DF you're using, but here's a couple: </p>\n\n<ol>\n<li>Do not use \"While\" when traversing record sets. Always use repeat. (see example at bottom)</li>\n<li>The dataflex newsgroups (news.dataaccess.com) is the best place to ask questions. </li>\n<li>Other useful sites include <a href=\"http://sture.dk/wasp\" rel=\"nofollow noreferrer\">http://sture.dk/wasp</a> and <a href=\"http://www.vdf-guidance.com\" rel=\"nofollow noreferrer\">http://www.vdf-guidance.com</a></li>\n<li>Use entering_scope instead of activating to initialise values on forms. </li>\n<li>With deferred modal objects, use a container object above the deferred object to pass in parameters. </li>\n</ol>\n\n<p>I've got loads more. But I'm just going to have to go and lie down. I can't believe someone asked a dataflex question. </p>\n\n<pre><code>clear orders\nmove const.complete to orders.status\nfind ge orders by index.2\nrepeat\n if orders.status ne const.complete indicate finderr true\n if (not(finderr)) begin\n send doYourStuffHere\n find gt orders by index.2\n end\nuntil (finderr)\n</code></pre>\n" }, { "answer_id": 290565, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>mixin inheritance was an excellent feature - the methods of any other class could be reused in your class; as long as you provided the properties that they needed to work, everything was fine = multiple inheritance (MI) without the 'diamond problem', name conflicts, and other MI issues</p>\n" }, { "answer_id": 359450, "author": "Ola Eldøy", "author_id": 18651, "author_profile": "https://Stackoverflow.com/users/18651", "pm_score": 2, "selected": false, "text": "<p>My \"working language\" (i.e. what I am working on as an employed developer) is Visual Dataflex, currently on version 14.0. It's not the best language/environment available, but it certainly isn't the worst either.</p>\n\n<p>My number 1 tip would be, to quote Steve McConnell's Code Complete: \"Program <em>into</em> your language, not <em>in</em> it. Don't limit your programming thinking only to the concepts that are supported automatically by your language. The best programmers think of what they want to do, and then they assess how to accomplish their objectives with the programming tools at their disposal.\"</p>\n" }, { "answer_id": 477295, "author": "Dennis", "author_id": 16757, "author_profile": "https://Stackoverflow.com/users/16757", "pm_score": 2, "selected": false, "text": "<p>Another good new site for VDF/DF tips is <a href=\"http://www.vdfwiki.com/\" rel=\"nofollow noreferrer\">VDF Wiki</a>.</p>\n" }, { "answer_id": 565007, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The vdfguidance URL has a typo, it is <a href=\"http://www.vdf-guidance.com\" rel=\"nofollow noreferrer\">http://www.vdf-guidance.com</a> </p>\n" }, { "answer_id": 729059, "author": "fredrik", "author_id": 87750, "author_profile": "https://Stackoverflow.com/users/87750", "pm_score": 2, "selected": false, "text": "<p>The new Data Access World Wide forums!<br><br>\n<a href=\"http://support.dataaccess.com/forums/\" rel=\"nofollow noreferrer\">http://support.dataaccess.com/forums/</a></p>\n" }, { "answer_id": 982072, "author": "Mike Peat", "author_id": 121200, "author_profile": "https://Stackoverflow.com/users/121200", "pm_score": 2, "selected": false, "text": "<p>long time no see!</p>\n\n<p>Yes, DataFlex is still alive and well and being used by lots of people and organisations.</p>\n\n<p>The current version is the \"Visual\" form (i.e. Widows GUI): Visual DataFlex (VDF) 14.1, although v15.0 is just about to release (I've been using alphas, betas and RCs for development for a few months now).</p>\n\n<p>The character mode product (now v3.2) is still around as well, for DOS, Unix and Linux.</p>\n\n<p>VDF now has good support for Web Applications, web services (since about v10), an Ajax library (which will come \"in the box\" with 15.0), CodeJock controls for nicer UI design, a development environment (VDF Studio) that has for some time (since v12.0) been so complete that I rarely step outside it any more (I even code my JavaScript in it, when doing that for VDF projects). It also comes with a free CMS called Electos (now itself in v4.0 with VDF 15.0).</p>\n\n<p>It has connectivity kits in the box for Pervasive, MS SQL Server, DB2 and ODBC databases, with Oracle, MySQL and other drivers provided by Mertech Data Systems (Riaz Merchant's company: www.mertechdata.com).</p>\n\n<p>You can download a free \"Personal\" edition (for non-commercial use) from <a href=\"http://www.visualdataflex.com/download.asp?pageid=845\" rel=\"nofollow noreferrer\">here</a> - it is a fully-featured product, but if you make money from it you are required to buy a kosher licence. Give it a whirl! <strong>;-)</strong></p>\n\n<p>Good to hear from you again!</p>\n\n<p>Mike<br>\n(Still fighting with the b4stard descendants of your thrice-damned DataSets!!! <strong>;-)</strong> )</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
Is anyone out there still using DataFlex? If so, what are you favorite tips and tricks for this venerable 4GL?
It all depends on the version of DF you're using, but here's a couple: 1. Do not use "While" when traversing record sets. Always use repeat. (see example at bottom) 2. The dataflex newsgroups (news.dataaccess.com) is the best place to ask questions. 3. Other useful sites include <http://sture.dk/wasp> and <http://www.vdf-guidance.com> 4. Use entering\_scope instead of activating to initialise values on forms. 5. With deferred modal objects, use a container object above the deferred object to pass in parameters. I've got loads more. But I'm just going to have to go and lie down. I can't believe someone asked a dataflex question. ``` clear orders move const.complete to orders.status find ge orders by index.2 repeat if orders.status ne const.complete indicate finderr true if (not(finderr)) begin send doYourStuffHere find gt orders by index.2 end until (finderr) ```
154,655
<p>We have a VXML project that a 3rd party parses to provide us with a phone navigation system. We require them to enter an id code to leave a message, which is later reviewed by our company.</p> <p>We currently have this working as follows:</p> <pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache); Stream m = new MemoryStream(); //Create Memory Stream - Used to create XML document in Memory XmlTextWriter XML_Writer = new XmlTextWriter(m, System.Text.Encoding.UTF8); XML_Writer.Formatting = Formatting.Indented; XML_Writer.WriteStartDocument(); /* snip - writing a valid XML document */ XML_Writer.WriteEndDocument(); XML_Writer.Flush(); m.Position = 0; byte[] b = new byte[m.Length]; m.Read(b, 0, (int)m.Length); XML_Writer.Close(); HttpContext.Current.Response.Write(System.Text.Encoding.UTF8.GetString(b, 0, b.Length)); </code></pre> <p>I'm just maintaining this app, I didn't write it...but the end section seems convoluted to me.</p> <p>I know it's taking the output stream and feeding the written XML into it...but why is it first reading the entire string? Isn't that inefficient?</p> <p>Is there a better way to write the above code?</p>
[ { "answer_id": 154684, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 2, "selected": true, "text": "<p>Yes, just write directly to the Response <code>Output</code> (IO.StreamWriter) or <code>OutputStream</code> (IO.Stream):</p>\n\n<pre><code>XmlTextWriter XML_Writer = new XmlTextWriter(HttpContext.Current.Response.OutputStream, HttpContext.Current.Response.Encoding);\n//...\nXML_Writer.Flush();\n</code></pre>\n" }, { "answer_id": 154692, "author": "Jeff", "author_id": 23902, "author_profile": "https://Stackoverflow.com/users/23902", "pm_score": 0, "selected": false, "text": "<p>After that I can just call XML_Writer.Flush(), right? That'll flush the XML to the stream?</p>\n" }, { "answer_id": 154700, "author": "Boaz", "author_id": 2892, "author_profile": "https://Stackoverflow.com/users/2892", "pm_score": 0, "selected": false, "text": "<p>You can write directly to the response stream:</p>\n\n<p><code>\nResponse.Cache.SetCacheability(HttpCacheability.NoCache);</p>\n\n<p>XmlWriter XML_Writer = XmlWriter.Create(HttpContext.Current.Response.Output);\n</code></p>\n\n<p>To add settings to the writer you are better off using the newer <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx\" rel=\"nofollow noreferrer\">XmlWriterSettings</a> class. Give it as a parameter to the XmlWriter.Create function.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23902/" ]
We have a VXML project that a 3rd party parses to provide us with a phone navigation system. We require them to enter an id code to leave a message, which is later reviewed by our company. We currently have this working as follows: ``` Response.Cache.SetCacheability(HttpCacheability.NoCache); Stream m = new MemoryStream(); //Create Memory Stream - Used to create XML document in Memory XmlTextWriter XML_Writer = new XmlTextWriter(m, System.Text.Encoding.UTF8); XML_Writer.Formatting = Formatting.Indented; XML_Writer.WriteStartDocument(); /* snip - writing a valid XML document */ XML_Writer.WriteEndDocument(); XML_Writer.Flush(); m.Position = 0; byte[] b = new byte[m.Length]; m.Read(b, 0, (int)m.Length); XML_Writer.Close(); HttpContext.Current.Response.Write(System.Text.Encoding.UTF8.GetString(b, 0, b.Length)); ``` I'm just maintaining this app, I didn't write it...but the end section seems convoluted to me. I know it's taking the output stream and feeding the written XML into it...but why is it first reading the entire string? Isn't that inefficient? Is there a better way to write the above code?
Yes, just write directly to the Response `Output` (IO.StreamWriter) or `OutputStream` (IO.Stream): ``` XmlTextWriter XML_Writer = new XmlTextWriter(HttpContext.Current.Response.OutputStream, HttpContext.Current.Response.Encoding); //... XML_Writer.Flush(); ```
154,672
<p>I asked a question about Lua perfromance, and on of the <a href="https://stackoverflow.com/questions/124455/how-do-you-pre-size-an-array-in-lua#152894">responses</a> asked:</p> <blockquote> <p>Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.</p> </blockquote> <p>This is a slightly different question from <a href="https://stackoverflow.com/questions/89523/lua-patternstips-and-tricks">Lua Patterns,Tips and Tricks</a> because I'd like answers that specifically impact performance and (if possible) an explanation of why performance is impacted.</p> <p>One tip per answer would be ideal.</p>
[ { "answer_id": 324931, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "<p>Keep tables short, the larger the table the longer the search time.\nAnd in the same line iterating over numerically indexed tables (=arrays) is faster than key based tables (thus ipairs is faster than pairs)</p>\n" }, { "answer_id": 324955, "author": "Kknd", "author_id": 18403, "author_profile": "https://Stackoverflow.com/users/18403", "pm_score": 2, "selected": false, "text": "<ul>\n<li>Making the most used functions locals</li>\n<li>Making good use of tables as HashSets</li>\n<li>Lowering table creation by reutilization</li>\n<li>Using luajit!</li>\n</ul>\n" }, { "answer_id": 326703, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 3, "selected": false, "text": "<p>If your lua program is really too slow, use the Lua profiler and clean up expensive stuff or migrate to C. But if you're not sitting there waiting, your time is wasted.</p>\n\n<p>The first law of optimization: Don't.</p>\n\n<p>I'd love to see a problem where you have a choice between ipairs and pairs and can measure the effect of the difference.</p>\n\n<p>The one easy piece of low-hanging fruit is to remember to use local variables within each module. It's general not worth doing stuff like</p>\n\n<pre>\nlocal strfind = string.find\n</pre>\n\n<p>unless you can find a measurement telling you otherwise.</p>\n" }, { "answer_id": 12865406, "author": "dualed", "author_id": 1244588, "author_profile": "https://Stackoverflow.com/users/1244588", "pm_score": 7, "selected": true, "text": "<p>In response to some of the other answers and comments:</p>\n\n<p>It is true that as a programmer you should generally avoid premature optimization. <em>But</em>. This is not so true for scripting languages where the compiler does not optimize much -- or at all.</p>\n\n<p>So, whenever you write something in Lua, and that is executed very often, is run in a time-critical environment or could run for a while, it is a good thing to know things to <em>avoid</em> (and avoid them).</p>\n\n<p>This is a collection of what I found out over time. Some of it I found out over the net, but being of a suspicious nature when <em>the interwebs</em> are concerned I tested all of it myself. Also, I have read the Lua performance paper at Lua.org.</p>\n\n<p>Some reference:</p>\n\n<ul>\n<li><a href=\"http://www.lua.org/gems/sample.pdf\">Lua Performance Tips</a></li>\n<li><a href=\"http://lua-users.org/wiki/OptimisationTips\">Lua-users.org Optimisation Tips</a></li>\n</ul>\n\n<h1>Avoid globals</h1>\n\n<p>This is one of the most common hints, but stating it once more can't hurt.</p>\n\n<p>Globals are stored in a hashtable by their name. Accessing them means you have to access a table index. While Lua has a pretty good hashtable implementation, it's still a lot slower than accessing a local variable. If you have to use globals, assign their value to a local variable, this is faster at the 2nd variable access.</p>\n\n<pre><code>do\n x = gFoo + gFoo;\nend\ndo -- this actually performs better.\n local lFoo = gFoo;\n x = lFoo + lFoo;\nend\n</code></pre>\n\n<p>(Not that simple testing may yield different results. eg. <code>local x; for i=1, 1000 do x=i; end</code> here the for loop header takes actually more time than the loop body, thus profiling results could be distorted.)</p>\n\n<h1>Avoid string creation</h1>\n\n<p>Lua hashes all strings on creation, this makes comparison and using them in tables very fast and reduces memory use since all strings are stored internally only once. But it makes string creation more expensive.</p>\n\n<p>A popular option to avoid excessive string creation is using tables. For example, if you have to assemble a long string, create a table, put the individual strings in there and then use <code>table.concat</code> to join it <em>once</em></p>\n\n<pre><code>-- do NOT do something like this\nlocal ret = \"\";\nfor i=1, C do\n ret = ret..foo();\nend\n</code></pre>\n\n<p>If <code>foo()</code> would return only the character <code>A</code>, this loop would create a series of strings like <code>\"\"</code>, <code>\"A\"</code>, <code>\"AA\"</code>, <code>\"AAA\"</code>, etc. Each string would be hashed and reside in memory until the application finishes -- see the problem here?</p>\n\n<pre><code>-- this is a lot faster\nlocal ret = {};\nfor i=1, C do\n ret[#ret+1] = foo();\nend\nret = table.concat(ret);\n</code></pre>\n\n<p>This method does not create strings at all during the loop, the string is created in the function <code>foo</code> and only references are copied into the table. Afterwards, concat creates a second string <code>\"AAAAAA...\"</code> (depending on how large <code>C</code> is). Note that you <em>could</em> use <code>i</code> instead of <code>#ret+1</code> but often you don't have such a useful loop and you won't have an iterator variable you can use.</p>\n\n<p>Another trick I found somewhere on lua-users.org is to use gsub if you have to parse a string</p>\n\n<pre><code>some_string:gsub(\".\", function(m)\n return \"A\";\nend);\n</code></pre>\n\n<p>This looks odd at first, the benefit is that gsub creates a string \"at once\" in C which is only hashed after it is passed back to lua when gsub returns. This avoids table creation, but possibly has more function overhead (not if you call <code>foo()</code> anyway, but if <code>foo()</code> is actually an expression)</p>\n\n<h1>Avoid function overhead</h1>\n\n<p>Use language constructs instead of functions where possible</p>\n\n<h2>function <code>ipairs</code></h2>\n\n<p>When iterating a table, the function overhead from ipairs does not justify it's use. To iterate a table, instead use</p>\n\n<pre><code>for k=1, #tbl do local v = tbl[k];\n</code></pre>\n\n<p>It does exactly the same without the function call overhead (pairs actually returns another function which is then called for every element in the table while <code>#tbl</code> is only evaluated once). It's a lot faster, even if you need the value. And if you don't...</p>\n\n<p><strong>Note for Lua 5.2</strong>: In 5.2 you can actually define a <code>__ipairs</code> field in the metatable, which <em>does</em> make <code>ipairs</code> useful in some cases. However, Lua 5.2 also makes the <code>__len</code> field work for tables, so you might <em>still</em> prefer the above code to <code>ipairs</code> as then the <code>__len</code> metamethod is only called once, while for <code>ipairs</code> you would get an additional function call per iteration.</p>\n\n<h2>functions <code>table.insert</code>, <code>table.remove</code></h2>\n\n<p>Simple uses of <code>table.insert</code> and <code>table.remove</code> can be replaced by using the <code>#</code> operator instead. Basically this is for simple push and pop operations. Here are some examples:</p>\n\n<pre><code>table.insert(foo, bar);\n-- does the same as\nfoo[#foo+1] = bar;\n\nlocal x = table.remove(foo);\n-- does the same as\nlocal x = foo[#foo];\nfoo[#foo] = nil;\n</code></pre>\n\n<p>For shifts (eg. <code>table.remove(foo, 1)</code>), and if ending up with a sparse table is not desirable, it is of course still better to use the table functions.</p>\n\n<h1>Use tables for SQL-IN alike compares</h1>\n\n<p>You might - or might not - have decisions in your code like the following</p>\n\n<pre><code>if a == \"C\" or a == \"D\" or a == \"E\" or a == \"F\" then\n ...\nend\n</code></pre>\n\n<p>Now this is a perfectly valid case, however (from my own testing) starting with 4 comparisons and excluding table generation, this is actually faster:</p>\n\n<pre><code>local compares = { C = true, D = true, E = true, F = true };\nif compares[a] then\n ...\nend\n</code></pre>\n\n<p>And since hash tables have constant look up time, the performance gain increases with every additional comparison. On the other hand if \"most of the time\" one or two comparisons match, you might be better off with the Boolean way or a combination.</p>\n\n<h1>Avoid frequent table creation</h1>\n\n<p>This is discussed thoroughly in <a href=\"http://www.lua.org/gems/sample.pdf\">Lua Performance Tips</a>. Basically the problem is that Lua allocates your table on demand and doing it this way will actually take more time than cleaning it's content and filling it again.</p>\n\n<p>However, this is a bit of a problem, since Lua itself does not provide a method for removing all elements from a table, and <code>pairs()</code> is not the performance beast itself. I have not done any performance testing on this problem myself yet.</p>\n\n<p>If you can, define a C function that clears a table, this should be a good solution for table reuse.</p>\n\n<h1>Avoid doing the same over and over</h1>\n\n<p>This is the biggest problem, I think. While a compiler in a non-interpreted language can easily optimize away a lot of redundancies, Lua will not.</p>\n\n<h2>Memoize</h2>\n\n<p>Using tables this can be done quite easily in Lua. For single-argument functions you can even replace them with a table and __index metamethod. Even though this destroys transparancy, performance is better on cached values due to one less function call.</p>\n\n<p>Here is an implementation of memoization for a single argument using a metatable. (Important: This variant does <em>not</em> support a nil value argument, but is pretty damn fast for existing values.)</p>\n\n<pre><code>function tmemoize(func)\n return setmetatable({}, {\n __index = function(self, k)\n local v = func(k);\n self[k] = v\n return v;\n end\n });\nend\n-- usage (does not support nil values!)\nlocal mf = tmemoize(myfunc);\nlocal v = mf[x];\n</code></pre>\n\n<p>You could actually modify this pattern for multiple input values</p>\n\n<h2><a href=\"http://en.wikipedia.org/wiki/Partial_application\">Partial application</a></h2>\n\n<p>The idea is similar to memoization, which is to \"cache\" results. But here instead of caching the results of the function, you would cache intermediate values by putting their calculation in a constructor function that defines the calculation function in it's block. In reality I would just call it clever use of closures.</p>\n\n<pre><code>-- Normal function\nfunction foo(a, b, x)\n return cheaper_expression(expensive_expression(a,b), x);\nend\n-- foo(a,b,x1);\n-- foo(a,b,x2);\n-- ...\n\n-- Partial application\nfunction foo(a, b)\n local C = expensive_expression(a,b);\n return function(x)\n return cheaper_expression(C, x);\n end\nend\n-- local f = foo(a,b);\n-- f(x1);\n-- f(x2);\n-- ...\n</code></pre>\n\n<p>This way it is possible to easily create flexible functions that cache some of their work without too much impact on program flow.</p>\n\n<p>An extreme variant of this would be <a href=\"http://en.wikipedia.org/wiki/Currying\">Currying</a>, but that is actually more a way to mimic functional programming than anything else.</p>\n\n<p>Here is a more extensive (\"real world\") example with some code omissions, otherwise it would easily take up the whole page here (namely <code>get_color_values</code> actually does a lot of value checking and recognizes accepts mixed values)</p>\n\n<pre><code>function LinearColorBlender(col_from, col_to)\n local cfr, cfg, cfb, cfa = get_color_values(col_from);\n local ctr, ctg, ctb, cta = get_color_values(col_to);\n local cdr, cdg, cdb, cda = ctr-cfr, ctg-cfg, ctb-cfb, cta-cfa;\n if not cfr or not ctr then\n error(\"One of given arguments is not a color.\");\n end\n\n return function(pos)\n if type(pos) ~= \"number\" then\n error(\"arg1 (pos) must be in range 0..1\");\n end\n if pos &lt; 0 then pos = 0; end;\n if pos &gt; 1 then pos = 1; end;\n return cfr + cdr*pos, cfg + cdg*pos, cfb + cdb*pos, cfa + cda*pos;\n end\nend\n-- Call \nlocal blender = LinearColorBlender({1,1,1,1},{0,0,0,1});\nobject:SetColor(blender(0.1));\nobject:SetColor(blender(0.3));\nobject:SetColor(blender(0.7));\n</code></pre>\n\n<p>You can see that once the blender was created, the function only has to sanity-check a single value instead of up to eight. I even extracted the difference calculation, though it probably does not improve a lot, I hope it shows what this pattern tries to achieve.</p>\n" }, { "answer_id": 44766479, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It must be also pointed that using array fields from tables is much faster than using tables with any kind of key. It happens (almost) all Lua implementations (including LuaJ) store a called \"array part\" inside tables, which is accessed by the table array fields, and doesn't store the field key, nor lookup for it ;).</p>\n\n<p>You can even also imitate static aspects of other languages like <code>struct</code>, C++/Java <code>class</code>, etc.. Locals and arrays are enough.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
I asked a question about Lua perfromance, and on of the [responses](https://stackoverflow.com/questions/124455/how-do-you-pre-size-an-array-in-lua#152894) asked: > > Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses. > > > This is a slightly different question from [Lua Patterns,Tips and Tricks](https://stackoverflow.com/questions/89523/lua-patternstips-and-tricks) because I'd like answers that specifically impact performance and (if possible) an explanation of why performance is impacted. One tip per answer would be ideal.
In response to some of the other answers and comments: It is true that as a programmer you should generally avoid premature optimization. *But*. This is not so true for scripting languages where the compiler does not optimize much -- or at all. So, whenever you write something in Lua, and that is executed very often, is run in a time-critical environment or could run for a while, it is a good thing to know things to *avoid* (and avoid them). This is a collection of what I found out over time. Some of it I found out over the net, but being of a suspicious nature when *the interwebs* are concerned I tested all of it myself. Also, I have read the Lua performance paper at Lua.org. Some reference: * [Lua Performance Tips](http://www.lua.org/gems/sample.pdf) * [Lua-users.org Optimisation Tips](http://lua-users.org/wiki/OptimisationTips) Avoid globals ============= This is one of the most common hints, but stating it once more can't hurt. Globals are stored in a hashtable by their name. Accessing them means you have to access a table index. While Lua has a pretty good hashtable implementation, it's still a lot slower than accessing a local variable. If you have to use globals, assign their value to a local variable, this is faster at the 2nd variable access. ``` do x = gFoo + gFoo; end do -- this actually performs better. local lFoo = gFoo; x = lFoo + lFoo; end ``` (Not that simple testing may yield different results. eg. `local x; for i=1, 1000 do x=i; end` here the for loop header takes actually more time than the loop body, thus profiling results could be distorted.) Avoid string creation ===================== Lua hashes all strings on creation, this makes comparison and using them in tables very fast and reduces memory use since all strings are stored internally only once. But it makes string creation more expensive. A popular option to avoid excessive string creation is using tables. For example, if you have to assemble a long string, create a table, put the individual strings in there and then use `table.concat` to join it *once* ``` -- do NOT do something like this local ret = ""; for i=1, C do ret = ret..foo(); end ``` If `foo()` would return only the character `A`, this loop would create a series of strings like `""`, `"A"`, `"AA"`, `"AAA"`, etc. Each string would be hashed and reside in memory until the application finishes -- see the problem here? ``` -- this is a lot faster local ret = {}; for i=1, C do ret[#ret+1] = foo(); end ret = table.concat(ret); ``` This method does not create strings at all during the loop, the string is created in the function `foo` and only references are copied into the table. Afterwards, concat creates a second string `"AAAAAA..."` (depending on how large `C` is). Note that you *could* use `i` instead of `#ret+1` but often you don't have such a useful loop and you won't have an iterator variable you can use. Another trick I found somewhere on lua-users.org is to use gsub if you have to parse a string ``` some_string:gsub(".", function(m) return "A"; end); ``` This looks odd at first, the benefit is that gsub creates a string "at once" in C which is only hashed after it is passed back to lua when gsub returns. This avoids table creation, but possibly has more function overhead (not if you call `foo()` anyway, but if `foo()` is actually an expression) Avoid function overhead ======================= Use language constructs instead of functions where possible function `ipairs` ----------------- When iterating a table, the function overhead from ipairs does not justify it's use. To iterate a table, instead use ``` for k=1, #tbl do local v = tbl[k]; ``` It does exactly the same without the function call overhead (pairs actually returns another function which is then called for every element in the table while `#tbl` is only evaluated once). It's a lot faster, even if you need the value. And if you don't... **Note for Lua 5.2**: In 5.2 you can actually define a `__ipairs` field in the metatable, which *does* make `ipairs` useful in some cases. However, Lua 5.2 also makes the `__len` field work for tables, so you might *still* prefer the above code to `ipairs` as then the `__len` metamethod is only called once, while for `ipairs` you would get an additional function call per iteration. functions `table.insert`, `table.remove` ---------------------------------------- Simple uses of `table.insert` and `table.remove` can be replaced by using the `#` operator instead. Basically this is for simple push and pop operations. Here are some examples: ``` table.insert(foo, bar); -- does the same as foo[#foo+1] = bar; local x = table.remove(foo); -- does the same as local x = foo[#foo]; foo[#foo] = nil; ``` For shifts (eg. `table.remove(foo, 1)`), and if ending up with a sparse table is not desirable, it is of course still better to use the table functions. Use tables for SQL-IN alike compares ==================================== You might - or might not - have decisions in your code like the following ``` if a == "C" or a == "D" or a == "E" or a == "F" then ... end ``` Now this is a perfectly valid case, however (from my own testing) starting with 4 comparisons and excluding table generation, this is actually faster: ``` local compares = { C = true, D = true, E = true, F = true }; if compares[a] then ... end ``` And since hash tables have constant look up time, the performance gain increases with every additional comparison. On the other hand if "most of the time" one or two comparisons match, you might be better off with the Boolean way or a combination. Avoid frequent table creation ============================= This is discussed thoroughly in [Lua Performance Tips](http://www.lua.org/gems/sample.pdf). Basically the problem is that Lua allocates your table on demand and doing it this way will actually take more time than cleaning it's content and filling it again. However, this is a bit of a problem, since Lua itself does not provide a method for removing all elements from a table, and `pairs()` is not the performance beast itself. I have not done any performance testing on this problem myself yet. If you can, define a C function that clears a table, this should be a good solution for table reuse. Avoid doing the same over and over ================================== This is the biggest problem, I think. While a compiler in a non-interpreted language can easily optimize away a lot of redundancies, Lua will not. Memoize ------- Using tables this can be done quite easily in Lua. For single-argument functions you can even replace them with a table and \_\_index metamethod. Even though this destroys transparancy, performance is better on cached values due to one less function call. Here is an implementation of memoization for a single argument using a metatable. (Important: This variant does *not* support a nil value argument, but is pretty damn fast for existing values.) ``` function tmemoize(func) return setmetatable({}, { __index = function(self, k) local v = func(k); self[k] = v return v; end }); end -- usage (does not support nil values!) local mf = tmemoize(myfunc); local v = mf[x]; ``` You could actually modify this pattern for multiple input values [Partial application](http://en.wikipedia.org/wiki/Partial_application) ----------------------------------------------------------------------- The idea is similar to memoization, which is to "cache" results. But here instead of caching the results of the function, you would cache intermediate values by putting their calculation in a constructor function that defines the calculation function in it's block. In reality I would just call it clever use of closures. ``` -- Normal function function foo(a, b, x) return cheaper_expression(expensive_expression(a,b), x); end -- foo(a,b,x1); -- foo(a,b,x2); -- ... -- Partial application function foo(a, b) local C = expensive_expression(a,b); return function(x) return cheaper_expression(C, x); end end -- local f = foo(a,b); -- f(x1); -- f(x2); -- ... ``` This way it is possible to easily create flexible functions that cache some of their work without too much impact on program flow. An extreme variant of this would be [Currying](http://en.wikipedia.org/wiki/Currying), but that is actually more a way to mimic functional programming than anything else. Here is a more extensive ("real world") example with some code omissions, otherwise it would easily take up the whole page here (namely `get_color_values` actually does a lot of value checking and recognizes accepts mixed values) ``` function LinearColorBlender(col_from, col_to) local cfr, cfg, cfb, cfa = get_color_values(col_from); local ctr, ctg, ctb, cta = get_color_values(col_to); local cdr, cdg, cdb, cda = ctr-cfr, ctg-cfg, ctb-cfb, cta-cfa; if not cfr or not ctr then error("One of given arguments is not a color."); end return function(pos) if type(pos) ~= "number" then error("arg1 (pos) must be in range 0..1"); end if pos < 0 then pos = 0; end; if pos > 1 then pos = 1; end; return cfr + cdr*pos, cfg + cdg*pos, cfb + cdb*pos, cfa + cda*pos; end end -- Call local blender = LinearColorBlender({1,1,1,1},{0,0,0,1}); object:SetColor(blender(0.1)); object:SetColor(blender(0.3)); object:SetColor(blender(0.7)); ``` You can see that once the blender was created, the function only has to sanity-check a single value instead of up to eight. I even extracted the difference calculation, though it probably does not improve a lot, I hope it shows what this pattern tries to achieve.
154,680
<p>How would I create the equivalent Linq To Objects query?</p> <pre><code>SELECT MIN(CASE WHEN p.type = "In" THEN p.PunchTime ELSE NULL END ) AS EarliestIn, MAX(CASE WHEN p.type = "Out" THEN p.PunchTime ELSE NULL END ) AS LatestOUt FROM Punches p </code></pre>
[ { "answer_id": 154710, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>You can't efficiently select multiple aggregates in vanilla LINQ to Objects. You can perform multiple queries, of course, but that may well be inefficient depending on your data source.</p>\n\n<p>I have a framework which copes with this which I call \"Push LINQ\" - it's only a hobby (for me and Marc Gravell) but we believe it works pretty well. It's available as part of <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"nofollow noreferrer\">MiscUtil</a>, and you can read about it in <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx\" rel=\"nofollow noreferrer\">my blog post on it</a>.</p>\n\n<p>It looks slightly odd - because you define where you want the results to go as \"futures\", then push the data through the query, then retrieve the results - but once you get your head round it, it's fine. I'd be interested to hear how you get on with it - if you use it, please mail me at [email protected].</p>\n" }, { "answer_id": 155059, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Single enumeration yielding both min and max (and any other aggregate you want to throw in there). This is much easier in vb.net.</p>\n\n<p>I know this doesn't handle the empty case. That's pretty easy to add.</p>\n\n<pre><code> List&lt;int&gt; myInts = new List&lt;int&gt;() { 1, 4, 2, 0, 3 };\n var y = myInts.Aggregate(\n new { Min = int.MaxValue, Max = int.MinValue },\n (a, i) =&gt;\n new\n {\n Min = (i &lt; a.Min) ? i : a.Min,\n Max = (a.Max &lt; i) ? i : a.Max\n });\n Console.WriteLine(\"{0} {1}\", y.Min, y.Max);\n</code></pre>\n" }, { "answer_id": 2094810, "author": "DRBlaise", "author_id": 234720, "author_profile": "https://Stackoverflow.com/users/234720", "pm_score": 0, "selected": false, "text": "<p>It is possible to do multiple aggregates with LINQ-to-Objects, but it is a little ugly.</p>\n\n<pre><code>var times = punches.Aggregate(\n new { EarliestIn = default(DateTime?), LatestOut = default(DateTime?) },\n (agg, p) =&gt; new {\n EarliestIn = Min(\n agg.EarliestIn,\n p.type == \"In\" ? (DateTime?)p.PunchTime : default(DateTime?)),\n LatestOut = Max(\n agg.LatestOut,\n p.type == \"Out\" ? (DateTime?)p.PunchTime : default(DateTime?)) \n }\n);\n</code></pre>\n\n<p>You would also need Min and Max functions for DateTime since these are not available standard.</p>\n\n<pre><code>public static DateTime? Max(DateTime? d1, DateTime? d2)\n{\n if (!d1.HasValue)\n return d2;\n if (!d2.HasValue)\n return d1;\n return d1.Value &gt; d2.Value ? d1 : d2;\n}\npublic static DateTime? Min(DateTime? d1, DateTime? d2)\n{\n if (!d1.HasValue)\n return d2;\n if (!d2.HasValue)\n return d1;\n return d1.Value &lt; d2.Value ? d1 : d2;\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6819/" ]
How would I create the equivalent Linq To Objects query? ``` SELECT MIN(CASE WHEN p.type = "In" THEN p.PunchTime ELSE NULL END ) AS EarliestIn, MAX(CASE WHEN p.type = "Out" THEN p.PunchTime ELSE NULL END ) AS LatestOUt FROM Punches p ```
You can't efficiently select multiple aggregates in vanilla LINQ to Objects. You can perform multiple queries, of course, but that may well be inefficient depending on your data source. I have a framework which copes with this which I call "Push LINQ" - it's only a hobby (for me and Marc Gravell) but we believe it works pretty well. It's available as part of [MiscUtil](http://pobox.com/~skeet/csharp/miscutil), and you can read about it in [my blog post on it](http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx). It looks slightly odd - because you define where you want the results to go as "futures", then push the data through the query, then retrieve the results - but once you get your head round it, it's fine. I'd be interested to hear how you get on with it - if you use it, please mail me at [email protected].
154,686
<p>I've got a stock Debian Etch system, using Exim4. The domains are mostly local but there are some that are remote. To handle the delivery of remote mail I use the Debian configuration file:</p> <pre><code> /etc/exim4/hubbed_hosts </code></pre> <p>This file lists the domain names, and remote MX machines to deliver to. For example:</p> <pre><code> example.org: mx.example.com example.com: mx2.example.com </code></pre> <p>Looking at the exim4 configuration file I see that this used as follows:</p> <pre><code>hubbed_hosts: debug_print = "R: hubbed_hosts for $domain" driver = manualroute domains = "${if exists{CONFDIR/hubbed_hosts}\ {partial-lsearch;CONFDIR/hubbed_hosts}\ fail}" route_data = ${lookup{$domain}partial-lsearch{CONFDIR/hubbed_hosts}} transport = remote_smtp </code></pre> <p>The issue I have is that <em>some</em> of the hosts I'm using need to have their mail delivered to a non-standard port. Unfortunately the Debian hubbed_hosts file doesn't work if I try to change it to include a port:</p> <pre><code>example.org: mx1.example.org:2525 example.com: 1.2.3.4.2525 </code></pre> <p>Is it possible to dynamically allow the port to be specified?</p>
[ { "answer_id": 154711, "author": "manicmethod", "author_id": 12098, "author_profile": "https://Stackoverflow.com/users/12098", "pm_score": 1, "selected": false, "text": "<p>make a new transport that specifies the port</p>\n\n<pre><code>remote_hub_2525:\ndriver = smtp\nport = 2525\n</code></pre>\n\n<p>and then create a router for the domains needing non-standard delivery</p>\n\n<pre><code>non_standard_hub:\ndriver = manualroute\ndomains = example.org : example.com\ntransport = remote_hub_2525\nno_more\n</code></pre>\n" }, { "answer_id": 154796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>I was hoping for something a little more dynamic - and this solution works:</p>\n\n<pre><code> port = ${if exists{/etc/exim4/ports.list}\\\n {${lookup{$domain}lsearch{/etc/exim4/ports.list}\\\n {$value}{25}}}{25}}\n</code></pre>\n\n<p>Then a simple file may have a list of ports on a per-domain basis:</p>\n\n<pre><code> example.org: 2525\n example.com: 26\n</code></pre>\n" }, { "answer_id": 159880, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 2, "selected": false, "text": "<p>You could probably use the ${extract} operator to let you combine the port numbers and host names, like in the example in your original question.</p>\n\n<p>Something like (untested):</p>\n\n<pre><code>route_data = ${extract{1}{:}{${lookup{$domain}partial-lsearch{CONFDIR/hubbed_hosts}}}}\n</code></pre>\n" }, { "answer_id": 1950359, "author": "sherbang", "author_id": 5026, "author_profile": "https://Stackoverflow.com/users/5026", "pm_score": 3, "selected": false, "text": "<p>This is actually supported by default without any changes to your exim4 config.</p>\n\n<p>In hubbed_hosts, you separate hosts with a colon, and you specify a port number with a double-colon.\n EX:</p>\n\n<pre><code>domain1: server1:server2::port:server3\ndomain2: server1::port\ndomain3: server1:server2\n</code></pre>\n\n<p>For more info check out <a href=\"http://www.exim.org/exim-html-current/doc/html/spec_html/ch20.html#SECID122\" rel=\"noreferrer\">http://www.exim.org/exim-html-current/doc/html/spec_html/ch20.html#SECID122</a></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a stock Debian Etch system, using Exim4. The domains are mostly local but there are some that are remote. To handle the delivery of remote mail I use the Debian configuration file: ``` /etc/exim4/hubbed_hosts ``` This file lists the domain names, and remote MX machines to deliver to. For example: ``` example.org: mx.example.com example.com: mx2.example.com ``` Looking at the exim4 configuration file I see that this used as follows: ``` hubbed_hosts: debug_print = "R: hubbed_hosts for $domain" driver = manualroute domains = "${if exists{CONFDIR/hubbed_hosts}\ {partial-lsearch;CONFDIR/hubbed_hosts}\ fail}" route_data = ${lookup{$domain}partial-lsearch{CONFDIR/hubbed_hosts}} transport = remote_smtp ``` The issue I have is that *some* of the hosts I'm using need to have their mail delivered to a non-standard port. Unfortunately the Debian hubbed\_hosts file doesn't work if I try to change it to include a port: ``` example.org: mx1.example.org:2525 example.com: 1.2.3.4.2525 ``` Is it possible to dynamically allow the port to be specified?
I was hoping for something a little more dynamic - and this solution works: ``` port = ${if exists{/etc/exim4/ports.list}\ {${lookup{$domain}lsearch{/etc/exim4/ports.list}\ {$value}{25}}}{25}} ``` Then a simple file may have a list of ports on a per-domain basis: ``` example.org: 2525 example.com: 26 ```
154,697
<p>I'm trying to retrieve numeric values from a <code>DataGridView</code>. So far, the only way I've found is to retrieve them as a string and convert them to numeric.</p> <pre><code>Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString()); </code></pre> <p>There must be an easier way. The cell is originally populated from a <code>DataSet</code> with a numeric field value but since the <code>DataGridViewCell</code> object returns it as an object, I can't do a straight assignment. I must be missing something simple here.</p> <p>Thanks.</p>
[ { "answer_id": 154825, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 0, "selected": false, "text": "<p>What is the error you are getting? <code>Convert.ToDouble</code> has an overloaded method that takes an object, so you shouldn't need the <code>ToString()</code>? Unless you are doing a <code>TryParse</code>?</p>\n" }, { "answer_id": 154945, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "<p><code>DataGridViewCell</code> has <code>ValueType</code> property. You can use to do directly cast the value to that type without first converting it to string:</p>\n\n<pre><code>if(MyGrid.SelectedRows[0].Cells[0].ValueType!=null &amp;&amp;\n MyGrid.SelectedRows[0].Cells[0].ValueType == Double)\n return (Double)MyGrid.SelectedRows[0].Cells[0].Value;\n</code></pre>\n" }, { "answer_id": 154963, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 0, "selected": false, "text": "<p>Since <code>DataGridViewCell.Value</code> is an Object type, you really need to convert it to the appropriate type, <code>Double</code> or any <code>numeric</code> type in your case. The <code>DataGridView</code> contents aren't strongly typed so you have to cast the values retrieved from its cells.</p>\n" }, { "answer_id": 155058, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>With <code>DataGridViewCell</code> you can just cast the <code>.Value</code> to your known type; the following is a complete example that shows this happening (using double) from a <code>DataTable</code> (like your example).\nAdditionally, <code>Convert.To{blah}(...)</code> and <code>Convert.ChangeType(...)</code> might be helpful.</p>\n\n<pre><code>using System.Data;\nusing System.Windows.Forms;\nstatic class Program\n{\n static void Main()\n {\n Application.EnableVisualStyles();\n DataTable table = new DataTable\n {\n Columns = {\n {\"Foo\", typeof(double)},\n {\"Bar\", typeof(string)}\n },\n Rows = {\n {123.45, \"abc\"},\n {678.90, \"def\"}\n }\n };\n Form form = new Form();\n DataGridView grid = new DataGridView {\n Dock = DockStyle.Fill, DataSource = table};\n form.Controls.Add(grid);\n grid.CurrentCellChanged += delegate\n {\n form.Text = string.Format(\"{0}: {1}\",\n grid.CurrentCell.Value.GetType(),\n grid.CurrentCell.Value);\n\n if (grid.CurrentCell.Value is double)\n {\n double val = (double)grid.CurrentCell.Value;\n form.Text += \" is a double: \" + val;\n }\n };\n Application.Run(form);\n\n }\n}\n</code></pre>\n" }, { "answer_id": 156197, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 2, "selected": false, "text": "<p>I've actually just recently dealt with this problem and <code>TryParse</code> I think is your best bet with respect to robustness, but don't forget to check if the value in the Cell is <code>null</code>, if so <code>TryParse</code> will fail and throw up an error.</p>\n\n<pre><code>double d = 0;\nif(grid[col,row].Value != null)\n double.TryParse(grid[col,row].Value.ToString(), out d);\n</code></pre>\n\n<p>I would also recommend avoiding a straight cast, unless you know absolutely what type you are converting and that there will, in fact, be a value there, it will probably at some point cause an error in your code.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to retrieve numeric values from a `DataGridView`. So far, the only way I've found is to retrieve them as a string and convert them to numeric. ``` Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString()); ``` There must be an easier way. The cell is originally populated from a `DataSet` with a numeric field value but since the `DataGridViewCell` object returns it as an object, I can't do a straight assignment. I must be missing something simple here. Thanks.
With `DataGridViewCell` you can just cast the `.Value` to your known type; the following is a complete example that shows this happening (using double) from a `DataTable` (like your example). Additionally, `Convert.To{blah}(...)` and `Convert.ChangeType(...)` might be helpful. ``` using System.Data; using System.Windows.Forms; static class Program { static void Main() { Application.EnableVisualStyles(); DataTable table = new DataTable { Columns = { {"Foo", typeof(double)}, {"Bar", typeof(string)} }, Rows = { {123.45, "abc"}, {678.90, "def"} } }; Form form = new Form(); DataGridView grid = new DataGridView { Dock = DockStyle.Fill, DataSource = table}; form.Controls.Add(grid); grid.CurrentCellChanged += delegate { form.Text = string.Format("{0}: {1}", grid.CurrentCell.Value.GetType(), grid.CurrentCell.Value); if (grid.CurrentCell.Value is double) { double val = (double)grid.CurrentCell.Value; form.Text += " is a double: " + val; } }; Application.Run(form); } } ```
154,706
<p>Unfortunately, there seems to be no string.Split(string separator), only string.Split(char speparator).</p> <p>I want to break up my string based on a multi-character separator, a la VB6. Is there an easy (that is, not by referencing Microsoft.VisualBasic or having to learn RegExes) way to do this in c#?</p> <p>EDIT: Using .NET Framework 3.5.</p>
[ { "answer_id": 154712, "author": "leora", "author_id": 4653, "author_profile": "https://Stackoverflow.com/users/4653", "pm_score": 1, "selected": false, "text": "<p>the regex for spliting string is extremely simple so i would go with that route.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx</a></p>\n" }, { "answer_id": 154716, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Which version of .Net? At least 2.0 onwards includes the following overloads:</p>\n\n<pre><code>.Split(string[] separator, StringSplitOptions options) \n.Split(string[] separator, int count, StringSplitOptions options)\n</code></pre>\n\n<p>Now if they'd only fix it to accept any IEnumerable&lt;string> instead of just array.</p>\n" }, { "answer_id": 154723, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 4, "selected": true, "text": "<p><code>String.Split()</code> has other overloads. Some of them take <code>string[]</code> arguments.</p>\n\n<pre><code>string original = \"first;&amp;second;&amp;third\";\nstring[] splitResults = original.Split( new string[] { \";&amp;\" }, StringSplitOptions.None );\n</code></pre>\n" }, { "answer_id": 154746, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 0, "selected": false, "text": "<p>The regex version is probably prettier but this works too:</p>\n\n<pre><code>string[] y = { \"bar\" };\n\nstring x = \"foobarfoo\";\nforeach (string s in x.Split(y, StringSplitOptions.None))\n Console.WriteLine(s);\n</code></pre>\n\n<p>This'll print foo twice.</p>\n" }, { "answer_id": 154755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code> string[] stringSeparators = new string[] {\"[stop]\"};\n string[] result;\nresult = someString.Split(stringSeparators, StringSplitOptions.None);\n</code></pre>\n\n<p>via <a href=\"http://msdn.microsoft.com/en-us/library/tabh47cf.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/tabh47cf.aspx</a></p>\n" }, { "answer_id": 2210590, "author": "J.Hendrix", "author_id": 180385, "author_profile": "https://Stackoverflow.com/users/180385", "pm_score": 0, "selected": false, "text": "<p>I use this under .NET 2.0 all the time.</p>\n\n<pre><code>string[] args = \"first;&amp;second;&amp;third\".Split(\";&amp;\".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
Unfortunately, there seems to be no string.Split(string separator), only string.Split(char speparator). I want to break up my string based on a multi-character separator, a la VB6. Is there an easy (that is, not by referencing Microsoft.VisualBasic or having to learn RegExes) way to do this in c#? EDIT: Using .NET Framework 3.5.
`String.Split()` has other overloads. Some of them take `string[]` arguments. ``` string original = "first;&second;&third"; string[] splitResults = original.Split( new string[] { ";&" }, StringSplitOptions.None ); ```
154,708
<p>Ok, Regex wizards. I want to be able to search through my logfile and find any sessions with the word 'error' in it and then return the entire session log entry.</p> <p>I know I can do this with a string/array but I'd like to learn how to do it with Regex but here's the question. If I decide to do this with Regex do I <a href="http://www.codinghorror.com/blog/archives/001016.html" rel="nofollow noreferrer">have one or two problems</a>? ;o)</p> <p>Here's the log:</p> <p>PS: I'm using the perl Regex engine.</p> <p><strong>Note</strong>: I don't think I can get this done in Regex. In other words, I now have two problems. ;o) I've tried the solutions below but, since I've confused the issue by stating that I was using a Perl engine, many of the answers were in Perl (which cannot be used in my case). I did however post my solution below.</p> <hr> <pre><code>2008.08.27 08:04:21 (Wed)------------Start of Session----------------- Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19) Sending stdin.txt to [email protected] Subject: test 1 Login name is [email protected] The SMTP server does not require AUTH LOGIN. Are you sure server supports AUTH? The SMTP server does not like the sender name. Have you set your mail address correctly? 2008.08.27 08:04:24 (Wed)-------------End of Session------------------ 2008.08.27 08:05:56 (Wed)------------Start of Session----------------- Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19) Error: Wait a bit (possible timeout). SMTP server error Error: Not a socket. Error: Not a socket. 2008.08.27 08:06:26 (Wed)-------------End of Session------------------ 2008.08.27 08:07:58 (Wed)------------Start of Session----------------- Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19) Sending stdin.txt to [email protected] Subject: Lorem Update 08/27/2008 Login name is [email protected] 2008.08.27 08:07:58 (Wed)-------------End of Session------------------ </code></pre>
[ { "answer_id": 154743, "author": "Kyle", "author_id": 2237619, "author_profile": "https://Stackoverflow.com/users/2237619", "pm_score": 3, "selected": false, "text": "<p><p>It looks as if your sessions are delimited by blank lines (in addition to the start/end markers). If that's the case, this is a one liner:</p>\n\n<p><code>\nperl -ne 'BEGIN{$/=\"\"} print if /error/i' &lt; logfile\n</code></p>\n" }, { "answer_id": 154886, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 3, "selected": false, "text": "<p>Kyle's answer is probably the most perlish, but in case you have it all in one string and want to use a single regex, here's a (tested) solution:</p>\n\n<p>(<em>Second update</em>: fixed a bit, now more readable then ever ;-)</p>\n\n<pre><code>my $re = qr{\n ( # capture in $1\n (?:\n (?!\\n\\n). # Any character that's not at a paragraph break\n )* # repeated\n error\n (?:\n (?!\\n\\n).\n )*\n )\n}msxi;\n\n\nwhile ($s =~ m/$re/g){\n print \"'$1'\\n\";\n}\n</code></pre>\n\n<p>Ugly, but you asked for it.</p>\n" }, { "answer_id": 154910, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 0, "selected": false, "text": "<p>Like the last guy said, perl from the command line will work. So will awk from the command line:<br>\n<code>awk '/-Start of Session-/ { text=\"\"; gotError=0; } /Error/{gotError=1;}/-End of Session-/{ if(gotError) {print text}} { text=text \"\\n\" $0}' logFileName.txt</code></p>\n\n<p>Basically, start recording on a line with \"-Start of Session-\", set a flag on a line with \"Error\", and conditionally output on a line with \"-End of Session-\".</p>\n\n<p>Or put this into errorLogParser.awk:<pre>\n/-Start of Session-/{\n text=\"\";\n gotError=0;\n}\n/Error/{\n gotError=1;\n}\n/-End of Session-/{\n if(gotError)\n {\n print text\n }\n}\n{\n text=text \"\\n\" $0\n}\n</pre>\n... and invoke like so:\n<code>awk -f errorLineParser.awk logFileName.txt</code></p>\n" }, { "answer_id": 154913, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>With a perl regexp engine, the simple regexp</p>\n\n<pre><code>Error:.+ \n</code></pre>\n\n<p>does the trick according to <a href=\"https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world#89858\">quickrex</a>.</p>\n\n<p>(With a java regexp engine, another regexp would have been required:</p>\n\n<pre><code>(?ms)^Error:[^\\r\\n]+$\n</code></pre>\n\n<p>)</p>\n\n<p>a regexp with a capturing group would allow to redirect only the error message and not 'Error' itself, as in:</p>\n\n<pre><code>Error:\\s*(\\S.+)\n</code></pre>\n\n<p>The group n°1 capture only what follows 'Error: '</p>\n\n<p>Anyhow, for for to regexp, see <a href=\"http://www.regular-expressions.info/tutorial.html\" rel=\"nofollow noreferrer\">regular-Expressions.info tutorial</a>, a first-class introduction to this technique.</p>\n" }, { "answer_id": 155013, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "<pre><code>/(?:[^\\n\\r]|\\r?\\n(?!\\r|\\n))*?Error:(?:[^\\n\\r]|\\r?\\n(?!\\r|\\n))*/g\n</code></pre>\n\n<p>This takes advantage of the blank lines in between the entries. It works for both unix and windows line breaks. You can replace the text \"Error:\" in the middle with almost anything else if you would like.</p>\n" }, { "answer_id": 162191, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "<p>If you want to understand or play with any of these solutions, I high recommend downloading <a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">Regex Coach</a>, which helps you build up and test regular expressions</p>\n" }, { "answer_id": 162194, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 1, "selected": true, "text": "<p>What I did was to run the entire log into a string then went through line by line and added each line to a third variable until the line contained \"--End of Session--\". I then added that line to the 3rd var as well and then searched that 3rd var for the word \"error\". If it contained it, I added the 3rd var to a forth and then cleared the 3rd var and started going back through the var with the log on the next line. </p>\n\n<p>It looks like this:</p>\n\n<pre><code>str a b email gp lgf\nlgf.getfile( \"C:\\blat\\log.txt\")\nforeach a lgf\n if(find(a \"--End of Session--\")&gt;-1)\n gp.from(gp \"[]\" a)\n if(find(gp \"error\" 0 1)&gt;-1)\n gp.trim\n email.from(email gp \"[]\")\n gp=\"\"\n continue\n gp.from(gp \"[]\" a)\nemail.trim\n</code></pre>\n\n<p>It turns out that regex can really be a bear-cat to implement when it doesn't fit well. Kind of like using a screwdriver instead of a hammer. It'll get the job done, but takes a long time, break the screwdriver, and probably hurt you in the process.</p>\n" }, { "answer_id": 231530, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<p>Once in a while when only Vim was available (and sed, awk which I did not master at that time), I did something like:</p>\n\n<p>Via Vim I had joined all the lines between - in your case - Start of Session/End of Session to a Single line:</p>\n\n<blockquote>\n <ol>\n <li>First replaced all the line endings to some specific char:<br>\n <code>:%s:$:#</code></li>\n <li>Then turned the double enters into some other separator:<br>\n <code>:%s:#\\n#\\n:#\\r@\\r</code></li>\n <li>Joining the lines:<br>\n <code>:%s:#\\n:#</code></li>\n <li>Displayed only the lines with Error:<br>\n <code>:v/[Ee]rror/d</code></li>\n <li>Split lines to their original format:<br>\n <code>:%s:#:\\r</code></li>\n </ol>\n</blockquote>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
Ok, Regex wizards. I want to be able to search through my logfile and find any sessions with the word 'error' in it and then return the entire session log entry. I know I can do this with a string/array but I'd like to learn how to do it with Regex but here's the question. If I decide to do this with Regex do I [have one or two problems](http://www.codinghorror.com/blog/archives/001016.html)? ;o) Here's the log: PS: I'm using the perl Regex engine. **Note**: I don't think I can get this done in Regex. In other words, I now have two problems. ;o) I've tried the solutions below but, since I've confused the issue by stating that I was using a Perl engine, many of the answers were in Perl (which cannot be used in my case). I did however post my solution below. --- ``` 2008.08.27 08:04:21 (Wed)------------Start of Session----------------- Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19) Sending stdin.txt to [email protected] Subject: test 1 Login name is [email protected] The SMTP server does not require AUTH LOGIN. Are you sure server supports AUTH? The SMTP server does not like the sender name. Have you set your mail address correctly? 2008.08.27 08:04:24 (Wed)-------------End of Session------------------ 2008.08.27 08:05:56 (Wed)------------Start of Session----------------- Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19) Error: Wait a bit (possible timeout). SMTP server error Error: Not a socket. Error: Not a socket. 2008.08.27 08:06:26 (Wed)-------------End of Session------------------ 2008.08.27 08:07:58 (Wed)------------Start of Session----------------- Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19) Sending stdin.txt to [email protected] Subject: Lorem Update 08/27/2008 Login name is [email protected] 2008.08.27 08:07:58 (Wed)-------------End of Session------------------ ```
What I did was to run the entire log into a string then went through line by line and added each line to a third variable until the line contained "--End of Session--". I then added that line to the 3rd var as well and then searched that 3rd var for the word "error". If it contained it, I added the 3rd var to a forth and then cleared the 3rd var and started going back through the var with the log on the next line. It looks like this: ``` str a b email gp lgf lgf.getfile( "C:\blat\log.txt") foreach a lgf if(find(a "--End of Session--")>-1) gp.from(gp "[]" a) if(find(gp "error" 0 1)>-1) gp.trim email.from(email gp "[]") gp="" continue gp.from(gp "[]" a) email.trim ``` It turns out that regex can really be a bear-cat to implement when it doesn't fit well. Kind of like using a screwdriver instead of a hammer. It'll get the job done, but takes a long time, break the screwdriver, and probably hurt you in the process.
154,718
<p>My web application sends email fairly often, and it sends 3 kinds of emails: initiated by user, in response to an event in the system, and in automatic response to an email received by the application.</p> <p>I would like to make sure that the third type of email does not get stuck in an endless loop of auto-responders talking to each other. Currently, I use the header:</p> <pre><code>Precedence: junk </code></pre> <p>but Yahoo! mail is treating these messages as spam. This is obviously not ideal, because we would like SOMEBODY to read our auto-response and make a decision on it, just not an out-of-office reply.</p> <p><strong>What is the best way to send an email without triggering either junk filters or auto-responders?</strong></p> <pre><code>Precedence: junk? Precedence: bulk? Precedence: list? X-Priority: 2? </code></pre>
[ { "answer_id": 154750, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": -1, "selected": false, "text": "<p>How about configuring a white list on your email account?</p>\n\n<p>I would assume that any email key words could get flagged by a junk filter.</p>\n" }, { "answer_id": 154769, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 0, "selected": false, "text": "<p>The traditional way of dealing with this is to send the email with a null envelope-sender (traditionally written as &lt;>). This prevents the autoresponder on the other end from responding because there's no sender to respond to.</p>\n" }, { "answer_id": 154794, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://www.faqs.org/rfcs/rfc2076.html\" rel=\"noreferrer\">RFC 2076</a> discourages the use of the precedence header. as you have noted, many clients will just filter that off (especially the precedence: junk variety). it may be better to use a null path to avoid auto responder wars:</p>\n\n<pre><code>Return-Path: &lt;&gt;\n</code></pre>\n\n<p>Ultimately you could use priority to try to get around this, but this seems like going against the spirit of the header. i'd suggest just using the return-path header for this, and avoiding precedence. in some cases you may have to write in some way to drop auto-responders in your application (to avoid getting into a responder war), but i can't remember a situation in which this happened using an appropriate return-path. (most auto responder wars i recall having to deal with were the result of very badly formed emails)</p>\n\n<p>Note: the <code>Return-Path</code> header is, in short, the destination for notifications (bounces, delay delivery, etc...), and is described in <a href=\"http://www.faqs.org/rfcs/rfc2821.html\" rel=\"noreferrer\">RFC 2821</a> -- because it's required by SMTP. It's also one method to drop bad mail (as theoretically all good mail will set an appropriate return-path).</p>\n" }, { "answer_id": 301958, "author": "user38936", "author_id": 38936, "author_profile": "https://Stackoverflow.com/users/38936", "pm_score": 5, "selected": false, "text": "<p>There is a <a href=\"https://www.rfc-editor.org/rfc/rfc3834\" rel=\"nofollow noreferrer\">RFC 3834</a> dedicated for automated email responses.</p>\n<p>In short, it recommends:</p>\n<ol>\n<li><p>Send auto-responses only to address contained in the <code>Return-Path</code> header of an incoming message, if it is valid email address. Particularly &quot;&lt;&gt;&quot; (null address) in the <code>Return-Path</code> of the message means that auto-responses must not be sent for this message.</p>\n</li>\n<li><p>When sending auto-response, MAIL FROM smtp command must contain &quot;&lt;&gt;&quot; (null address). This would lead to Return-Path:&lt;&gt; when message will be delivered.</p>\n</li>\n<li><p>Use <a href=\"https://www.rfc-editor.org/rfc/rfc3834#section-5\" rel=\"nofollow noreferrer\">Auto-Submitted</a> header with value other than &quot;no&quot; to explicitly indicate automated response.</p>\n</li>\n</ol>\n<p>One note: it is not worth to explicitly set Return-Path header in outgoing message, as this header must be rewritten by envelop address (from MAIL FROM smtp command) during delivery.</p>\n" }, { "answer_id": 8908739, "author": "guettli", "author_id": 633961, "author_profile": "https://Stackoverflow.com/users/633961", "pm_score": 3, "selected": false, "text": "<p>You can set these headers:</p>\n\n<pre><code>Precedence: bulk\nAuto-Submitted: auto-generated\n</code></pre>\n\n<p>Source: <a href=\"http://www.redmine.org/projects/redmine/repository/revisions/2655/diff\" rel=\"noreferrer\">http://www.redmine.org/projects/redmine/repository/revisions/2655/diff</a></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3140/" ]
My web application sends email fairly often, and it sends 3 kinds of emails: initiated by user, in response to an event in the system, and in automatic response to an email received by the application. I would like to make sure that the third type of email does not get stuck in an endless loop of auto-responders talking to each other. Currently, I use the header: ``` Precedence: junk ``` but Yahoo! mail is treating these messages as spam. This is obviously not ideal, because we would like SOMEBODY to read our auto-response and make a decision on it, just not an out-of-office reply. **What is the best way to send an email without triggering either junk filters or auto-responders?** ``` Precedence: junk? Precedence: bulk? Precedence: list? X-Priority: 2? ```
[RFC 2076](http://www.faqs.org/rfcs/rfc2076.html) discourages the use of the precedence header. as you have noted, many clients will just filter that off (especially the precedence: junk variety). it may be better to use a null path to avoid auto responder wars: ``` Return-Path: <> ``` Ultimately you could use priority to try to get around this, but this seems like going against the spirit of the header. i'd suggest just using the return-path header for this, and avoiding precedence. in some cases you may have to write in some way to drop auto-responders in your application (to avoid getting into a responder war), but i can't remember a situation in which this happened using an appropriate return-path. (most auto responder wars i recall having to deal with were the result of very badly formed emails) Note: the `Return-Path` header is, in short, the destination for notifications (bounces, delay delivery, etc...), and is described in [RFC 2821](http://www.faqs.org/rfcs/rfc2821.html) -- because it's required by SMTP. It's also one method to drop bad mail (as theoretically all good mail will set an appropriate return-path).
154,754
<p>I would find out the <em>floppy inserted state</em>:</p> <ul> <li>no floppy inserted</li> <li>unformatted floppy inserted</li> <li>formatted floppy inserted</li> </ul> <p>Can this determined using "WMI" in the System.Management namespace?</p> <p>If so, can I generate events when the <em>floppy inserted state</em> changes? </p>
[ { "answer_id": 163970, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<p>This comes from <a href=\"http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx\" rel=\"nofollow noreferrer\">Scripting Center @ MSDN</a>:</p>\n\n<pre><code>strComputer = \".\"\nSet objWMIService = GetObject( _\n \"winmgmts:\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery _\n (\"Select * From Win32_LogicalDisk Where DeviceID = 'A:'\")\n\nFor Each objItem in colItems\n intFreeSpace = objItem.FreeSpace\n If IsNull(intFreeSpace) Then\n Wscript.Echo \"There is no disk in the floppy drive.\"\n Else\n Wscript.Echo \"There is a disk in the floppy drive.\"\n End If\nNext\n</code></pre>\n\n<p>You'll also be able to tell if it's formatted or not, by checking other members of the <a href=\"http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx\" rel=\"nofollow noreferrer\">Win32_LogicalDisk class</a>.</p>\n" }, { "answer_id": 168452, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 2, "selected": true, "text": "<p>Using Bob Kings idea I wrote the following method.</p>\n\n<p>It works great on CD's, removable drives, regular drives.</p>\n\n<p>However for a floppy it always return \"Not Available\".</p>\n\n<pre><code> public static void TestFloppy( char driveLetter ) {\n using( var searcher = new ManagementObjectSearcher( @\"SELECT * FROM Win32_LogicalDisk WHERE DeviceID = '\" + driveLetter + \":'\" ) )\n using( var logicalDisks = searcher.Get() ) {\n foreach( ManagementObject logicalDisk in logicalDisks ) {\n var fs = logicalDisk[ \"FreeSpace\" ];\n Console.WriteLine( \"FreeSpace = \" + ( fs ?? \"Not Available\" ) );\n\n logicalDisk.Dispose();\n }\n }\n }\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14841/" ]
I would find out the *floppy inserted state*: * no floppy inserted * unformatted floppy inserted * formatted floppy inserted Can this determined using "WMI" in the System.Management namespace? If so, can I generate events when the *floppy inserted state* changes?
Using Bob Kings idea I wrote the following method. It works great on CD's, removable drives, regular drives. However for a floppy it always return "Not Available". ``` public static void TestFloppy( char driveLetter ) { using( var searcher = new ManagementObjectSearcher( @"SELECT * FROM Win32_LogicalDisk WHERE DeviceID = '" + driveLetter + ":'" ) ) using( var logicalDisks = searcher.Get() ) { foreach( ManagementObject logicalDisk in logicalDisks ) { var fs = logicalDisk[ "FreeSpace" ]; Console.WriteLine( "FreeSpace = " + ( fs ?? "Not Available" ) ); logicalDisk.Dispose(); } } } ```
154,762
<p>I need to create XML in Perl. From what I read, <a href="http://search.cpan.org/dist/XML-LibXML" rel="noreferrer">XML::LibXML</a> is great for parsing and using XML that comes from somewhere else. Does anyone have any suggestions for an XML Writer? Is <a href="http://search.cpan.org/dist/XML-Writer" rel="noreferrer">XML::Writer</a> still maintained? Does anyone like/use it?</p> <p>In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer.</p> <p>Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up. Hopefully it will be easy to see what is most popular.</p> <p>Thanks!</p>
[ { "answer_id": 155010, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 6, "selected": true, "text": "<p>XML::Writer is still maintained (at least, as of February of this year), and it's indeed one of the favorite Perl XML writers out there. </p>\n\n<p>As for describing the syntax, one is better to look at the module's documentation (the link is already in the question). To wit:</p>\n\n<pre><code>use XML::Writer;\n\nmy $writer = new XML::Writer(); # will write to stdout\n$writer-&gt;startTag(\"greeting\", \n \"class\" =&gt; \"simple\");\n$writer-&gt;characters(\"Hello, world!\");\n$writer-&gt;endTag(\"greeting\");\n$writer-&gt;end();\n\n# produces &lt;greeting class='simple'&gt;Hello world!&lt;/greeting&gt;\n</code></pre>\n" }, { "answer_id": 155192, "author": "Matt Siegman", "author_id": 12299, "author_profile": "https://Stackoverflow.com/users/12299", "pm_score": 3, "selected": false, "text": "<p>I don't do much XML, but <a href=\"http://search.cpan.org/~gmpassos/XML-Smart-1.6.9/lib/XML/Smart.pm\" rel=\"nofollow noreferrer\">XML::Smart</a> looks like it might do what you want. Take a look at the section <a href=\"http://search.cpan.org/~gmpassos/XML-Smart-1.6.9/lib/XML/Smart.pm#CREATING_XML_DATA\" rel=\"nofollow noreferrer\">Creating XML Data</a> in the doc and it looks very simple and easy to use.</p>\n\n<p>Paraphrasing the doc:</p>\n\n<pre><code>use XML::Smart;\n\n## Create a null XML object:\nmy $XML = XML::Smart-&gt;new() ;\n\n## Add a server to the list:\n$XML-&gt;{server} = {\n os =&gt; 'Linux' ,\n type =&gt; 'mandrake' ,\n version =&gt; 8.9 ,\n address =&gt; [ '192.168.3.201', '192.168.3.202' ] ,\n} ;\n\n$XML-&gt;save('newfile.xml') ;\n</code></pre>\n\n<p>Which would put this in newfile.xml:</p>\n\n<pre><code>&lt;server os=\"Linux\" type=\"mandrake\" version=\"8.9\"&gt;\n &lt;address&gt;192.168.3.201&lt;/address&gt;\n &lt;address&gt;192.168.3.202&lt;/address&gt;\n&lt;/server&gt;\n</code></pre>\n\n<p>Cool. I'm going to have to play with this :)</p>\n" }, { "answer_id": 155227, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 2, "selected": false, "text": "<p>XML::Smart looks nice, but I don't remember it being available when I was using <a href=\"http://search.cpan.org/~grantm/XML-Simple-2.18/lib/XML/Simple.pm\" rel=\"nofollow noreferrer\">XML::Simple</a> many years ago. Nice interface, and works well for reading and writing XML.</p>\n" }, { "answer_id": 157145, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "<p>If you want to take a data structure in Perl and turn it into XML, <a href=\"http://search.cpan.org/dist/XML-Simple\" rel=\"nofollow noreferrer\">XML::Simple</a> will do the job nicely.</p>\n<p>At its simplest:</p>\n<pre>\nmy $hashref = { foo => 'bar', baz => [ 1, 2, 3 ] };\nuse XML::Simple;\nmy $xml = XML::Simple::XMLout($hashref);\n</pre>\n<p>As its name suggests, its basic usage is simple; however it does offer a lot of features if you need them.</p>\n<p>Naturally, it can also parse XML easily.</p>\n<p>EDIT: I wrote this back in Oct 2008, 14 years ago this year. Things have changed since then. XML::Simple's own documentation carries a clear warning:</p>\n<blockquote>\nThe use of this module in new code is strongly discouraged. Other modules are available which provide more straightforward and consistent interfaces. In particular, <a href=\"https://metacpan.org/pod/XML::LibXML\" rel=\"nofollow noreferrer\">XML::LibXML</a> is highly recommended and you can refer to for a tutorial introduction. <a href=\"https://metacpan.org/pod/XML::Twig\" rel=\"nofollow noreferrer\">XML::Twig</a> is another excellent alternative.\n</blockquote>\n<p>These days, I'd strongly recommend checking those out rather than using XML::Simple in new code.</p>\n" }, { "answer_id": 159708, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 1, "selected": false, "text": "<p>I like <a href=\"http://search.cpan.org/dist/XML-TreeBuilder\" rel=\"nofollow noreferrer\">XML::TreeBuilder</a> because it fits the way I think. Historically, I've used it more for parsing than emitting.</p>\n\n<p>A few weeks after this question was posted, I had occasion to generate some XML from Perl. I surveyed the other modules listed here, assuming one of them would work better than XML::TreeBuilder, but TreeBuilder was still the best choice for what I wanted.</p>\n\n<p>One drawback was there is no way to represent processing instructions and declarations in an XML::TreeBuilder object.</p>\n" }, { "answer_id": 2934794, "author": "Cosimo", "author_id": 11303, "author_profile": "https://Stackoverflow.com/users/11303", "pm_score": 5, "selected": false, "text": "<p>Just for the record, here's a snippet that uses XML::LibXML.</p>\n<pre><code>#!/usr/bin/env perl\n\n#\n# Create a simple XML document\n#\n\nuse strict;\nuse warnings;\nuse XML::LibXML;\n\nmy $doc = XML::LibXML::Document-&gt;new('1.0', 'utf-8');\n\nmy $root = $doc-&gt;createElement('my-root-element');\n$root-&gt;setAttribute('some-attr'=&gt; 'some-value');\n\nmy %elements = (\n color =&gt; 'blue',\n metal =&gt; 'steel',\n);\n\nfor my $name (keys %elements) {\n my $tag = $doc-&gt;createElement($name);\n my $value = $elements{$name};\n $tag-&gt;appendTextNode($value);\n $root-&gt;appendChild($tag);\n}\n\n$doc-&gt;setDocumentElement($root);\nprint $doc-&gt;toString();\n</code></pre>\n<p>and this outputs:</p>\n<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;my-root-element some-attr=&quot;some-value&quot;&gt;\n &lt;color&gt;blue&lt;/color&gt;\n &lt;metal&gt;steel&lt;/metal&gt;\n&lt;/my-root-element&gt;\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
I need to create XML in Perl. From what I read, [XML::LibXML](http://search.cpan.org/dist/XML-LibXML) is great for parsing and using XML that comes from somewhere else. Does anyone have any suggestions for an XML Writer? Is [XML::Writer](http://search.cpan.org/dist/XML-Writer) still maintained? Does anyone like/use it? In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer. Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up. Hopefully it will be easy to see what is most popular. Thanks!
XML::Writer is still maintained (at least, as of February of this year), and it's indeed one of the favorite Perl XML writers out there. As for describing the syntax, one is better to look at the module's documentation (the link is already in the question). To wit: ``` use XML::Writer; my $writer = new XML::Writer(); # will write to stdout $writer->startTag("greeting", "class" => "simple"); $writer->characters("Hello, world!"); $writer->endTag("greeting"); $writer->end(); # produces <greeting class='simple'>Hello world!</greeting> ```
154,780
<p>I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas?</p> <pre><code>template &lt;class T&gt; class kGUICallBackPtr { public: kGUICallBackPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *)); inline void Call(T *i) {if(m_func) m_func(m_obj,i);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *); }; template &lt;class T,class U&gt; class kGUICallBackPtrPtr { public: kGUICallBackPtrPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *,U *)); inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *,U *j); }; </code></pre>
[ { "answer_id": 154833, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 4, "selected": true, "text": "<p>Not yet in the language itself but C++0x will have support for <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates\" rel=\"nofollow noreferrer\">variadic templates</a>.</p>\n" }, { "answer_id": 155667, "author": "John Zwinck", "author_id": 4323, "author_profile": "https://Stackoverflow.com/users/4323", "pm_score": 0, "selected": false, "text": "<p>How about sidestepping this issue through the use of <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html\" rel=\"nofollow noreferrer\">Boost Bind</a>? You could make your code accept a single argument, or none at all, and bind arguments you need at the call site.</p>\n" }, { "answer_id": 156385, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 2, "selected": false, "text": "<p>C++0x variatdic templates is your best bet, but it will also be a while before you can use them.</p>\n\n<p>If you need sequences of types today, take a look at MPL's <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/refmanual/vector.html\" rel=\"nofollow noreferrer\">vector</a> of types, as well as other type sequence types. It's part of the <a href=\"http://boost.org/\" rel=\"nofollow noreferrer\">Boost</a> library. It allows you to provide a template argument that is a sequence of types, instead of just a single type.</p>\n" }, { "answer_id": 11770914, "author": "bytemaster", "author_id": 1446644, "author_profile": "https://Stackoverflow.com/users/1446644", "pm_score": 0, "selected": false, "text": "<p>My first choice would be to use boost::bind, boost::function, or std::bind/std::function and/or c++11 lambda's to achieve your goal. But if you need to roll your own functor then I would use boost fusion to create a 'fused functor' that takes a single template argument. </p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_41_0/libs/fusion/doc/html/fusion/functional/generation/functions/mk_fused.html\" rel=\"nofollow\">http://www.boost.org/doc/libs/1_41_0/libs/fusion/doc/html/fusion/functional/generation/functions/mk_fused.html</a></p>\n\n<p>Ultimately all of these libraries use pre-processor macros to enumerate all possible options to work around lack of varidic templates. </p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas? ``` template <class T> class kGUICallBackPtr { public: kGUICallBackPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *)); inline void Call(T *i) {if(m_func) m_func(m_obj,i);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *); }; template <class T,class U> class kGUICallBackPtrPtr { public: kGUICallBackPtrPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *,U *)); inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *,U *j); }; ```
Not yet in the language itself but C++0x will have support for [variadic templates](http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates).
154,802
<p>Given the following:</p> <pre><code>&amp;row-&gt;count </code></pre> <p>Would &amp;(row->count) be evaluated or (&amp;row)->count be evaluated in C++?</p> <p>EDIT: Here's a great <a href="http://www.cppreference.com/wiki/operator_precedence" rel="nofollow noreferrer">link</a> for C++ precedence.</p>
[ { "answer_id": 154811, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "<p>This is already asked. But <a href=\"http://www.cppreference.com/wiki/operator_precedence\" rel=\"nofollow noreferrer\">here</a> is a link.</p>\n\n<p>Edit: \nOk <a href=\"https://stackoverflow.com/questions/113992/c-binary-operators-order-of-precedence\">this</a> question is very similar. And possibly there is an other one.</p>\n" }, { "answer_id": 154817, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 0, "selected": false, "text": "<p>&amp;(row->count)</p>\n" }, { "answer_id": 154820, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.cppreference.com/wiki/operator_precedence\" rel=\"nofollow noreferrer\">&amp;(row->count)</a></p>\n" }, { "answer_id": 154827, "author": "mxg", "author_id": 11157, "author_profile": "https://Stackoverflow.com/users/11157", "pm_score": 0, "selected": false, "text": "<p>-> has a higher priority than &amp; (address of). So your expression would be evalutated as &amp;(row->count)</p>\n" }, { "answer_id": 154838, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 1, "selected": false, "text": "<p>C operator precendence is explained <a href=\"http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>As per the table, -> is higher priority than the &amp; operator, so it's &amp;(row->count)</p>\n" }, { "answer_id": 154854, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>As far as precedence rules go, I've always liked the one put forth by Steve Oualline in \"Practical C\":</p>\n\n<blockquote>\n <p>There are fifteen precedence rules in\n C (&amp;&amp; comes before || comes before\n ?:). The practical programmer reduces\n these to two:</p>\n \n <p>1) Multiplication and division come\n before addition and subtraction. </p>\n \n <p>2) Put parentheses around everything\n else.</p>\n</blockquote>\n" }, { "answer_id": 155201, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 1, "selected": false, "text": "<p>May I suggest that you resolve such questions using a test programme? That has the advantage that you will know for sure that the answer is correct for your implementation, and you are not exposed to the risk of badly answered questions.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
Given the following: ``` &row->count ``` Would &(row->count) be evaluated or (&row)->count be evaluated in C++? EDIT: Here's a great [link](http://www.cppreference.com/wiki/operator_precedence) for C++ precedence.
[&(row->count)](http://www.cppreference.com/wiki/operator_precedence)
154,826
<p>My Techie Bretheren (and Sisteren, of course!),</p> <p>I have a LinqToSql data model that has the following entities: <a href="http://danimal.acsysinteractive.com/images/advisor.jpg" rel="nofollow noreferrer">data model http://danimal.acsysinteractive.com/images/advisor.jpg</a></p> <p>I need to retrieve all advisors for a specific office, ordered by their sequence within the office. I've got the first part working with a join:</p> <pre><code>public static List&lt;Advisor&gt;GetOfficeEmployees(int OfficeID) { List&lt;Advisor&gt; lstAdvisors = null; using (AdvisorDataModelDataContext _context = new AdvisorDataModelDataContext()) { var advisors = from adv in _context.Advisors join advisoroffice in _context.OfficeAdvisors on adv.AdvisorId equals advisoroffice.AdvisorId where advisoroffice.OfficeId == OfficeID select adv; lstAdvisors = advisors.ToList(); } return lstAdvisors; } </code></pre> <p>However, I can't seem to wrap my weary brain around the order by clause. Can anyone give some suggestions?</p>
[ { "answer_id": 154992, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": 0, "selected": false, "text": "<p>Funny enough, if you just need \"basic-level\" security, you can set it up in the Excel sheet itself:<br><br>Go to the Tools -> Protection menu and you can lock down the whole sheet, or just specific ranges.<br><br><em>Note</em> This is not \"really good\" security and will not stand up against an even moderately-skilled attack...but it will pass muster for the most basic uses.</p>\n" }, { "answer_id": 180801, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "<p>Maybe use <a href=\"http://docs.google.com/\" rel=\"nofollow noreferrer\">Google Docs</a> to share the document. That would be as turn-key as it gets. :)</p>\n" }, { "answer_id": 331863, "author": "Min", "author_id": 14461, "author_profile": "https://Stackoverflow.com/users/14461", "pm_score": -1, "selected": false, "text": "<p>Webdav can do this. Might be a hassle to set it up.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
My Techie Bretheren (and Sisteren, of course!), I have a LinqToSql data model that has the following entities: [data model http://danimal.acsysinteractive.com/images/advisor.jpg](http://danimal.acsysinteractive.com/images/advisor.jpg) I need to retrieve all advisors for a specific office, ordered by their sequence within the office. I've got the first part working with a join: ``` public static List<Advisor>GetOfficeEmployees(int OfficeID) { List<Advisor> lstAdvisors = null; using (AdvisorDataModelDataContext _context = new AdvisorDataModelDataContext()) { var advisors = from adv in _context.Advisors join advisoroffice in _context.OfficeAdvisors on adv.AdvisorId equals advisoroffice.AdvisorId where advisoroffice.OfficeId == OfficeID select adv; lstAdvisors = advisors.ToList(); } return lstAdvisors; } ``` However, I can't seem to wrap my weary brain around the order by clause. Can anyone give some suggestions?
Maybe use [Google Docs](http://docs.google.com/) to share the document. That would be as turn-key as it gets. :)
154,837
<p>We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.</p> <p>We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.</p> <p>But for some reason my Workflows just don't see the config file.</p> <pre><code>&lt;configuration&gt; &lt;appSettings&gt; &lt;add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" /&gt; &lt;/appSettings&gt; &lt;/configuration&gt; </code></pre> <p>Given the above config file, the following code prints an empty string:</p> <pre><code>Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]); </code></pre> <p>I think what I want is to just specify a config filename, but I'm having problems here. I'm just not getting results. Anyone have any pointers?</p>
[ { "answer_id": 154914, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Funny, where I'm at we're doing something very similar and the config file loads just fine. In our case I think each new config file's name matches that of it's associated assembly. So MyLibrary.dll would have a file named MyLibrary.dll.config with information for that file assembly. Also, the example I have handy is using VB.Net rather than C# (we have some of each) and all the settings in there are for the VB-specific My.Settings namespace, so we don't use the ConfigurationManager class directly to read them.</p>\n\n<p>The settings themselves look like this:</p>\n\n<pre><code>&lt;applicationSettings&gt;\n &lt;MyLibrary.My.MySettings&gt;\n &lt;setting name=\"SomeSetting\" serializeAs=\"String\"&gt;\n &lt;value&gt;12345&lt;/value&gt;\n &lt;/setting&gt;\n &lt;/MyLibrary.My.MySettings&gt;\n&lt;/applicationSettings&gt;\n</code></pre>\n" }, { "answer_id": 154946, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly, the app.config will be loaded from your application directory, so if you are loading dlls from some other directory, you'll want the keys they need in your application's config file.</p>\n" }, { "answer_id": 154974, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 4, "selected": true, "text": "<p>If your code sample for reading the AppSettings is in your DLL, then it will attempt to read the config file for the application and not the config file for the DLL. This is because you're using Reflection to execute the code. </p>\n" }, { "answer_id": 154999, "author": "Juan Zamudio", "author_id": 15058, "author_profile": "https://Stackoverflow.com/users/15058", "pm_score": 0, "selected": false, "text": "<p>I'm not totally sure but I think that class only works with the path of the entry method of the AppDomain (the path of the exe most of the time) by default.\nYou need to call OpenExeConfiguration(string exePath) (Framework 2.0 and later) first to point to a different config file.</p>\n" }, { "answer_id": 155534, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>I wrote this for a similar system. My recollection is that I used <code>Assembly.GetExecutingAssembly</code> to get the file path to the DLL, appended <code>.config</code> to that name, loaded it as an <code>XmlDocument</code>, navigated to the <code>&lt;appSettings&gt;</code> node and passed that to a <code>NameValueSectionHandler</code>'s <code>Create</code> method.</p>\n" }, { "answer_id": 6214544, "author": "0xDEAD BEEF", "author_id": 293138, "author_profile": "https://Stackoverflow.com/users/293138", "pm_score": 1, "selected": false, "text": "<p>Here is one way - \nAppDomain.CurrentDomain.SetData (\"APP_CONFIG_FILE\", \"path to config file\");</p>\n\n<p>Call in constructor.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23597/" ]
We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection. We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory. But for some reason my Workflows just don't see the config file. ``` <configuration> <appSettings> <add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" /> </appSettings> </configuration> ``` Given the above config file, the following code prints an empty string: ``` Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]); ``` I think what I want is to just specify a config filename, but I'm having problems here. I'm just not getting results. Anyone have any pointers?
If your code sample for reading the AppSettings is in your DLL, then it will attempt to read the config file for the application and not the config file for the DLL. This is because you're using Reflection to execute the code.
154,842
<p>I posted an answer to <a href="https://stackoverflow.com/questions/154706">this question</a>, including a very short rant at the end about how String.Split() should accept IEnumerable&lt;string> rather than string[]. </p> <p>That got me thinking. What if the base Object class from which everything else inherits provided a default implementation for IEnumerable such that everything now returns an Enumerator over exactly one item (itself) -- unless it's overridden to do something else like with collections classes.</p> <p>The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.</p> <p>I'm sure there are all kinds of reasons not to do this, not the least of which is that if everything implemented IEnumerable, then the few classes where the implementation strays from the default could behave differently than you'd expect in certain scenarios. But I still thought it would be a fun exercise: what other consequences would there be?</p>
[ { "answer_id": 154890, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p><strong>the index operator ([]) isn't part of the contract of IEnumerable&lt;T&gt;</strong>\nAfter looking at the code in reflector, the code uses the index operator heavily, which is always part of Array.</p>\n\n<p>Well, simply put, Array will always have an enumerator.</p>\n\n<blockquote>\n <p>The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.</p>\n</blockquote>\n\n<p>That isn't true, string inherits IEnumerable&lt;char&gt; And you don't have generic variance, so you can't cast IEnumerable&lt;char&gt; to IEnumerable&lt;string&gt;. You would be getting the IEnumerable&lt;char&gt; version(s) of split, rather then the required string.</p>\n" }, { "answer_id": 154904, "author": "Leahn Novash", "author_id": 5954, "author_profile": "https://Stackoverflow.com/users/5954", "pm_score": 0, "selected": false, "text": "<p>Have you thought about using a helper object and implementing a Split for the IEnumerable class?</p>\n\n<p>I did once make a GetDescription for the Enum class so to get the DescriptionAttribute easily. It works amazingly well.</p>\n" }, { "answer_id": 154932, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<pre><code>public static IEnumerable&lt;object&gt; ToEnumerable(this object someObject)\n{\n return System.Linq.Enumerable.Repeat(someObject, 1);\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I posted an answer to [this question](https://stackoverflow.com/questions/154706), including a very short rant at the end about how String.Split() should accept IEnumerable<string> rather than string[]. That got me thinking. What if the base Object class from which everything else inherits provided a default implementation for IEnumerable such that everything now returns an Enumerator over exactly one item (itself) -- unless it's overridden to do something else like with collections classes. The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array. I'm sure there are all kinds of reasons not to do this, not the least of which is that if everything implemented IEnumerable, then the few classes where the implementation strays from the default could behave differently than you'd expect in certain scenarios. But I still thought it would be a fun exercise: what other consequences would there be?
``` public static IEnumerable<object> ToEnumerable(this object someObject) { return System.Linq.Enumerable.Repeat(someObject, 1); } ```
154,845
<p>I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present. </p> <p><strong>So something like:</strong></p> <p><em>dr.ToString.Substring(1, dr.ToString.Length);</em></p> <p>But more conditionally in case the dollar sign ever made an appearance again.</p> <p>I am trying to do this with explicitly defining another string.</p>
[ { "answer_id": 154857, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 5, "selected": true, "text": "<pre><code>Convert.ToString(dr(columnName)).Replace(\"$\", String.Empty)\n</code></pre>\n\n<p>--\nIf you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations. </p>\n" }, { "answer_id": 154865, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>Regex would work.</p>\n\n<p>Regex.Replace(theString, \"$\", \"\");</p>\n\n<p>But there are multiple ways to solve this problem.</p>\n" }, { "answer_id": 154894, "author": "devmode", "author_id": 12368, "author_profile": "https://Stackoverflow.com/users/12368", "pm_score": 2, "selected": false, "text": "<p>dr[columeName].ToString().Replace(\"$\", String.Empty)</p>\n" }, { "answer_id": 154927, "author": "Kwirk", "author_id": 21879, "author_profile": "https://Stackoverflow.com/users/21879", "pm_score": 0, "selected": false, "text": "<p>Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.</p>\n" }, { "answer_id": 154956, "author": "Shaun Bowe", "author_id": 1514, "author_profile": "https://Stackoverflow.com/users/1514", "pm_score": 3, "selected": false, "text": "<p>If you are using C# 3.0 or greater you could use <a href=\"http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx\" rel=\"noreferrer\">extension methods</a>.</p>\n\n<pre><code>public static string RemoveNonNumeric(this string s)\n{\n return s.Replace(\"$\", \"\");\n}\n</code></pre>\n\n<p>Then your code could be changed to:</p>\n\n<pre><code>((String)dr[columnName]).RemoveNonNumeric();\n</code></pre>\n\n<p>This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.</p>\n\n<p>Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.</p>\n" }, { "answer_id": 155035, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 3, "selected": false, "text": "<p>You could also use</p>\n\n<pre><code>string trimmed = (dr as string).Trim('$');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>string trimmed = (dr as string).TrimStart('$');\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present. **So something like:** *dr.ToString.Substring(1, dr.ToString.Length);* But more conditionally in case the dollar sign ever made an appearance again. I am trying to do this with explicitly defining another string.
``` Convert.ToString(dr(columnName)).Replace("$", String.Empty) ``` -- If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
154,846
<p>I'm looking for a way to create an online form that will update an Access database that has just a few tables. Does anyone know of a simple solution for this?</p>
[ { "answer_id": 154857, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 5, "selected": true, "text": "<pre><code>Convert.ToString(dr(columnName)).Replace(\"$\", String.Empty)\n</code></pre>\n\n<p>--\nIf you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations. </p>\n" }, { "answer_id": 154865, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>Regex would work.</p>\n\n<p>Regex.Replace(theString, \"$\", \"\");</p>\n\n<p>But there are multiple ways to solve this problem.</p>\n" }, { "answer_id": 154894, "author": "devmode", "author_id": 12368, "author_profile": "https://Stackoverflow.com/users/12368", "pm_score": 2, "selected": false, "text": "<p>dr[columeName].ToString().Replace(\"$\", String.Empty)</p>\n" }, { "answer_id": 154927, "author": "Kwirk", "author_id": 21879, "author_profile": "https://Stackoverflow.com/users/21879", "pm_score": 0, "selected": false, "text": "<p>Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.</p>\n" }, { "answer_id": 154956, "author": "Shaun Bowe", "author_id": 1514, "author_profile": "https://Stackoverflow.com/users/1514", "pm_score": 3, "selected": false, "text": "<p>If you are using C# 3.0 or greater you could use <a href=\"http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx\" rel=\"noreferrer\">extension methods</a>.</p>\n\n<pre><code>public static string RemoveNonNumeric(this string s)\n{\n return s.Replace(\"$\", \"\");\n}\n</code></pre>\n\n<p>Then your code could be changed to:</p>\n\n<pre><code>((String)dr[columnName]).RemoveNonNumeric();\n</code></pre>\n\n<p>This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.</p>\n\n<p>Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.</p>\n" }, { "answer_id": 155035, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 3, "selected": false, "text": "<p>You could also use</p>\n\n<pre><code>string trimmed = (dr as string).Trim('$');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>string trimmed = (dr as string).TrimStart('$');\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6958/" ]
I'm looking for a way to create an online form that will update an Access database that has just a few tables. Does anyone know of a simple solution for this?
``` Convert.ToString(dr(columnName)).Replace("$", String.Empty) ``` -- If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
154,862
<p>How can I convert a JavaScript string value to be in all lower case letters?</p> <p>Example: <code>&quot;Your Name&quot;</code> to <code>&quot;your name&quot;</code></p>
[ { "answer_id": 154882, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 5, "selected": false, "text": "<p>Yes, any string in JavaScript has a <code>toLowerCase()</code> method that will return a new string that is the old string in all lower case. The old string will remain unchanged.</p>\n\n<p>So, you can do something like:</p>\n\n<pre><code>\"Foo\".toLowerCase();\ndocument.getElementById('myField').value.toLowerCase();\n</code></pre>\n" }, { "answer_id": 154891, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 12, "selected": true, "text": "<pre><code>var lowerCaseName = \"Your Name\".toLowerCase();\n</code></pre>\n" }, { "answer_id": 155257, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 9, "selected": false, "text": "<p>Use either <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLowerCase\" rel=\"noreferrer\">toLowerCase</a> or <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLocaleLowerCase\" rel=\"noreferrer\">toLocaleLowerCase</a> methods of the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String\" rel=\"noreferrer\">String</a> object. The difference is that <code>toLocaleLowerCase</code> will take current locale of the user/host into account. As per § 15.5.4.17 of the <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"noreferrer\">ECMAScript Language Specification (ECMA-262)</a>, <code>toLocaleLowerCase</code>…</p>\n\n<blockquote>\n <p>…works exactly the same as toLowerCase\n except that its result is intended to\n yield the correct result for the host\n environment’s current locale, rather\n than a locale-independent result.\n There will only be a difference in the\n few cases (such as Turkish) where the\n rules for that language conflict with\n the regular Unicode case mappings.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>var lower = 'Your Name'.toLowerCase();\n</code></pre>\n\n<p>Also note that the <code>toLowerCase</code> and <code>toLocaleLowerCase</code> functions are implemented to work generically on <em>any</em> value type. Therefore you can invoke these functions even on non-<code>String</code> objects. Doing so will imply automatic conversion to a string value prior to changing the case of each character in the resulting string value. For example, you can <em>apply</em> <code>toLowerCase</code> directly on a date like this:</p>\n\n<pre><code>var lower = String.prototype.toLowerCase.apply(new Date());\n</code></pre>\n\n<p>and which is effectively equivalent to:</p>\n\n<pre><code>var lower = new Date().toString().toLowerCase();\n</code></pre>\n\n<p>The second form is generally preferred for its simplicity and readability. On earlier versions of IE, the first had the benefit that it could work with a <code>null</code> value. The result of applying <code>toLowerCase</code> or <code>toLocaleLowerCase</code> on <code>null</code> would yield <code>null</code> (and not an error condition).</p>\n" }, { "answer_id": 1850197, "author": "sanilunlu", "author_id": 206391, "author_profile": "https://Stackoverflow.com/users/206391", "pm_score": 4, "selected": false, "text": "<p>toLocaleUpperCase() or lower case functions don't behave like they should do. For example, on my system, with Safari 4, Chrome 4 Beta, and Firefox 3.5.x, it converts strings with Turkish characters incorrectly. The browsers respond to navigator.language as &quot;en-US&quot;, &quot;tr&quot;, &quot;en-US&quot; respectively.</p>\n<p>But there isn't any way to get user's Accept-Lang setting in the browser as far as I could find.</p>\n<p>Only Chrome gives me trouble although I have configured every browser as tr-TR locale preferred. I think these settings only affect the HTTP header, but we can't access to these settings via JavaScript.</p>\n<p>In the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String\" rel=\"nofollow noreferrer\">Mozilla documentation</a> it says &quot;The characters within a string are converted to ... while respecting the current locale. For most languages, this will return the same as ...&quot;. I think it's valid for Turkish, and it doesn't differ if it's configured as <em>en</em> or <em>tr</em>.</p>\n<p>In Turkish it should convert &quot;DİNÇ&quot; to &quot;dinç&quot; and &quot;DINÇ&quot; to &quot;dınç&quot; or vice-versa.</p>\n" }, { "answer_id": 3845060, "author": "ewwink", "author_id": 458214, "author_profile": "https://Stackoverflow.com/users/458214", "pm_score": 4, "selected": false, "text": "<p>Just an example for <code>toLowerCase()</code>, <code>toUpperCase()</code> and a prototype for the not yet available <code>toTitleCase()</code> or <code>toProperCase()</code>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>String.prototype.toTitleCase = function() {\n return this.split(' ').map(i =&gt; i[0].toUpperCase() + i.substring(1).toLowerCase()).join(' ');\n}\n\nString.prototype.toPropperCase = function() {\n return this.toTitleCase();\n}\n\nvar OriginalCase = 'Your Name';\nvar lowercase = OriginalCase.toLowerCase();\nvar upperCase = lowercase.toUpperCase();\nvar titleCase = upperCase.toTitleCase();\n\nconsole.log('Original: ' + OriginalCase);\nconsole.log('toLowerCase(): ' + lowercase);\nconsole.log('toUpperCase(): ' + upperCase);\nconsole.log('toTitleCase(): ' + titleCase);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 7453032, "author": "Dan", "author_id": 139361, "author_profile": "https://Stackoverflow.com/users/139361", "pm_score": 4, "selected": false, "text": "<p>I paid attention that lots of people <a href=\"http://www.google.com.ua/search?sourceid=chrome&amp;ie=UTF-8&amp;q=strtolower%20js\" rel=\"nofollow noreferrer\">are looking</a> for <code>strtolower()</code> in JavaScript. They are expecting the same function name as in other languages, and that's why this post is here.</p>\n<p>I would recommend using a <a href=\"http://www.quirksmode.org/js/strings.html#tocase\" rel=\"nofollow noreferrer\">native</a> JavaScript function:</p>\n<p><code>&quot;SomE StriNg&quot;.toLowerCase()</code></p>\n<p>Here's the function that behaves exactly the same as PHP's one (for those who are porting PHP code into JavaScript)</p>\n<pre><code>function strToLower (str) {\n return String(str).toLowerCase();\n}\n</code></pre>\n" }, { "answer_id": 10770658, "author": "Paul Gorbas", "author_id": 600889, "author_profile": "https://Stackoverflow.com/users/600889", "pm_score": 3, "selected": false, "text": "<p>Note that the function will <em>only</em> work on <em>string</em> objects.</p>\n<p>For instance, I was consuming a plugin, and was confused why I was getting a &quot;extension.tolowercase is not a function&quot; JavaScript error.</p>\n<pre><code> onChange: function(file, extension)\n {\n alert(&quot;extension.toLowerCase()=&gt;&quot; + extension.toLowerCase() + &quot;&lt;=&quot;);\n</code></pre>\n<p>Which produced the error &quot;extension.toLowerCase is not a function&quot;. So I tried this piece of code, which revealed the problem!</p>\n<pre><code>alert(&quot;(typeof extension)=&gt;&quot; + (typeof extension) + &quot;&lt;=&quot;);;\n</code></pre>\n<p>The output was &quot;(typeof extension)=&gt;object&lt;=&quot; - so aha, I was <em>not</em> getting a string var for my input. The fix is straightforward though - just force the darn thing into a String!:</p>\n<pre><code>var extension = String(extension);\n</code></pre>\n<p>After the cast, the <em>extension.toLowerCase()</em> function worked fine.</p>\n" }, { "answer_id": 17762625, "author": "JackSparrow", "author_id": 2309028, "author_profile": "https://Stackoverflow.com/users/2309028", "pm_score": 3, "selected": false, "text": "<p>Method or Function: toLowerCase(), toUpperCase()</p>\n<p>Description: These methods are used to cover a string or alphabet from lower case to upper case or vice versa. e.g: &quot;and&quot; to &quot;AND&quot;.</p>\n<p>Converting to Upper Case:</p>\n<p>Example Code:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script language=javascript&gt;\n var ss = &quot; testing case conversion method &quot;;\n var result = ss.toUpperCase();\n document.write(result);\n&lt;/script&gt;\n</code></pre>\n<p>Result: TESTING CASE CONVERSION METHOD</p>\n<p>Converting to Lower Case:</p>\n<p>Example Code:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script language=javascript&gt;\n var ss = &quot; TESTING LOWERCASE CONVERT FUNCTION &quot;;\n var result = ss.toLowerCase();\n document.write(result);\n&lt;/script&gt;\n</code></pre>\n<p>Result: testing lowercase convert function</p>\n<p>Explanation: In the above examples,</p>\n<ul>\n<li><p>toUpperCase() method converts any string to &quot;UPPER&quot; case letters.</p>\n</li>\n<li><p>toLowerCase() method converts any string to &quot;lower&quot; case letters.</p>\n</li>\n</ul>\n" }, { "answer_id": 33918207, "author": "Some Java Guy", "author_id": 387774, "author_profile": "https://Stackoverflow.com/users/387774", "pm_score": -1, "selected": false, "text": "<p>Try</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input type=&quot;text&quot; style=&quot;text-transform: uppercase&quot;&gt; &lt;!-- uppercase --&gt;\n&lt;input type=&quot;text&quot; style=&quot;text-transform: lowercase&quot;&gt; &lt;!-- lowercase --&gt;\n</code></pre>\n<p><a href=\"http://jsfiddle.net/oneofthelions/z45ygobL/\" rel=\"nofollow noreferrer\">Demo - JSFiddle</a></p>\n" }, { "answer_id": 46235553, "author": "Siddhartha", "author_id": 7840265, "author_profile": "https://Stackoverflow.com/users/7840265", "pm_score": 2, "selected": false, "text": "<p><strong>Opt 1: using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase\" rel=\"nofollow noreferrer\">toLowerCase()</a></strong></p>\n<pre><code>var x = 'ABC';\nx = x.toLowerCase();\n</code></pre>\n<p><strong>Opt 2: Using your own function</strong></p>\n<pre><code>function convertToLowerCase(str) {\n var result = '';\n\n for (var i = 0; i &lt; str.length; i++) {\n var code = str.charCodeAt(i);\n if (code &gt; 64 &amp;&amp; code &lt; 91) {\n result += String.fromCharCode(code + 32);\n } else {\n result += str.charAt(i);\n }\n }\n return result;\n}\n</code></pre>\n<p>Call it as:</p>\n<pre><code>x = convertToLowerCase(x);\n</code></pre>\n" }, { "answer_id": 50602049, "author": "Harun Or Rashid", "author_id": 4724147, "author_profile": "https://Stackoverflow.com/users/4724147", "pm_score": 2, "selected": false, "text": "<p>Simply use JS <code>toLowerCase()</code><br>\n<code>let v = \"Your Name\"\n let u = v.toLowerCase();</code> or<br>\n<code>let u = \"Your Name\".toLowerCase();</code></p>\n" }, { "answer_id": 55678237, "author": "Praveen", "author_id": 1175932, "author_profile": "https://Stackoverflow.com/users/1175932", "pm_score": -1, "selected": false, "text": "<p>You can use the in built .toLowerCase() method on JavaScript strings. Example:</p>\n<pre><code>var x = &quot;Hello&quot;;\nx.toLowerCase();\n</code></pre>\n" }, { "answer_id": 55868778, "author": "Abdurahman Popal", "author_id": 10020712, "author_profile": "https://Stackoverflow.com/users/10020712", "pm_score": -1, "selected": false, "text": "<p>Try this short way:</p>\n<pre><code>var lower = (str+&quot;&quot;).toLowerCase();\n</code></pre>\n" }, { "answer_id": 56174904, "author": "Javier Giovannini", "author_id": 1277165, "author_profile": "https://Stackoverflow.com/users/1277165", "pm_score": -1, "selected": false, "text": "<p>In case you want to build it yourself:</p>\n<pre><code>function toLowerCase(string) {\n\n let lowerCaseString = &quot;&quot;;\n\n for (let i = 0; i &lt; string.length; i++) {\n // Find ASCII charcode\n let charcode = string.charCodeAt(i);\n\n // If uppercase\n if (charcode &gt; 64 &amp;&amp; charcode &lt; 97) {\n // Convert to lowercase\n charcode = charcode + 32\n }\n\n // Back to char\n let lowercase = String.fromCharCode(charcode);\n\n // Append\n lowerCaseString = lowerCaseString.concat(lowercase);\n }\n\n return lowerCaseString\n}\n</code></pre>\n" }, { "answer_id": 67386662, "author": "Force Bolt", "author_id": 15478252, "author_profile": "https://Stackoverflow.com/users/15478252", "pm_score": 0, "selected": false, "text": "<pre><code>const str = 'Your Name';\n\n// convert string to lowercase\nconst lowerStr = str.toLowerCase();\n\n// print the new string\nconsole.log(lowerStr);\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5440/" ]
How can I convert a JavaScript string value to be in all lower case letters? Example: `"Your Name"` to `"your name"`
``` var lowerCaseName = "Your Name".toLowerCase(); ```
154,900
<p>I was wrestling with some Perl that uses hash references.</p> <p>In the end it turned out that my problem was the line:</p> <pre><code>$myhash{$key} |= {}; </code></pre> <p>That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value".</p> <p>Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference.</p> <p>Changing it to:</p> <pre><code>if( ! exists $myhash{$key}) { $myhash{$key} = {}; } </code></pre> <p>... made things work.</p> <p>So I don't have a <em>problem</em>. But I'm curious about what was going on.</p> <p>Can anyone explain?</p>
[ { "answer_id": 154916, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>my %myhash;\n$myhash{$key} ||= {};\n</code></pre>\n\n<p>You can't declare a hash <em>element</em> in a <code>my</code> clause, as far as I know. You declare the hash first, then add the element in.</p>\n\n<p>Edit: I see you've taken out the <code>my</code>. How about trying <code>||=</code> instead of <code>|=</code>? The former is idiomatic for \"lazy\" initialisation.</p>\n" }, { "answer_id": 154984, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 4, "selected": false, "text": "<p>Perl has shorthand assignment operators. The <code>||=</code> operator is often used to set default values for variables due to Perl's feature of having logical operators return the last value evaluated. The problem is that you used <code>|=</code> which is a <em>bitwise</em> or instead of <code>||=</code> which is a <em>logical</em> or.</p>\n\n<p>As of Perl 5.10 it's better to use <code>//=</code> instead. <code>//</code> is the logical defined-or operator and doesn't fail in the corner case where the current value is defined but false.</p>\n" }, { "answer_id": 154991, "author": "Kyle", "author_id": 2237619, "author_profile": "https://Stackoverflow.com/users/2237619", "pm_score": 2, "selected": false, "text": "<p><p>I think your problem was using \"<code>|=</code>\" (bitwise-or assignment) instead of \"<code>||=</code>\" (assign if false).\n<p>Note that your new code is not exactly equivalent. The difference is that \"<code>$myhash{$key} ||= {}</code>\" will replace existing-but-false values with a hash reference, but the new one won't. In practice, this is probably not relevant.</p>\n" }, { "answer_id": 155026, "author": "friedo", "author_id": 20745, "author_profile": "https://Stackoverflow.com/users/20745", "pm_score": 5, "selected": true, "text": "<p>The reason you're seeing an error about using a string as a hash reference is because you're using the wrong operator. <code>|=</code> means &quot;bitwise-or-assign.&quot; In other words,</p>\n<pre><code> $foo |= $bar;\n</code></pre>\n<p>is the same as</p>\n<pre><code> $foo = $foo | $bar\n</code></pre>\n<p>What's happening in your example is that your new anonymous hash reference is getting stringified, then bitwise-ORed with the value of <code>$myhash{$key}</code>. To confuse matters further, if <code>$myhash{$key}</code> is undefined at the time, the value is the simple stringification of the hash reference, which looks like <code>HASH(0x80fc284)</code>. So if you do a cursory inspection of the structure, it may <em>look</em> like a hash reference, but it's not. Here's some useful output via <code>Data::Dumper</code>:</p>\n<pre><code> perl -MData::Dumper -le '$hash{foo} |= { }; print Dumper \\%hash'\n $VAR1 = {\n 'foo' =&gt; 'HASH(0x80fc284)'\n };\n</code></pre>\n<p>And here's what you get when you use the correct operator:</p>\n<pre><code> perl -MData::Dumper -le '$hash{foo} ||= { }; print Dumper \\%hash'\n $VAR1 = {\n 'foo' =&gt; {}\n };\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7512/" ]
I was wrestling with some Perl that uses hash references. In the end it turned out that my problem was the line: ``` $myhash{$key} |= {}; ``` That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value". Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference. Changing it to: ``` if( ! exists $myhash{$key}) { $myhash{$key} = {}; } ``` ... made things work. So I don't have a *problem*. But I'm curious about what was going on. Can anyone explain?
The reason you're seeing an error about using a string as a hash reference is because you're using the wrong operator. `|=` means "bitwise-or-assign." In other words, ``` $foo |= $bar; ``` is the same as ``` $foo = $foo | $bar ``` What's happening in your example is that your new anonymous hash reference is getting stringified, then bitwise-ORed with the value of `$myhash{$key}`. To confuse matters further, if `$myhash{$key}` is undefined at the time, the value is the simple stringification of the hash reference, which looks like `HASH(0x80fc284)`. So if you do a cursory inspection of the structure, it may *look* like a hash reference, but it's not. Here's some useful output via `Data::Dumper`: ``` perl -MData::Dumper -le '$hash{foo} |= { }; print Dumper \%hash' $VAR1 = { 'foo' => 'HASH(0x80fc284)' }; ``` And here's what you get when you use the correct operator: ``` perl -MData::Dumper -le '$hash{foo} ||= { }; print Dumper \%hash' $VAR1 = { 'foo' => {} }; ```
154,902
<p>I wrote a program in C with Ubuntu Linux and now I need to port it over to a UNIX machine (or what I believe to be a UNIX box). It compiles fine on my Ubuntu with GCC but when I try to compile it with GCC on the UNIX box, it gives this error:</p> <pre><code>a.c: In function `goUpDir': a.c:44: parse error before `char' a.c:45: `newDir' undeclared (first use in this function) a.c:45: (Each undeclared identifier is reported only once a.c:45: for each function it appears in.) a.c: In function `goIntoDir': a.c:54: parse error before `char' a.c:57: `newDir' undeclared (first use in this function) a.c:57: `oldDir' undeclared (first use in this function) </code></pre> <p>The main problems seem to be the parse error before <code>char</code> (the others are related)</p> <pre><code>44 char newDir[50] = ""; 54 char* oldDir = (char*)get_current_dir_name(); </code></pre> <p>These are just simple C-style strings declarations. Is there a header file that I need to include to get it to work in UNIX?</p> <p>P.S. what is the command to see what version of unix and which version of gcc you are using? Knowing this will allow me to be more specific in my question.</p> <p>Thanks</p>
[ { "answer_id": 154930, "author": "Leahn Novash", "author_id": 5954, "author_profile": "https://Stackoverflow.com/users/5954", "pm_score": 3, "selected": true, "text": "<p>If you are compiling pure C, variables must be declared on the beggining of the functions. I mention this because most people compile their C programs using C++ compilers, which offers then some resources not normally available to pure C compilers, the most common example being the // comment lines.</p>\n" }, { "answer_id": 154937, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "<p>What UNIX is it? AIX, Ultrix, Minix, Xenix? </p>\n\n<p>GCC has a \"--version\" flag:</p>\n\n<pre><code>gcc --version\n</code></pre>\n" }, { "answer_id": 154938, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 0, "selected": false, "text": "<p>To display the GCC version:</p>\n\n<pre>gcc --version</pre>\n\n<p>It might help to show the function so we could see the surrounding code. That is often the problem with \"parse error before\" type errors.</p>\n" }, { "answer_id": 154943, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<p>How did you copy the file over? Is it possible that you inserted something that shouldn't be there?</p>\n\n<p>BTW: Please fix up your use of the code tag in your code - it's currently nearly impossible to read without using \"view source\" in my browser.</p>\n\n<p>As for you end questions:</p>\n\n<pre><code>uname -a\ngcc -v\n</code></pre>\n" }, { "answer_id": 154976, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>If you want to make sure your code is portable always use the -pedantic or -pedantic-errors.</p>\n\n<p>This will provide warnings/errors where your code strays from standards compliance.</p>\n\n<p>While we are on the subject. You should probably also turn on all the warnings. There are good reasons why the compiler warns you; when moving code from one platform to another these warnings are the source of potential bugs as the new hardware/OS/Compiler may not act the same as your current one.</p>\n\n<p>Also use the correct GCC frontend executable: g++ Will treat *.c files like C++ files unless you explicitly tell it not too. So if you are compiling real C then use gcc not g++.</p>\n\n<blockquote>\n <p>gcc -pedantic -Wall -Werror *.c<br>\n g++ -pedantic -Wall -Werror *.cpp</p>\n</blockquote>\n\n<p>To help with your specific problem it may be nice to see line 43. Though the error says line 44 a lot of problems are caused by the proceeding line having a problem and the problem not being detected by the parser until you get to the first lexeme on the next line.</p>\n" }, { "answer_id": 155219, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "<p>When trying to write portable code, the following compiler flags will tell you about a lot of problems <em>before</em> you get as far as trying to compile the code on the next platform:</p>\n\n<pre><code>-std=c89 -pedantic -Wall\n</code></pre>\n\n<p>If you only need to target GCC on other platforms, not any other compilers, then you could try:</p>\n\n<pre><code>-std=gnu89 -pedantic -Wall\n</code></pre>\n\n<p>But I'd guess this might allow GNU extensions on a newer GCC that aren't supported on an older one. I'm not sure.</p>\n\n<p>Note that although it would be nice if -pedantic was guaranteed to warn about all non-standard programs, it isn't. There are still some things it misses.</p>\n" }, { "answer_id": 155993, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>You will have to provide us with more context for the errors...at least one, probably several lines before lines 44 and 54. At a guess, if you give us the code from the start of the function definition before line 44 (perhaps line 40 or so) through to line 54 (or a few lines later - maybe line 60 - then we may be able to help. Something is up with the information before line 44 that is causing it to expect something other than 'char' at line 44; ditto (probably the same problem) at line 54.</p>\n" }, { "answer_id": 156357, "author": "Friedrich", "author_id": 15068, "author_profile": "https://Stackoverflow.com/users/15068", "pm_score": 1, "selected": false, "text": "<p>The information is insufficient. The code above is at least as intersting and one has to\nknow if ones talks about ANSI C89 or ANSI C99. The first answer is wrong in that broad sense.</p>\n\n<p>Regards\nFriedrich</p>\n" }, { "answer_id": 159480, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 1, "selected": false, "text": "<p>Steve,</p>\n\n<p>The first error message says \"<code>parse error</code> <strong><code>before</code></strong> <code>'char'</code>\". What is the code that <em>precedes</em> char? Is it a function declaration? Does it include any user-defined types or anything of the sort?</p>\n\n<p>The most likely source of this error is that something shortly <em>above</em> line 44 uses a type or macro that's declared in a header file... that header file may differ between your own Ubuntu system and the one you're trying to compile on.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I wrote a program in C with Ubuntu Linux and now I need to port it over to a UNIX machine (or what I believe to be a UNIX box). It compiles fine on my Ubuntu with GCC but when I try to compile it with GCC on the UNIX box, it gives this error: ``` a.c: In function `goUpDir': a.c:44: parse error before `char' a.c:45: `newDir' undeclared (first use in this function) a.c:45: (Each undeclared identifier is reported only once a.c:45: for each function it appears in.) a.c: In function `goIntoDir': a.c:54: parse error before `char' a.c:57: `newDir' undeclared (first use in this function) a.c:57: `oldDir' undeclared (first use in this function) ``` The main problems seem to be the parse error before `char` (the others are related) ``` 44 char newDir[50] = ""; 54 char* oldDir = (char*)get_current_dir_name(); ``` These are just simple C-style strings declarations. Is there a header file that I need to include to get it to work in UNIX? P.S. what is the command to see what version of unix and which version of gcc you are using? Knowing this will allow me to be more specific in my question. Thanks
If you are compiling pure C, variables must be declared on the beggining of the functions. I mention this because most people compile their C programs using C++ compilers, which offers then some resources not normally available to pure C compilers, the most common example being the // comment lines.
154,993
<p>I have an application where the contents of e-mails that get sent are stored in a .resx file.<br> This is an ASP.Net application, the .resx file lives in /App_GlobalResources </p> <p>When I need to send an e-mail, i'm reading this using: </p> <pre><code> HttpContext.GetGlobalResourceObject("MailContents", "EmailID").ToString </code></pre> <p>Now, I need to use the same mailing method from another project (not a website). The mailing method is in a DLL that all the projects in the solution share.</p> <p>In this other project, I obviously don't have an HttpContext.</p> <p>How can I read these resources?</p> <p>My current approach is, inside the Mailing class, check whether HttpContext.Current is null, and if so, use a separate method.<br> The separate method I'm looking at right now (after resigning myself to the fact that there's nothing better) is to have the path to the .resx file of the website stored in the app.config file, and somehow read that file.<br> I started trying with System.Resources.ResourceReader, but it looks like it wants a .resources file, not a .resx one.</p>
[ { "answer_id": 155027, "author": "Caerbanog", "author_id": 23190, "author_profile": "https://Stackoverflow.com/users/23190", "pm_score": -1, "selected": false, "text": "<p>Something is not right with your placement of resources.</p>\n\n<p>Either your resource belongs to the website and should be sent to the mailing method by parameter.</p>\n\n<p>Or, your resource belongs to the mailing API dll and should be kept there (.dll projects can have .resx files too). Then the mailing method should have no problem finding the resource, especcially if you embed it in the dll itself.</p>\n" }, { "answer_id": 155040, "author": "Daniel Magliola", "author_id": 3314, "author_profile": "https://Stackoverflow.com/users/3314", "pm_score": 3, "selected": true, "text": "<p>I think I answered my own question...<br>\nThere's a ResXResourceReader class. I couldn't find it because it's in the Windows Forms namespace, which is not included in my current DLL references.</p>\n\n<p>Unfortunately, this will only let me iterate through results, so i'll implement some cute caching (read: memoization) over it...</p>\n" }, { "answer_id": 190315, "author": "martin", "author_id": 8421, "author_profile": "https://Stackoverflow.com/users/8421", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The mailing method is in a DLL that\n all the projects in the solution\n share.</p>\n \n <p>In this other project, I obviously\n don't have an HttpContext.</p>\n</blockquote>\n\n<p>Yes you do. HttpContext is available in any dll called from a website, as long as the class library references System.Web. </p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/154993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
I have an application where the contents of e-mails that get sent are stored in a .resx file. This is an ASP.Net application, the .resx file lives in /App\_GlobalResources When I need to send an e-mail, i'm reading this using: ``` HttpContext.GetGlobalResourceObject("MailContents", "EmailID").ToString ``` Now, I need to use the same mailing method from another project (not a website). The mailing method is in a DLL that all the projects in the solution share. In this other project, I obviously don't have an HttpContext. How can I read these resources? My current approach is, inside the Mailing class, check whether HttpContext.Current is null, and if so, use a separate method. The separate method I'm looking at right now (after resigning myself to the fact that there's nothing better) is to have the path to the .resx file of the website stored in the app.config file, and somehow read that file. I started trying with System.Resources.ResourceReader, but it looks like it wants a .resources file, not a .resx one.
I think I answered my own question... There's a ResXResourceReader class. I couldn't find it because it's in the Windows Forms namespace, which is not included in my current DLL references. Unfortunately, this will only let me iterate through results, so i'll implement some cute caching (read: memoization) over it...
155,022
<p>What is the easiest way to find out how much memory an object uses in .NET?</p> <p>Preferably without having to resort to a third party tool. Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types.</p> <p>Some related posts:</p> <ul> <li><a href="https://stackoverflow.com/questions/109836/object-memory-analysis-in-net">Object Memory Analysis in .NET</a></li> <li><a href="https://stackoverflow.com/questions/151936/does-an-empty-array-in-net-use-any-space">Does an empty array in .NET use any space?</a></li> </ul>
[ { "answer_id": 155042, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 2, "selected": false, "text": "<p>Asked and answered here: <a href=\"https://stackoverflow.com/questions/51540/determine-how-much-memory-a-class-uses#51895\">Determine how much memory a class uses?</a></p>\n\n<p>The quick summary is that if you don't want to use a tool, you need to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms404386.aspx\" rel=\"nofollow noreferrer\">.NET Profiling API</a></p>\n\n<p>The Profiling API is amazingly powerful, but I don't think it would qualify as \"easy\" by any stretch of the imagination, so I would strongly recommend using a memory profiling tool - there are some free ones that are OK, and some not-too-expensive commercial ones (<a href=\"http://www.jetbrains.com/profiler/index.html\" rel=\"nofollow noreferrer\">JetBrains dotTrace</a> in particular) that are really good.</p>\n" }, { "answer_id": 155048, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 1, "selected": true, "text": "<p>you could also do something like this:</p>\n\n<pre><code>int startMem = GC.GetTotalMemory(true);\nYourClass c = new YourClass();\nint endMem = GC.GetTotalMemory(true);\nint usedMeme = endMem - startMem;\n</code></pre>\n" }, { "answer_id": 14629091, "author": "Kenzi", "author_id": 557646, "author_profile": "https://Stackoverflow.com/users/557646", "pm_score": 0, "selected": false, "text": "<p>Because of .NET's garbage-collected nature, it's somewhat difficult to measure how much memory is really being used. If you want to measure the size of a class instance, for example, does it include the memory used by instances that your instance points to?</p>\n\n<p><strong>If the answer is no</strong>, add up the size of all of the fields:\nUsing reflection, iterate through all members of the class; use Marshal.Sizeof(member.Type) for anything that typeof(ValueType).IsAssignableFrom(member.Type) - this measures primitive types and structs, all of which reside in the class's instance allocation. Every reference type (anything that isn't assignable to a valuetype) will take IntPtr.Size. There are a disgusting number of exceptions to this, but it might work for you.</p>\n\n<p><strong>If the answer is yes</strong>, you have a serious problem. Multiple things can reference a single instance, so if 'a' and 'b' both point to 'c', then <code>RecursiveSizeOf(a) + RecursiveSizeOf(b)</code> would be larger than <code>SimpleSizeOf(a) + SimpleSizeOf(b) + SimpleSizeOf(c)</code>.</p>\n\n<p>Even worse, measuring recursively can lead you down circular references, or lead you to objects you don't intend to measure - if a class is referencing a mutex, for example, that mutex may point to the thread that owns it. That thread may point to all of its local variables, which point to some C# framework structures... you may end up measuring your entire program.</p>\n\n<p>It might help to understand that a garbage-collected language like C# is somewhat \"fuzzy\" (from a completely non-technical sense) in the way it draws distinctions between objects and units of memory. This is a lot of what <code>Marshal</code> mitigates - marshaling rules ensure that the struct you're marshaling (or measuring) has a well-defined memory layout, and therefore a well-defined size. In which case, you should be using well-defined, marshalable structs if you intend on using Marhsal.SizeOf().</p>\n\n<p>Another option is serialization. This won't tell you specifically how much memory is in use, but it will give you a relative idea of the size of the object. But again, in order to serialize things, they have to have a well-defined layout (and therefore a well-defined size) - you accomplish by making the class appropriately serializable.</p>\n\n<p>I can post implementation examples if any of the above options appeal to you.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15985/" ]
What is the easiest way to find out how much memory an object uses in .NET? Preferably without having to resort to a third party tool. Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types. Some related posts: * [Object Memory Analysis in .NET](https://stackoverflow.com/questions/109836/object-memory-analysis-in-net) * [Does an empty array in .NET use any space?](https://stackoverflow.com/questions/151936/does-an-empty-array-in-net-use-any-space)
you could also do something like this: ``` int startMem = GC.GetTotalMemory(true); YourClass c = new YourClass(); int endMem = GC.GetTotalMemory(true); int usedMeme = endMem - startMem; ```
155,046
<p>I have two drop down menus that I want populated with identical data depending on what is selected on the parent drop down menu. Right now, I am using a javascript library that populates one child drop down menu based on a parent, but I need to have two drop down menus populated simultaneously.</p> <p>This javascript library contains a function called PrintOptions that is supposed to populate the dropdown menu when something is selected from the parent menu. I have tried calling the same function twice one for each drop down menu, but it doesn't seem to be working.</p> <p>This is where I got the library: <a href="http://www.javascripttoolbox.com/lib/dynamicoptionlist/documentation.php" rel="nofollow noreferrer">http://www.javascripttoolbox.com/lib/dynamicoptionlist/documentation.php</a></p>
[ { "answer_id": 155056, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 0, "selected": false, "text": "<p>In the event handler you have for your parent drop down, you are probably having some other code populate that child drop down. Simply add the code again, but instead reference the second drop down. That's the rough approach. There are some details and style guidance I'm leaving out, but that'll get the job done.</p>\n" }, { "answer_id": 155123, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 1, "selected": false, "text": "<p>Reading the document you list, it seems there's a section that allows you to specify multiple child components from the parent:</p>\n\n<pre>\nTo create the DynamicOptionList object, pass the names of the fields that are dependent on each other, with the parent field first.\nCreate the object by passing field names\n\nvar dol = new DynamicOptionList(\"Field1\",\"Child1\",\"Child2\");\n\nOr create an empty object and then pass the field names\n\nvar dol = new DynamicOptionList();\ndol.addDependentFields(\"Field1\",\"Child1\",\"Child2\");\n</pre>\n\n<p>Instead of trying to call the function more than once, just add the 2nd child component's name to the DynamicOptionList constructor, as in the first example above. As I read the docs that means whatever happens to Child1 will also happen to Child2 when Field1 is selected.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23597/" ]
I have two drop down menus that I want populated with identical data depending on what is selected on the parent drop down menu. Right now, I am using a javascript library that populates one child drop down menu based on a parent, but I need to have two drop down menus populated simultaneously. This javascript library contains a function called PrintOptions that is supposed to populate the dropdown menu when something is selected from the parent menu. I have tried calling the same function twice one for each drop down menu, but it doesn't seem to be working. This is where I got the library: <http://www.javascripttoolbox.com/lib/dynamicoptionlist/documentation.php>
Reading the document you list, it seems there's a section that allows you to specify multiple child components from the parent: ``` To create the DynamicOptionList object, pass the names of the fields that are dependent on each other, with the parent field first. Create the object by passing field names var dol = new DynamicOptionList("Field1","Child1","Child2"); Or create an empty object and then pass the field names var dol = new DynamicOptionList(); dol.addDependentFields("Field1","Child1","Child2"); ``` Instead of trying to call the function more than once, just add the 2nd child component's name to the DynamicOptionList constructor, as in the first example above. As I read the docs that means whatever happens to Child1 will also happen to Child2 when Field1 is selected.
155,065
<p>I am trying to implement a custom "broken image" icon to appear if I cannot load an image. To accomplish this, I used the brokenImageSkin parameter, but it renders the image at its true resolution, which ends up cutting off the image if the size of the control is constrained.</p> <pre><code> &lt;mx:Image brokenImageSkin="@Embed('/assets/placeholder.png')" source="http://www.example.com/bad_url.png"/&gt; </code></pre> <p>How can I scale the brokenImageSkin to a custom width and height?</p>
[ { "answer_id": 155214, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 2, "selected": true, "text": "<p>I see that in this example,\n<a href=\"http://blog.flexexamples.com/2008/03/02/setting-a-custom-broken-image-skin-for-the-image-control-in-flex/#more-538\" rel=\"nofollow noreferrer\">http://blog.flexexamples.com/2008/03/02/setting-a-custom-broken-image-skin-for-the-image-control-in-flex/#more-538</a>, there is an IO error event where you could set the width and height of the image.</p>\n" }, { "answer_id": 155361, "author": "Aaron", "author_id": 23965, "author_profile": "https://Stackoverflow.com/users/23965", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>Make a new class that extends ProgrammaticSkin. Embed your image using the [Embed] meta keyword and associate it with a variable of type Class (see the documentation for this)</p></li>\n<li><p>Override updateDisplaylist.</p></li>\n<li><p>Call graphics.clear() in this function.</p></li>\n<li><p>Call graphics.beginBitmapFill and then apply the appropriate dimensions and scaling based on the unscaledWidth and unscaledHeight passed in.</p></li>\n</ol>\n\n<p>This is way more complicated but it's the only way I know of to get more control out of a custom skinning operation like that.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5126/" ]
I am trying to implement a custom "broken image" icon to appear if I cannot load an image. To accomplish this, I used the brokenImageSkin parameter, but it renders the image at its true resolution, which ends up cutting off the image if the size of the control is constrained. ``` <mx:Image brokenImageSkin="@Embed('/assets/placeholder.png')" source="http://www.example.com/bad_url.png"/> ``` How can I scale the brokenImageSkin to a custom width and height?
I see that in this example, <http://blog.flexexamples.com/2008/03/02/setting-a-custom-broken-image-skin-for-the-image-control-in-flex/#more-538>, there is an IO error event where you could set the width and height of the image.
155,071
<p>Do you have a simple debounce routine handy to deal with a single switch input?</p> <p>This is a simple bare metal system without any OS.</p> <p>I would like to avoid a looping construct with a specific count, as the processor speed might fluctuate.</p>
[ { "answer_id": 155103, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "<p>To debounce, you want to ignore any switch up that lasts under a certain threshold. You can set a hardware timer on switch up, or use a flag set via periodic interrupt.</p>\n" }, { "answer_id": 155137, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 5, "selected": true, "text": "<p>I think you could learn a lot about this here: <a href=\"http://www.ganssle.com/debouncing.pdf\" rel=\"noreferrer\">http://www.ganssle.com/debouncing.pdf</a></p>\n\n<p>Your best bet is always to do this in hardware if possible, but there are some thoughts on software in there as well.</p>\n\n<p>Simple example code from TFA:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#define CHECK_MSEC 5 // Read hardware every 5 msec\n#define PRESS_MSEC 10 // Stable time before registering pressed\n#define RELEASE_MSEC 100 // Stable time before registering released\n// This function reads the key state from the hardware.\nextern bool_t RawKeyPressed();\n// This holds the debounced state of the key.\nbool_t DebouncedKeyPress = false;\n// Service routine called every CHECK_MSEC to\n// debounce both edges\nvoid DebounceSwitch1(bool_t *Key_changed, bool_t *Key_pressed)\n{\n static uint8_t Count = RELEASE_MSEC / CHECK_MSEC;\n bool_t RawState;\n *Key_changed = false;\n *Key_pressed = DebouncedKeyPress;\n RawState = RawKeyPressed();\n if (RawState == DebouncedKeyPress) {\n // Set the timer which allows a change from current state.\n if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC;\n else Count = PRESS_MSEC / CHECK_MSEC;\n } else {\n // Key has changed - wait for new state to become stable.\n if (--Count == 0) {\n // Timer expired - accept the change.\n DebouncedKeyPress = RawState;\n *Key_changed=true;\n *Key_pressed=DebouncedKeyPress;\n // And reset the timer.\n if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC;\n else Count = PRESS_MSEC / CHECK_MSEC;\n }\n }\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 155147, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>If you can get away with it, the best solution in hardware is to have the switch have two distinct states with no state between. That is, use a SPDT switch, with each pole feeding either the R or S lines of a flip/flop. Wired that way, the output of the flip/flop should be debounced.</p>\n" }, { "answer_id": 155160, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 2, "selected": false, "text": "<p>There's no single simple solution that works for all types of buttons. No matter what someone here tells you to use, you'll have to try it with your hardware, and see how well it works. And look at the signals on a scope, to make sure you really know what's going on. Rich B's link to the pdf looks like a good place to start.</p>\n" }, { "answer_id": 164741, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "<p>Simplest solutions are often the best, and I've found that simply only reading the switch state every N millseconds (between 10 and 50, depending on switches) has always worked for me. </p>\n\n<p>I've stripped out broken and complex debounce routines and replaced them with a simple slow poll, and the results have always been good enough that way. </p>\n\n<p>To implement it, you'll need a simple periodic timer interrupt on your system (assuming no RTOS support), but if you're used to programming it at the bare metal, that shouldn't be difficult to arrange.</p>\n\n<p>Note that this simple approach adds a delay to detection of the change in state. If a switch takes T ms to reach a new steady state, and it's polled every X ms, then the worst case delay for detecting the press is T+X ms. Your polling interval X <em>must</em> be larger than the worst-case bounce time T.</p>\n" }, { "answer_id": 206995, "author": "gthuffman", "author_id": 24592, "author_profile": "https://Stackoverflow.com/users/24592", "pm_score": 2, "selected": false, "text": "<p>I have used a majority vote method to debounce an input. I set up a simple three state shift register type of data structure, and shift each sample and take the best two out of three as the \"correct\" value. This is obviously a function of either your interrupt handler, or a poller, depending on what method is used to actually read the hardware.</p>\n\n<p>But, the best advice is to ask your friendly hardware designer to \"latch\" the value and allow you to clear this value when you get to it.</p>\n" }, { "answer_id": 235938, "author": "Justin Love", "author_id": 30203, "author_profile": "https://Stackoverflow.com/users/30203", "pm_score": 0, "selected": false, "text": "<p>What I usually do is have three or so variables the width of the input register. Every poll, usually from an interrupt, shift the values up one to make way for the new sample. Then I have a debounced variable formed by setting the logical-and of the samples, and clearing the inverse logical-or. i.e. (untested, from memory)</p>\n\n<pre><code>input3 = input2;\ninput2 = input1;\ninput1 = (*PORTA);\n\ndebounced |= input1 &amp; input2 &amp; input3;\ndebounced &amp;= (input1 | input2 | input3);\n</code></pre>\n\n<p>Here's an example:</p>\n\n<p>debounced has xxxx (where 'x' is \"whatever\")</p>\n\n<pre><code>input1 = 0110,\ninput2 = 1100,\ninput3 = 0100\n</code></pre>\n\n<p>With the information above,</p>\n\n<p>We need to switch only bit 2 to 1, and bit 0 to 0. The rest are still \"bouncing\".</p>\n\n<pre><code>debounced |= (0100); //set only bit 2\ndebounced &amp;= (1110); //clear only bit 0\n</code></pre>\n\n<p>The result is that now debounced = x1x0</p>\n" }, { "answer_id": 28154521, "author": "sorin", "author_id": 1665786, "author_profile": "https://Stackoverflow.com/users/1665786", "pm_score": 0, "selected": false, "text": "<p>The algorithm from ganssle.com could have a bug in it. I have the impression the following line</p>\n\n<pre><code>static uint8_t Count = RELEASE_MSEC / CHECK_MSEC;\n</code></pre>\n\n<p>should read</p>\n\n<pre><code>static uint8_t Count = PRESS_MSEC / CHECK_MSEC;\n</code></pre>\n\n<p>in order to debounce correctly the initial press.</p>\n" }, { "answer_id": 40812488, "author": "well but I'm", "author_id": 6292763, "author_profile": "https://Stackoverflow.com/users/6292763", "pm_score": 0, "selected": false, "text": "<p>At the hardware level the basic debouncing routine has to take into account the following segments of a physical key's (or switch's) behavior:</p>\n\n<p>Key sitting quietly->finger touches key and begins pushing down->key reaches bottom of travel and finger holds it there->finger begins releasing key and spring pushes key back up->finger releases key and key vibrates a bit until it quiesces</p>\n\n<p>All of these stages involve 2 pieces of metal scraping and rubbing and bumping against each other, jiggling the voltage up and down from 0 to maximum over periods of milliseconds, so there is electrical noise every step of the way:</p>\n\n<p>(1) Noise while the key is not being touched, caused by environmental issues like humidity, vibration, temperature changes, etc. causing voltage changes in the key contacts </p>\n\n<p>(2) Noise caused as the key is being pressed down</p>\n\n<p>(3) Noise as the key is being held down</p>\n\n<p>(4) Noise as the key is being released</p>\n\n<p>(5) Noise as the key vibrates after being released</p>\n\n<p>Here's the algorithm by which we basically guess that the key is being pressed by a person:</p>\n\n<p>read the state of the key, which can be \"might be pressed\", \"definitely is pressed\", \"definitely is not pressed\", \"might not be pressed\" (we're never really sure)</p>\n\n<p>loop while key \"might be\" pressed (if dealing with hardware, this is a voltage sample greater than some threshold value), until is is \"definitely not\" pressed (lower than the threshold voltage)\n(this is initialization, waiting for noise to quiesce, definition of \"might be\" and \"definitely not\" is dependent on specific application)</p>\n\n<p>loop while key is \"definitely not\" pressed, until key \"might be\" pressed</p>\n\n<p>when key \"might be\" pressed, begin looping and sampling the state of the key, and keep track of how long the key \"might be\" pressed \n- if the key goes back to \"might not be\" or \"definitely is not\" pressed state before a certain amount of time, restart the procedure\n- at a certain time (number of milliseconds) that you have chosen (usually through experimenting with different values) you decide that the sample value is no longer caused by noise, but is very likely caused by the key actually being held down by a human finger and you return the value \"pressed\"</p>\n\n<hr>\n\n<pre><code>while(keyvalue = maybepressed){\n//loop - wait for transition to notpressed\nsample keyvalue here;\nmaybe require it to be \"notpressed\" a number of times before you assume\nit's really notpressed;\n}\nwhile(keyvalue = notpressed){\n//loop - wait for transition to maybepressed\nsample keyvalue\nagain, maybe require a \"maybepressed\" value a number of times before you \ntransition\n}\nwhile(keyvalue=maybepressed){\n presstime+=1;\n if presstime&gt;required_presstime return pressed_affirmative\n }\n}\nreturn pressed_negative\n</code></pre>\n" }, { "answer_id": 54120805, "author": "Keith", "author_id": 10892754, "author_profile": "https://Stackoverflow.com/users/10892754", "pm_score": 0, "selected": false, "text": "<p>use integration and you'll be a happy camper. Works well for all switches.</p>\n\n<p>just increment a counter when read as high and decrement it when read as low and when the integrator reaches a limit (upper or lower) call the state (high or low).</p>\n" }, { "answer_id": 56303804, "author": "msimunic", "author_id": 9081348, "author_profile": "https://Stackoverflow.com/users/9081348", "pm_score": 0, "selected": false, "text": "<p>The whole concept is described well by Jack Ganssle. His solution posted as an answer to the original question is very good, but I find part of it not so clear how does it work.</p>\n\n<p>There are three main ways how to deal with switch bouncing:\n - using polling \n - using interrupts \n - combination of interrupts and pooling.</p>\n\n<p>As I deal mostly with embedded systems that are low-power or tend to be low-power so the answer from Keith to integrate is very reasonable to me.</p>\n\n<p>If you work with SPST push button type switch with one mechanically stable position then I would prefer the solution which works using a combination of interrupt and pooling.<br>\nLike this: use GPIO input interrupt to detect first edge (falling or rising, the opposite direction of un-actuated switch state). Under GPIO input ISR set flag about detection.<br>\nUse another interrupt for measuring time (ie. general purpose timer or SysTick) to count milliseconds. \nOn every SysTick increment (1 ms):<br>\nIF buttonFlag is true then call function to poll the state of push button (polling).<br>\nDo this for N consecutive SysTick increments then clear the flag. </p>\n\n<p>When you poll the button state use logic as you wish to decide button state like M consecutive readings same, average more than Z, count if the state, last X readings the same, etc. </p>\n\n<p>I think this approach should benefit from responsiveness on interrupt and lower power usage as there will be no button polling after N SysTick increments. There are no complicated interrupt modifications between various interrupts so the program code should be fairly simple and readable. </p>\n\n<p>Take into consideration things like: do you need to \"release\" button, do you need to detect long press and do you need action on button release. I don't like button action on button release, but some solutions work that way. </p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
Do you have a simple debounce routine handy to deal with a single switch input? This is a simple bare metal system without any OS. I would like to avoid a looping construct with a specific count, as the processor speed might fluctuate.
I think you could learn a lot about this here: <http://www.ganssle.com/debouncing.pdf> Your best bet is always to do this in hardware if possible, but there are some thoughts on software in there as well. Simple example code from TFA: ```cpp #define CHECK_MSEC 5 // Read hardware every 5 msec #define PRESS_MSEC 10 // Stable time before registering pressed #define RELEASE_MSEC 100 // Stable time before registering released // This function reads the key state from the hardware. extern bool_t RawKeyPressed(); // This holds the debounced state of the key. bool_t DebouncedKeyPress = false; // Service routine called every CHECK_MSEC to // debounce both edges void DebounceSwitch1(bool_t *Key_changed, bool_t *Key_pressed) { static uint8_t Count = RELEASE_MSEC / CHECK_MSEC; bool_t RawState; *Key_changed = false; *Key_pressed = DebouncedKeyPress; RawState = RawKeyPressed(); if (RawState == DebouncedKeyPress) { // Set the timer which allows a change from current state. if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC; else Count = PRESS_MSEC / CHECK_MSEC; } else { // Key has changed - wait for new state to become stable. if (--Count == 0) { // Timer expired - accept the change. DebouncedKeyPress = RawState; *Key_changed=true; *Key_pressed=DebouncedKeyPress; // And reset the timer. if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC; else Count = PRESS_MSEC / CHECK_MSEC; } } ``` }
155,074
<p>I'm a newbie when it comes to SQL. When creating a stored procedure with parameters as such:</p> <pre><code>@executed bit, @failure bit, @success bit, @testID int, @time float = 0, @name varchar(200) = '', @description varchar(200) = '', @executionDateTime nvarchar(max) = '', @message nvarchar(max) = '' </code></pre> <p>This is the correct form for default values in T-SQL? I have tried to use NULL instead of ''. </p> <p>When I attempted to execute this procedure through C# I get an error referring to the fact that description is expected but not provided. When calling it like this:</p> <pre><code> cmd.Parameters["@description"].Value = result.Description; </code></pre> <p>result.Description is null. Should this not default to NULL (well '' in my case right now) in SQL? </p> <p>Here's the calling command:</p> <pre><code> cmd.CommandText = "EXEC [dbo].insert_test_result @executed, @failure, @success, @testID, @time, @name, @description, @executionDateTime, @message;"; ... cmd.Parameters.Add("@description", SqlDbType.VarChar); cmd.Parameters.Add("@executionDateTime", SqlDbType.VarChar); cmd.Parameters.Add("@message", SqlDbType.VarChar); cmd.Parameters["@name"].Value = result.Name; cmd.Parameters["@description"].Value = result.Description; ... try { connection.Open(); cmd.ExecuteNonQuery(); } ... finally { connection.Close(); } </code></pre>
[ { "answer_id": 155082, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>A better approach would be to change the CommandText to just the name of the SP, and the CommandType to StoredProcedure - then the parameters will work much more cleanly:</p>\n\n<pre><code>cmd.CommandText = \"insert_test_result\";\ncmd.CommandType = CommandType.StoredProcedure;\n</code></pre>\n\n<p>This also allows simpler passing by name, rather than position.</p>\n\n<p>In general, ADO.NET wants DBNull.Value, not null. I just use a handy method that loops over my args and replaces any nulls with DBNull.Value - as simple as (wrapped):</p>\n\n<pre><code> foreach (IDataParameter param in command.Parameters)\n {\n if (param.Value == null) param.Value = DBNull.Value;\n }\n</code></pre>\n\n<p>However! Specifying a value with null is different to letting it assume the default value. If you want it to use the default, don't include the parameter in the command.</p>\n" }, { "answer_id": 155099, "author": "Dave Neeley", "author_id": 9660, "author_profile": "https://Stackoverflow.com/users/9660", "pm_score": 0, "selected": false, "text": "<p>If you aren't using named parameters, MSSQL takes the parameters in the order received (by index). I think there's an option for this on the cmd object.</p>\n\n<p>so your SQL should be more like </p>\n\n<pre><code>EXEC [dbo].insert_test_result \n@executed = @executed,\n@failure = @failure, \n@success = @success, \n@testID = @testID, \n@time = @time, \n@name = @name, \n@description = @description, \n@executionDateTime = @executionDateTime, \n@message = @message;\n</code></pre>\n" }, { "answer_id": 169417, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 0, "selected": false, "text": "<pre><code>\ncmd.CommandText = \"insert_test_result\";\ncmd.Parameters.Add(new SQLParameter(\"@description\", result.Description));\ncmd.Parameters.Add(new SQLParameter(\"@message\", result.Message));\ntry\n{\n connection.Open();\n cmd.ExecuteNonQuery();\n}\nfinally\n{\n connection.Close();\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
I'm a newbie when it comes to SQL. When creating a stored procedure with parameters as such: ``` @executed bit, @failure bit, @success bit, @testID int, @time float = 0, @name varchar(200) = '', @description varchar(200) = '', @executionDateTime nvarchar(max) = '', @message nvarchar(max) = '' ``` This is the correct form for default values in T-SQL? I have tried to use NULL instead of ''. When I attempted to execute this procedure through C# I get an error referring to the fact that description is expected but not provided. When calling it like this: ``` cmd.Parameters["@description"].Value = result.Description; ``` result.Description is null. Should this not default to NULL (well '' in my case right now) in SQL? Here's the calling command: ``` cmd.CommandText = "EXEC [dbo].insert_test_result @executed, @failure, @success, @testID, @time, @name, @description, @executionDateTime, @message;"; ... cmd.Parameters.Add("@description", SqlDbType.VarChar); cmd.Parameters.Add("@executionDateTime", SqlDbType.VarChar); cmd.Parameters.Add("@message", SqlDbType.VarChar); cmd.Parameters["@name"].Value = result.Name; cmd.Parameters["@description"].Value = result.Description; ... try { connection.Open(); cmd.ExecuteNonQuery(); } ... finally { connection.Close(); } ```
A better approach would be to change the CommandText to just the name of the SP, and the CommandType to StoredProcedure - then the parameters will work much more cleanly: ``` cmd.CommandText = "insert_test_result"; cmd.CommandType = CommandType.StoredProcedure; ``` This also allows simpler passing by name, rather than position. In general, ADO.NET wants DBNull.Value, not null. I just use a handy method that loops over my args and replaces any nulls with DBNull.Value - as simple as (wrapped): ``` foreach (IDataParameter param in command.Parameters) { if (param.Value == null) param.Value = DBNull.Value; } ``` However! Specifying a value with null is different to letting it assume the default value. If you want it to use the default, don't include the parameter in the command.
155,080
<p>I can get rootmenuitemlefthtml and rootmenuitemrighthtml to emit but not separator. Tried CDATA wrapping and setting SeparatorCssClass. I just want pipes between root menu items.</p> <pre><code>&lt;dnn:SOLPARTMENU runat="server" id="dnnSOLPARTMENU" Separator="&lt;![CDATA[|]]&gt;" SeparatorCssClass="MainMenu_SeparatorCSS" usearrows="false" userootbreadcrumbarrow="false" usesubmenubreadcrumbarrow="false" rootmenuitemlefthtml="&amp;nbsp;&amp;lt;span&amp;gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;" rootmenuitemrighthtml="&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;lt;/span&amp;gt;" rootmenuitemcssclass="rootmenuitem" rootmenuitemselectedcssclass="rootmenuitemselected" rootmenuitembreadcrumbcssclass="rootmenuitembreadcrumb" submenucssclass="submenu" submenuitemselectedcssclass="submenuitemselected" submenuitembreadcrumbcssclass="submenuitembreadcrumb" CSSNodeSelectedRoot="rootmenuitembreadcrumb" CSSNodeSelectedSub="submenuitembreadcrumb" MouseOverAction="False" MouseOutHideDelay="0" delaysubmenuload="true" level="Root" /&gt; </code></pre>
[ { "answer_id": 173792, "author": "Joe Brinkman", "author_id": 4820, "author_profile": "https://Stackoverflow.com/users/4820", "pm_score": 2, "selected": false, "text": "<p>While not a direct answer - you might want to shift to the DotNetNuke menu rather than using SolPart. SolPart is no longer officially supported and development work on this menu ceased almost two years ago. Jon Henning, the author of SolPart, wrote the DotNetNuke menu from the ground up and tried to address many of the shortcomings in the original SolPart menu.</p>\n" }, { "answer_id": 391474, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Check this for Solpartmenu:</p>\n\n<pre><code>&lt;dnn:SOLPARTMENU runat=\"server\" ID=\"dnnHorizontalSolpart\" ProviderName=\"SolpartMenuNavigationProvider\"\n ClearDefaults=\"True\" MenuBarCssClass=\"Hmain_dnnmenu_bar\" MenuContainerCssClass=\"Hmain_dnnmenu_container\"\n MenuItemCssClass=\"Hmain_dnnmenu_rootitem\" MenuItemSelCssClass=\"Hmain_dnnmenu_itemhoverRoot\"\n MenuIconCssClass=\"Hmain_dnnmenu_icon\" MenuBreakCssClass=\"Hmain_dnnmenu_break\"\n SubMenuCssClass=\"Hmain_dnnmenu_submenu\" SubMenuItemSelectedCssClass=\"Hmain_dnnmenu_subselected\"\n CSSNodeSelectedRoot=\"Hmain_dnnmenu_rootselected\" MenuEffectsMouseOverDisplay=\"None\"\n Separator=\"|\" SeparatorCssClass=\"Hmain_dnnmenu_separator\" UseArrows=\"False\" UseRootBreadCrumbArrow=\"False\" /&gt;\n</code></pre>\n\n\n\n<pre><code>.Hmain_dnnmenu_separator\n{\n background-color: Transparent;\n color: #C55203;\n font-family: Arial;\n font-size: 11px;\n}\n.Hmain_dnnmenu_bar\n{\n cursor: pointer;\n cursor: hand;\n height: 30px;\n background-color: Transparent;\n}\n.Hmain_dnnmenu_container\n{\n background-color: Transparent;\n}\n.Hmain_dnnmenu_rootitem\n{\n background-color: #DBDBDB;\n cursor: pointer;\n cursor: hand;\n color: #C55203;\n font-family: Arial;\n font-size: 11px;\n _height: 30px;\n _padding: 5px;\n vertical-align: middle;\n text-decoration:underline;\n}\n.Hmain_dnnmenu_rootitem td\n{\n font-family: Arial;\n font-size: 11px;\n _height: 30px;\n _padding: 5px;\n vertical-align: middle;\n}\n.Hmain_dnnmenu_itemhoverRoot\n{\n background-color: #DBDBDB;\n color: #C55203;\n cursor: pointer;\n cursor: hand;\n font-family: Arial;\n font-size: 11px;\n _height: 30px;\n _padding: 5px;\n text-decoration:underline;\n vertical-align: middle;\n}\n.Hmain_dnnmenu_icon\n{\n cursor: pointer;\n cursor: hand;\n}\n.Hmain_dnnmenu_submenu\n{\n background-color: #DBDBDB;\n border: solid 1px #B7B7B7;\n cursor: pointer;\n cursor: hand;\n color: #C55203;\n font-family: Arial;\n font-size: 11px;\n text-align: left;\n text-decoration:none;\n z-index: 1000;\n}\n.Hmain_dnnmenu_submenu td\n{\n border-bottom: solid 1px #B7B7B7;\n font-family: Arial;\n font-size: 11px;\n text-align: left;\n text-decoration:none;\n}\n.Hmain_dnnmenu_break\n{\n font-family: Arial;\n font-size: 11px;\n}\n.Hmain_dnnmenu_rootselected\n{\n color: #C55203;\n cursor: pointer;\n cursor: hand;\n font-size: 11px;\n font-weight: lighter;\n font-style: normal;\n font-family: Arial;\n white-space: nowrap;\n vertical-align: middle;\n text-decoration: None;\n}\n.Hmain_dnnmenu_submenu_itemhover\n{\n background-color: #C55203;\n color: #FFFFFF;\n font-family: Arial;\n font-size: 11px;\n}\n.Hmain_dnnmenu_subselected\n{\n background-color: #C55203;\n color: #FFFFFF;\n font-family: Arial;\n font-size: 11px;\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4489/" ]
I can get rootmenuitemlefthtml and rootmenuitemrighthtml to emit but not separator. Tried CDATA wrapping and setting SeparatorCssClass. I just want pipes between root menu items. ``` <dnn:SOLPARTMENU runat="server" id="dnnSOLPARTMENU" Separator="<![CDATA[|]]>" SeparatorCssClass="MainMenu_SeparatorCSS" usearrows="false" userootbreadcrumbarrow="false" usesubmenubreadcrumbarrow="false" rootmenuitemlefthtml="&nbsp;&lt;span&gt;&nbsp;&nbsp;&nbsp;" rootmenuitemrighthtml="&nbsp;&nbsp;&nbsp;&lt;/span&gt;" rootmenuitemcssclass="rootmenuitem" rootmenuitemselectedcssclass="rootmenuitemselected" rootmenuitembreadcrumbcssclass="rootmenuitembreadcrumb" submenucssclass="submenu" submenuitemselectedcssclass="submenuitemselected" submenuitembreadcrumbcssclass="submenuitembreadcrumb" CSSNodeSelectedRoot="rootmenuitembreadcrumb" CSSNodeSelectedSub="submenuitembreadcrumb" MouseOverAction="False" MouseOutHideDelay="0" delaysubmenuload="true" level="Root" /> ```
While not a direct answer - you might want to shift to the DotNetNuke menu rather than using SolPart. SolPart is no longer officially supported and development work on this menu ceased almost two years ago. Jon Henning, the author of SolPart, wrote the DotNetNuke menu from the ground up and tried to address many of the shortcomings in the original SolPart menu.
155,087
<p>Before you start firing at me, I'm NOT looking to do this, but someone in <a href="https://stackoverflow.com/questions/154698/how-can-i-keep-a-class-from-being-inherited-in-c">another post</a> said it was possible. How is it possible? I've never heard of inheriting from anything using reflection. But I've seen some strange things...</p>
[ { "answer_id": 155126, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>It <strong><em>MIGHT</em></strong> (would increase the size if I could). According to the guys on freenode, it would involved modifying the byte code, using Reflection.Emit, and handing the JIT a new set of byte code.</p>\n\n<p>Not that I <strong>KNOW</strong> how ... it was just what they thought.</p>\n" }, { "answer_id": 155132, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "<p>The other poster may have been thinking more along the lines of Reflection.Emit rather than the more usual read-only Reflection APIs.</p>\n\n<p>However, still isn't possible (at least according to <a href=\"http://www.devx.com/dotnet/Article/28783/1954\" rel=\"nofollow noreferrer\">this article</a>). But it is certainly possible to screw somethings up with Reflection.Emit that are not trapped until you try to actually execute the emitted code.</p>\n" }, { "answer_id": 155185, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": true, "text": "<p>Without virtual functions to override, there's not much point in subclassing a sealed class.</p>\n\n<p>If you try write a sealed class with a virtual function in it, you get the following compiler error:</p>\n\n<pre><code>// error CS0549: 'Seal.GetName()' is a new virtual member in sealed class 'Seal'\n</code></pre>\n\n<p>However, you can get virtual functions into sealed classes by declaring them in a base class (like this),</p>\n\n<pre><code>public abstract class Animal\n{\n private readonly string m_name;\n\n public virtual string GetName() { return m_name; }\n\n public Animal( string name )\n { m_name = name; }\n}\n\npublic sealed class Seal : Animal\n{\n public Seal( string name ) : base(name) {}\n}\n</code></pre>\n\n<p>The problem still remains though, I can't see how you could sneak past the compiler to let you declare a subclass. I tried using IronRuby (ruby is the hackiest of all the hackety languages) but even it wouldn't let me.</p>\n\n<p>The 'sealed' part is embedded into the MSIL, so I'd guess that the CLR itself actually enforces this. You'd have to load the code, dissassemble it, remove the 'sealed' bit, then reassemble it, and load the new version.</p>\n" }, { "answer_id": 156599, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 4, "selected": false, "text": "<p>I'm sorry for posting incorrect assumptions in the other thread, I failed to recall correctly. Using the following example, using Reflection.Emit, shows how to derive from another class, but it fails at runtime throwing an TypeLoadException.</p>\n\n<pre><code>sealed class Sealed\n{\n public int x;\n public int y;\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n AppDomain ad = Thread.GetDomain();\n AssemblyName an = new AssemblyName();\n an.Name = \"MyAssembly\";\n AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);\n ModuleBuilder mb = ab.DefineDynamicModule(\"MyModule\");\n TypeBuilder tb = mb.DefineType(\"MyType\", TypeAttributes.Class, typeof(Sealed));\n\n // Following throws TypeLoadException: Could not load type 'MyType' from\n // assembly 'MyAssembly' because the parent type is sealed.\n Type t = tb.CreateType();\n }\n}\n</code></pre>\n" }, { "answer_id": 937631, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Create a new class called GenericKeyValueBase</p>\n\n<p>put this in it</p>\n\n<pre><code> public class GenericKeyValueBase&lt;TKey,TValue&gt;\n {\n public TKey Key;\n public TValue Value;\n\n public GenericKeyValueBase(TKey ItemKey, TValue ItemValue)\n {\n Key = ItemKey;\n Value = ItemValue;\n }\n }\n</code></pre>\n\n<p>And inherit from that plus you can add additional extension methods for Add/Remove (AddAt and RemoveAt) to your new derived class (and make it a collection/dictionary) if you are feeling really cool.</p>\n\n<p>A simple implentation example where you would use a normal System.Collections.Generic.KeyValuePair for a base, but instead can use the above code</p>\n\n<pre><code> class GenericCookieItem&lt;TCookieKey, TCookieValue&gt; : GenericKeyValueBase&lt;TCookieKey,TCookieValue&gt;\n {\n public GenericCookieItem(TCookieKey KeyValue, TCookieValue ItemValue) : base(KeyValue, ItemValue)\n {\n }\n }\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
Before you start firing at me, I'm NOT looking to do this, but someone in [another post](https://stackoverflow.com/questions/154698/how-can-i-keep-a-class-from-being-inherited-in-c) said it was possible. How is it possible? I've never heard of inheriting from anything using reflection. But I've seen some strange things...
Without virtual functions to override, there's not much point in subclassing a sealed class. If you try write a sealed class with a virtual function in it, you get the following compiler error: ``` // error CS0549: 'Seal.GetName()' is a new virtual member in sealed class 'Seal' ``` However, you can get virtual functions into sealed classes by declaring them in a base class (like this), ``` public abstract class Animal { private readonly string m_name; public virtual string GetName() { return m_name; } public Animal( string name ) { m_name = name; } } public sealed class Seal : Animal { public Seal( string name ) : base(name) {} } ``` The problem still remains though, I can't see how you could sneak past the compiler to let you declare a subclass. I tried using IronRuby (ruby is the hackiest of all the hackety languages) but even it wouldn't let me. The 'sealed' part is embedded into the MSIL, so I'd guess that the CLR itself actually enforces this. You'd have to load the code, dissassemble it, remove the 'sealed' bit, then reassemble it, and load the new version.
155,101
<p>When I parse my xml file (variable f) in this method, I get an error </p> <blockquote> <p>C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)</p> </blockquote> <p>I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors?</p> <pre><code>private static Document getDoc(File f, String docId) throws Exception{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); return doc; } </code></pre>
[ { "answer_id": 155118, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I know I do not have the dtd, nor do I need it.</p>\n</blockquote>\n\n<p>I am suspicious of this statement; does your document contain any entity references? If so, you definitely need the DTD.</p>\n\n<p>Anyway, the usual way of preventing this from happening is using an XML catalog to define a local path for \"map.dtd\".</p>\n" }, { "answer_id": 155330, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": false, "text": "<p>here's another user who got the same issue : <a href=\"http://forums.sun.com/thread.jspa?threadID=284209&amp;forumID=34\" rel=\"nofollow noreferrer\">http://forums.sun.com/thread.jspa?threadID=284209&amp;forumID=34</a></p>\n\n<p>user ddssot on that post says</p>\n\n<pre><code>myDocumentBuilder.setEntityResolver(new EntityResolver() {\n public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId)\n throws SAXException, java.io.IOException\n {\n if (publicId.equals(\"--myDTDpublicID--\"))\n // this deactivates the open office DTD\n return new InputSource(new ByteArrayInputStream(\"&lt;?xml version='1.0' encoding='UTF-8'?&gt;\".getBytes()));\n else return null;\n }\n});\n</code></pre>\n\n<p>The user further mentions \"As you can see, when the parser hits the DTD, the entity resolver is called. I recognize my DTD with its specific ID and return an empty XML doc instead of the real DTD, stopping all validation...\"</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 155353, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 7, "selected": true, "text": "<p>A similar approach to the one suggested by <a href=\"https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references#155330\">@anjanb</a></p>\n\n<pre><code> builder.setEntityResolver(new EntityResolver() {\n @Override\n public InputSource resolveEntity(String publicId, String systemId)\n throws SAXException, IOException {\n if (systemId.contains(\"foo.dtd\")) {\n return new InputSource(new StringReader(\"\"));\n } else {\n return null;\n }\n }\n });\n</code></pre>\n\n<p>I found that simply returning an empty InputSource worked just as well?</p>\n" }, { "answer_id": 155874, "author": "jt.", "author_id": 4362, "author_profile": "https://Stackoverflow.com/users/4362", "pm_score": 7, "selected": false, "text": "<p>Try setting features on the DocumentBuilderFactory: </p>\n\n<pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n\ndbf.setValidating(false);\ndbf.setNamespaceAware(true);\ndbf.setFeature(\"http://xml.org/sax/features/namespaces\", false);\ndbf.setFeature(\"http://xml.org/sax/features/validation\", false);\ndbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\ndbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\nDocumentBuilder db = dbf.newDocumentBuilder();\n...\n</code></pre>\n\n<p>Ultimately, I think the options are specific to the parser implementation. <a href=\"http://xerces.apache.org/xerces2-j/features.html\" rel=\"noreferrer\">Here is some documentation for Xerces2</a> if that helps.</p>\n" }, { "answer_id": 5819461, "author": "Peter J", "author_id": 729412, "author_profile": "https://Stackoverflow.com/users/729412", "pm_score": 3, "selected": false, "text": "<p>I found an issue where the DTD file was in the jar file along with the XML. I solved the issue based on the examples here, as follows: -</p>\n\n<pre><code>DocumentBuilder db = dbf.newDocumentBuilder();\ndb.setEntityResolver(new EntityResolver() {\n public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n if (systemId.contains(\"doc.dtd\")) {\n InputStream dtdStream = MyClass.class\n .getResourceAsStream(\"/my/package/doc.dtd\");\n return new InputSource(dtdStream);\n } else {\n return null;\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 40529465, "author": "Shoaib Khan", "author_id": 2149956, "author_profile": "https://Stackoverflow.com/users/2149956", "pm_score": 3, "selected": false, "text": "<p><strong>Source XML (With DTD)</strong></p>\n\n<pre><code>&lt;!DOCTYPE MYSERVICE SYSTEM \"./MYSERVICE.DTD\"&gt;\n&lt;MYACCSERVICE&gt;\n &lt;REQ_PAYLOAD&gt;\n &lt;ACCOUNT&gt;1234567890&lt;/ACCOUNT&gt;\n &lt;BRANCH&gt;001&lt;/BRANCH&gt;\n &lt;CURRENCY&gt;USD&lt;/CURRENCY&gt;\n &lt;TRANS_REFERENCE&gt;201611100000777&lt;/TRANS_REFERENCE&gt;\n &lt;/REQ_PAYLOAD&gt;\n&lt;/MYACCSERVICE&gt;\n</code></pre>\n\n<p>Java DOM implementation for accepting above XML as String and removing DTD declaration </p>\n\n<pre><code>public Document removeDTDFromXML(String payload) throws Exception {\n\n System.out.println(\"### Payload received in XMlDTDRemover: \" + payload);\n\n Document doc = null;\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n try {\n\n dbf.setValidating(false);\n dbf.setNamespaceAware(true);\n dbf.setFeature(\"http://xml.org/sax/features/namespaces\", false);\n dbf.setFeature(\"http://xml.org/sax/features/validation\", false);\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\n DocumentBuilder db = dbf.newDocumentBuilder();\n\n InputSource is = new InputSource();\n is.setCharacterStream(new StringReader(payload));\n doc = db.parse(is); \n\n } catch (ParserConfigurationException e) {\n System.out.println(\"Parse Error: \" + e.getMessage());\n return null;\n } catch (SAXException e) {\n System.out.println(\"SAX Error: \" + e.getMessage());\n return null;\n } catch (IOException e) {\n System.out.println(\"IO Error: \" + e.getMessage());\n return null;\n }\n return doc;\n\n}\n</code></pre>\n\n<p><strong>Destination XML (Without DTD)</strong></p>\n\n<pre><code>&lt;MYACCSERVICE&gt;\n &lt;REQ_PAYLOAD&gt;\n &lt;ACCOUNT&gt;1234567890&lt;/ACCOUNT&gt;\n &lt;BRANCH&gt;001&lt;/BRANCH&gt;\n &lt;CURRENCY&gt;USD&lt;/CURRENCY&gt;\n &lt;TRANS_REFERENCE&gt;201611100000777&lt;/TRANS_REFERENCE&gt;\n &lt;/REQ_PAYLOAD&gt;\n&lt;/MYACCSERVICE&gt; \n</code></pre>\n" }, { "answer_id": 60079698, "author": "McCoy", "author_id": 2816092, "author_profile": "https://Stackoverflow.com/users/2816092", "pm_score": 0, "selected": false, "text": "<p>I'm working with sonarqube, and sonarlint for eclipse showed me <strong>Untrusted XML should be parsed without resolving external data (squid:S2755)</strong></p>\n\n<p>I managed to solve it using:</p>\n\n<pre><code> factory = DocumentBuilderFactory.newInstance();\n\n factory.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true);\n\n // If you can't completely disable DTDs, then at least do the following:\n // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities\n // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities\n // JDK7+ - http://xml.org/sax/features/external-general-entities\n factory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n\n // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities\n // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities\n // JDK7+ - http://xml.org/sax/features/external-parameter-entities\n factory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n\n // Disable external DTDs as well\n factory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\n // and these as well, per Timothy Morgan's 2014 paper: \"XML Schema, DTD, and Entity Attacks\"\n factory.setXIncludeAware(false);\n factory.setExpandEntityReferences(false);\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
When I parse my xml file (variable f) in this method, I get an error > > C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified) > > > I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors? ``` private static Document getDoc(File f, String docId) throws Exception{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); return doc; } ```
A similar approach to the one suggested by [@anjanb](https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references#155330) ``` builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("foo.dtd")) { return new InputSource(new StringReader("")); } else { return null; } } }); ``` I found that simply returning an empty InputSource worked just as well?
155,105
<p>I am getting the following error when I put class files in subfolders of my App_Code folder:</p> <p>errorCS0246: The type or namespace name 'MyClassName' could not be found (are you missing a using directive or an assembly reference?)</p> <p>This class is not in a namespace at all. Any ideas?</p>
[ { "answer_id": 155111, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Is it possible that you haven't set the folder as an application in IIS (or your web server)? If not, then the App_Code that gets used is that from the <em>parent</em> folder (or the next application upwards).</p>\n\n<p>Ensure that the folder is marked as an application, and uses the correct version of ASP.NET.</p>\n" }, { "answer_id": 155143, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>As you add folders to your app_code, they are getting separated by different namespaces, if I recall correctly, using the default namespace as the root, then adding for each folder.</p>\n" }, { "answer_id": 155149, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 5, "selected": true, "text": "<p>You need to add codeSubDirectories to your compilation element in web.config</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;compilation&gt;\n &lt;codeSubDirectories&gt;\n &lt;add directoryName=\"View\"/&gt;\n &lt;/codeSubDirectories&gt;\n &lt;/compilation&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 7082918, "author": "Firoj Husen Shaikh", "author_id": 897264, "author_profile": "https://Stackoverflow.com/users/897264", "pm_score": 4, "selected": false, "text": "<p>Check for BuildAction property of file. This should be set to \"Compile\"</p>\n" }, { "answer_id": 8047421, "author": "27k1", "author_id": 835921, "author_profile": "https://Stackoverflow.com/users/835921", "pm_score": 1, "selected": false, "text": "<p>It might not be the correct way but I find it the easiest.</p>\n\n<p>Create the class in the main Folder as usual, then move it with your mouse to your sub-folder. Re-compile and all should be fine.</p>\n" }, { "answer_id": 11479397, "author": "TonyH", "author_id": 657764, "author_profile": "https://Stackoverflow.com/users/657764", "pm_score": 0, "selected": false, "text": "<p>In Visual Studio (2010 at least, but I recall past versions too), you can right click on the folder, within Solution Explorer, and then choose \"Include in Project\".</p>\n\n<p>Then on the properties tab for each file (or select them all at once), you choose \"Compile\" for the \"Build Action\" property.</p>\n\n<p>This worked for me.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18926/" ]
I am getting the following error when I put class files in subfolders of my App\_Code folder: errorCS0246: The type or namespace name 'MyClassName' could not be found (are you missing a using directive or an assembly reference?) This class is not in a namespace at all. Any ideas?
You need to add codeSubDirectories to your compilation element in web.config ``` <configuration> <system.web> <compilation> <codeSubDirectories> <add directoryName="View"/> </codeSubDirectories> </compilation> </system.web> </configuration> ```
155,152
<p>I'm building a form with php/mysql. I've got a table with a list of locations and sublocations. Each sublocation has a parent location. A column "parentid" references another locationid in the same table. I now want to load these values into a dropdown in the following manner:</p> <pre><code>--Location 1 ----Sublocation 1 ----Sublocation 2 ----Sublocation 3 --Location 2 ----Sublocation 4 ----Sublocation 5 </code></pre> <p>etc. etc.</p> <p>Did anyone get an elegant solution for doing this?</p>
[ { "answer_id": 155159, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 1, "selected": false, "text": "<p>Are you looking for something like the <a href=\"http://www.w3schools.com/TAGS/tag_optgroup.asp\" rel=\"nofollow noreferrer\">OPTGROUP</a> tag?</p>\n" }, { "answer_id": 155175, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 0, "selected": false, "text": "<p>optgroup is definitely the way to go. It's actually what it's for,</p>\n\n<p>For example usage, view source of <a href=\"http://www.grandhall.eu/tips/submit/\" rel=\"nofollow noreferrer\">http://www.grandhall.eu/tips/submit/</a> - the selector under \"Grandhall Grill Used\".</p>\n" }, { "answer_id": 155177, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>You can use and space/dash indentation in the actual HTML. You'll need a recusrive loop to build it though. Something like:</p>\n\n<pre><code>&lt;?php\n\n$data = array(\n 'Location 1' =&gt; array(\n 'Sublocation1',\n 'Sublocation2',\n 'Sublocation3' =&gt; array(\n 'SubSublocation1',\n ),\n 'Location2'\n);\n\n$output = '&lt;select name=\"location\"&gt;' . PHP_EOL;\n\nfunction build_items($input, $output)\n{\n if(is_array($input))\n {\n $output .= '&lt;optgroup&gt;' . $key . '&lt;/optgroup&gt;' . PHP_EOL;\n foreach($input as $key =&gt; $value)\n {\n $output = build_items($value, $output);\n }\n }\n else\n {\n $output .= '&lt;option&gt;' . $value . '&lt;/option&gt;' . PHP_EOL;\n }\n\n return $output;\n}\n\n$output = build_items($data, $output);\n\n$output .= '&lt;/select&gt;' . PHP_EOL;\n\n?&gt;\n</code></pre>\n\n<p>Or something similar ;)</p>\n" }, { "answer_id": 155208, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": true, "text": "<p>NOTE: This is only psuedo-code.. I didn't try running it, though you should be able to adjust the concepts to what you need.</p>\n\n<pre><code>$parentsql = \"SELECT parentid, parentname FROM table\";\n\n $result = mysql_query($parentsql);\n print \"&lt;select&gt;\";\n while($row = mysql_fetch_assoc($result)){\n $childsql = \"SELECT childID, childName from table where parentid=\".$row[\"parentID\"];\n $result2 = mysql_query($childsql);\n print \"&lt;optgroup label=\\\".$row[\"parentname\"].\"\\\"&gt;\";\n while($row2 = mysql_fetch_assoc($result)){\n print \"&lt;option value=\\\"\".$row[\"childID\"].\"\\\"&gt;\".$row[\"childName\"].\"&lt;/option&gt;\\n\";\n }\n print \"&lt;/optgroup&gt;\";\n}\n print \"&lt;/select&gt;\";\n</code></pre>\n\n<p>With BaileyP's valid criticism in mind, here's how to do it WITHOUT the overhead of calling multiple queries in every loop:</p>\n\n<pre><code>$sql = \"SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName\"; \n$result = mysql_query($sql);\n$currentParent = \"\";\n\nprint \"&lt;select&gt;\";\nwhile($row = mysql_fetch_assoc($result)){\n if($currentParent != $row[\"parentID\"]){\n if($currentParent != \"\"){\n print \"&lt;/optgroup&gt;\";\n }\n print \"&lt;optgroup label=\\\".$row[\"parentName\"].\"\\\"&gt;\";\n $currentParent = $row[\"parentName\"];\n }\n\n print \"&lt;option value=\\\"\".$row[\"childID\"].\"\\\"&gt;\".$row[\"childName\"].\"&lt;/option&gt;\\n\";\n}\nprint \"&lt;/optgroup&gt;\"\nprint \"&lt;/select&gt;\";\n</code></pre>\n" }, { "answer_id": 155530, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>Ideally, you'd select all this data in the proper order right out of the database, then just loop over that for output. Here's my take on what you're asking for</p>\n\n<pre><code>&lt;?php\n/*\nAssuming data that looks like this\n\nlocations\n+----+-----------+-------+\n| id | parent_id | descr |\n+----+-----------+-------+\n| 1 | null | Foo |\n| 2 | null | Bar |\n| 3 | 1 | Doe |\n| 4 | 2 | Rae |\n| 5 | 1 | Mi |\n| 6 | 2 | Fa |\n+----+-----------+-------+\n*/\n\n$result = mysql_query( \"SELECT id, parent_id, descr FROM locations order by coalesce(id, parent_id), descr\" );\n\necho \"&lt;select&gt;\";\nwhile ( $row = mysql_fetch_object( $result ) )\n{\n $optionName = htmlspecialchars( ( is_null( $row-&gt;parent_id ) ) ? \"--{$row-&gt;descr}\" : \"----{$row-&gt;desc}r\", ENT_COMPAT, 'UTF-8' );\n echo \"&lt;option value=\\\"{$row-&gt;id}\\\"&gt;$optionName&lt;/option&gt;\";\n}\necho \"&lt;/select&gt;\";\n</code></pre>\n\n<p>If you don't like the use of the <code>coalesce()</code> function, you can add a \"display_order\" column to this table that you can manually set, and then use for the <code>ORDER BY</code>.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22837/" ]
I'm building a form with php/mysql. I've got a table with a list of locations and sublocations. Each sublocation has a parent location. A column "parentid" references another locationid in the same table. I now want to load these values into a dropdown in the following manner: ``` --Location 1 ----Sublocation 1 ----Sublocation 2 ----Sublocation 3 --Location 2 ----Sublocation 4 ----Sublocation 5 ``` etc. etc. Did anyone get an elegant solution for doing this?
NOTE: This is only psuedo-code.. I didn't try running it, though you should be able to adjust the concepts to what you need. ``` $parentsql = "SELECT parentid, parentname FROM table"; $result = mysql_query($parentsql); print "<select>"; while($row = mysql_fetch_assoc($result)){ $childsql = "SELECT childID, childName from table where parentid=".$row["parentID"]; $result2 = mysql_query($childsql); print "<optgroup label=\".$row["parentname"]."\">"; while($row2 = mysql_fetch_assoc($result)){ print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n"; } print "</optgroup>"; } print "</select>"; ``` With BaileyP's valid criticism in mind, here's how to do it WITHOUT the overhead of calling multiple queries in every loop: ``` $sql = "SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName"; $result = mysql_query($sql); $currentParent = ""; print "<select>"; while($row = mysql_fetch_assoc($result)){ if($currentParent != $row["parentID"]){ if($currentParent != ""){ print "</optgroup>"; } print "<optgroup label=\".$row["parentName"]."\">"; $currentParent = $row["parentName"]; } print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n"; } print "</optgroup>" print "</select>"; ```
155,164
<p>I am getting the following error:</p> <pre><code>Open OLE error code:80004005 in Microsoft OLE DB Provider for SQL Server [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied. HRESULT error code:0×80020009 Exception occurred. </code></pre> <p>I have tried following the directions <a href="http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer" rel="nofollow noreferrer">here</a> with no luck.</p> <p>Any ideas?</p> <p><strong><em>FIXED</em></strong></p> <p>My specific issue I believe was related to having to many mixed systems installed on my laptop. I had Visual Studio 2005 and 2008 components and SQL Server Management Standard loaded with SQL Server Express Edition as well as various other components that might have affected the stability of my environment. Once I reloaded Vista and went back through the steps <a href="http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer" rel="nofollow noreferrer">from the link above</a> it worked without issue.</p> <p>I only loaded the Express Editions of SQL Server and SQL Server Management Studio.</p>
[ { "answer_id": 155211, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>Usually a authentication/permissions error.</p>\n\n<p>Is the SQL Server on the same box as the web server, review the accounts they are running under, and review the type of connection you are making (integrated or otherwise)?</p>\n" }, { "answer_id": 155732, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>Random guess: By default SQL Server (express, at least anyway) does NOT enable network access. The SQL Admin manager tools connect to it using named pipes, however rails most likely will be trying to use TCP.</p>\n" }, { "answer_id": 587621, "author": "FortunateDuke", "author_id": 453046, "author_profile": "https://Stackoverflow.com/users/453046", "pm_score": 1, "selected": true, "text": "<p>My specifc issue I believe was related to having to many mixed systems installed on my laptop. I had Visual Studio 2005 and 2008 componets and SQL Server Managment Standard loaded with SQL Server Express Edition as well as various other componets that might have effected the stability of my envirnomnet. Once I reloaded Vista and went back through the steps on <a href=\"http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer\" rel=\"nofollow noreferrer\">http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer</a> it worked without issue.</p>\n\n<p>I only loaded the Express Editions of SQL Server and SQL Server Management Studio</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453046/" ]
I am getting the following error: ``` Open OLE error code:80004005 in Microsoft OLE DB Provider for SQL Server [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied. HRESULT error code:0×80020009 Exception occurred. ``` I have tried following the directions [here](http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer) with no luck. Any ideas? ***FIXED*** My specific issue I believe was related to having to many mixed systems installed on my laptop. I had Visual Studio 2005 and 2008 components and SQL Server Management Standard loaded with SQL Server Express Edition as well as various other components that might have affected the stability of my environment. Once I reloaded Vista and went back through the steps [from the link above](http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer) it worked without issue. I only loaded the Express Editions of SQL Server and SQL Server Management Studio.
My specifc issue I believe was related to having to many mixed systems installed on my laptop. I had Visual Studio 2005 and 2008 componets and SQL Server Managment Standard loaded with SQL Server Express Edition as well as various other componets that might have effected the stability of my envirnomnet. Once I reloaded Vista and went back through the steps on <http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer> it worked without issue. I only loaded the Express Editions of SQL Server and SQL Server Management Studio
155,188
<p>I have one text input and one button (see below). How can I use JavaScript to <strong>trigger the button's click event</strong> when the <kbd>Enter</kbd> key is pressed inside the text box?</p> <p>There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I <em>only</em> want the <kbd>Enter</kbd> key to click this specific button if it is pressed from within this one text box, nothing else.</p> <pre><code>&lt;input type="text" id="txtSearch" /&gt; &lt;input type="button" id="btnSearch" value="Search" onclick="doSomething();" /&gt; </code></pre>
[ { "answer_id": 155193, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 6, "selected": false, "text": "<p>Make the button a submit element, so it'll be automatic.</p>\n\n<pre><code>&lt;input type = \"submit\"\n id = \"btnSearch\"\n value = \"Search\"\n onclick = \"return doSomething();\"\n/&gt;\n</code></pre>\n\n<p>Note that you'll need a <code>&lt;form&gt;</code> element containing the input fields to make this work (thanks Sergey Ilinsky).</p>\n\n<p>It's not a good practice to redefine standard behaviour, the <kbd>Enter</kbd> key should always call the submit button on a form.</p>\n" }, { "answer_id": 155263, "author": "Steve Paulo", "author_id": 9414, "author_profile": "https://Stackoverflow.com/users/9414", "pm_score": 12, "selected": true, "text": "<p>In jQuery, the following would work:</p>\n\n<pre><code>$(\"#id_of_textbox\").keyup(function(event) {\n if (event.keyCode === 13) {\n $(\"#id_of_button\").click();\n }\n});\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"#pw\").keyup(function(event) {\r\n if (event.keyCode === 13) {\r\n $(\"#myButton\").click();\r\n }\r\n});\r\n\r\n$(\"#myButton\").click(function() {\r\n alert(\"Button code executed.\");\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\nUsername:&lt;input id=\"username\" type=\"text\"&gt;&lt;br&gt;\r\nPassword:&amp;nbsp;&lt;input id=\"pw\" type=\"password\"&gt;&lt;br&gt;\r\n&lt;button id=\"myButton\"&gt;Submit&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or in plain JavaScript, the following would work:</p>\n\n<pre><code>document.getElementById(\"id_of_textbox\")\n .addEventListener(\"keyup\", function(event) {\n event.preventDefault();\n if (event.keyCode === 13) {\n document.getElementById(\"id_of_button\").click();\n }\n});\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.getElementById(\"pw\")\r\n .addEventListener(\"keyup\", function(event) {\r\n event.preventDefault();\r\n if (event.keyCode === 13) {\r\n document.getElementById(\"myButton\").click();\r\n }\r\n});\r\n\r\nfunction buttonCode()\r\n{\r\n alert(\"Button code executed.\");\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\nUsername:&lt;input id=\"username\" type=\"text\"&gt;&lt;br&gt;\r\nPassword:&amp;nbsp;&lt;input id=\"pw\" type=\"password\"&gt;&lt;br&gt;\r\n&lt;button id=\"myButton\" onclick=\"buttonCode()\"&gt;Submit&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 155265, "author": "kdenney", "author_id": 23947, "author_profile": "https://Stackoverflow.com/users/23947", "pm_score": 8, "selected": false, "text": "<p>Figured this out:</p>\n\n<pre><code>&lt;input type=\"text\" id=\"txtSearch\" onkeypress=\"return searchKeyPress(event);\" /&gt;\n&lt;input type=\"button\" id=\"btnSearch\" Value=\"Search\" onclick=\"doSomething();\" /&gt;\n\n&lt;script&gt;\nfunction searchKeyPress(e)\n{\n // look for window.event in case event isn't passed in\n e = e || window.event;\n if (e.keyCode == 13)\n {\n document.getElementById('btnSearch').click();\n return false;\n }\n return true;\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 155272, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 9, "selected": false, "text": "<p>Then just code it in!</p>\n\n<pre><code>&lt;input type = \"text\"\n id = \"txtSearch\" \n onkeydown = \"if (event.keyCode == 13)\n document.getElementById('btnSearch').click()\" \n/&gt;\n\n&lt;input type = \"button\"\n id = \"btnSearch\"\n value = \"Search\"\n onclick = \"doSomething();\"\n/&gt;\n</code></pre>\n" }, { "answer_id": 155274, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 4, "selected": false, "text": "<pre><code>onkeydown=\"javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};\"\n</code></pre>\n\n<p>This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.</p>\n" }, { "answer_id": 156905, "author": "garrow", "author_id": 21095, "author_profile": "https://Stackoverflow.com/users/21095", "pm_score": 4, "selected": false, "text": "<p>Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.</p>\n\n<p>You can then capture the form onsubmit with js and do whatever validation or callbacks you want.</p>\n" }, { "answer_id": 2691390, "author": "ELEK", "author_id": 323305, "author_profile": "https://Stackoverflow.com/users/323305", "pm_score": 3, "selected": false, "text": "<pre><code>event.returnValue = false\n</code></pre>\n\n<p>Use it when handling the event or in the function your event handler calls.</p>\n\n<p>It works in Internet Explorer and Opera at least.</p>\n" }, { "answer_id": 2795390, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>This <strong><a href=\"https://developer.mozilla.org/en/DOM/element.onchange\" rel=\"noreferrer\">onchange</a></strong> attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.</p>\n\n<pre><code>&lt;input type=\"text\" id=\"txtSearch\" onchange=\"doSomething();\" /&gt;\n&lt;input type=\"button\" id=\"btnSearch\" value=\"Search\" onclick=\"doSomething();\" /&gt;\n</code></pre>\n" }, { "answer_id": 4929676, "author": "Varun", "author_id": 519755, "author_profile": "https://Stackoverflow.com/users/519755", "pm_score": 6, "selected": false, "text": "<p>In plain JavaScript,</p>\n\n<pre><code>if (document.layers) {\n document.captureEvents(Event.KEYDOWN);\n}\n\ndocument.onkeydown = function (evt) {\n var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;\n if (keyCode == 13) {\n // For Enter.\n // Your function here.\n }\n if (keyCode == 27) {\n // For Escape.\n // Your function here.\n } else {\n return true;\n }\n};\n</code></pre>\n\n<p>I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.</p>\n" }, { "answer_id": 7400586, "author": "Niraj Chauhan", "author_id": 608388, "author_profile": "https://Stackoverflow.com/users/608388", "pm_score": -1, "selected": false, "text": "<p>This also might help, a small JavaScript function, which works fine:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction blank(a) { if(a.value == a.defaultValue) a.value = \"\"; }\n\nfunction unblank(a) { if(a.value == \"\") a.value = a.defaultValue; }\n&lt;/script&gt; \n&lt;input type=\"text\" value=\"email goes here\" onfocus=\"blank(this)\" onblur=\"unblank(this)\" /&gt;\n</code></pre>\n\n<p>I know this question is solved, but I just found something, which can be helpful for others.</p>\n" }, { "answer_id": 7911458, "author": "me_an", "author_id": 1013810, "author_profile": "https://Stackoverflow.com/users/1013810", "pm_score": 4, "selected": false, "text": "<p>To trigger a search every time the enter key is pressed, use this:</p>\n\n<pre><code>$(document).keypress(function(event) {\n var keycode = (event.keyCode ? event.keyCode : event.which);\n if (keycode == '13') {\n $('#btnSearch').click();\n }\n}\n</code></pre>\n" }, { "answer_id": 10626419, "author": "user1071182", "author_id": 1071182, "author_profile": "https://Stackoverflow.com/users/1071182", "pm_score": 3, "selected": false, "text": "<p>For jQuery mobile, I had to do:</p>\n<pre><code>$('#id_of_textbox').live(&quot;keyup&quot;, function(event) {\n if(event.keyCode == '13'){\n $('#id_of_button').click();\n }\n});\n</code></pre>\n" }, { "answer_id": 18513090, "author": "frhd", "author_id": 2491198, "author_profile": "https://Stackoverflow.com/users/2491198", "pm_score": 4, "selected": false, "text": "<p>This is a solution for all the <strong><a href=\"http://yuilibrary.com/\">YUI</a></strong> lovers out there:</p>\n\n<pre><code>Y.on('keydown', function() {\n if(event.keyCode == 13){\n Y.one(\"#id_of_button\").simulate(\"click\");\n }\n}, '#id_of_textbox');\n</code></pre>\n\n<p>In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...</p>\n" }, { "answer_id": 18772817, "author": "Switters", "author_id": 1860358, "author_profile": "https://Stackoverflow.com/users/1860358", "pm_score": 5, "selected": false, "text": "<p>One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:</p>\n\n<pre><code>&lt;form onsubmit=\"Search();\" action=\"javascript:void(0);\"&gt;\n &lt;input type=\"text\" id=\"searchCriteria\" placeholder=\"Search Criteria\"/&gt;\n &lt;input type=\"button\" onclick=\"Search();\" value=\"Search\" id=\"searchBtn\"/&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Setting action=\"javascript:void(0);\" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.</p>\n" }, { "answer_id": 20064004, "author": "icedwater", "author_id": 1091386, "author_profile": "https://Stackoverflow.com/users/1091386", "pm_score": 6, "selected": false, "text": "<p>Since no one has used <code>addEventListener</code> yet, here is my version. Given the elements:</p>\n<pre><code>&lt;input type = &quot;text&quot; id = &quot;txt&quot; /&gt;\n&lt;input type = &quot;button&quot; id = &quot;go&quot; /&gt;\n</code></pre>\n<p>I would use the following:</p>\n<pre><code>var go = document.getElementById(&quot;go&quot;);\nvar txt = document.getElementById(&quot;txt&quot;);\n\ntxt.addEventListener(&quot;keypress&quot;, function(event) {\n event.preventDefault();\n if (event.keyCode == 13)\n go.click();\n});\n</code></pre>\n<p>This allows you to change the event type and action separately while keeping the HTML clean.</p>\n<blockquote>\n<p><strong>Note</strong> that it's probably worthwhile to make sure this is outside of a <code>&lt;form&gt;</code> because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.</p>\n<blockquote>\n<p><strong>Addendum</strong>: Thanks to a comment by @ruffin, I've added the missing event handler and a <code>preventDefault</code> to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)</p>\n</blockquote>\n</blockquote>\n" }, { "answer_id": 23738023, "author": "Eric Engel", "author_id": 1874272, "author_profile": "https://Stackoverflow.com/users/1874272", "pm_score": 3, "selected": false, "text": "<pre><code>document.onkeypress = function (e) {\n e = e || window.event;\n var charCode = (typeof e.which == \"number\") ? e.which : e.keyCode;\n if (charCode == 13) {\n\n // Do something here\n printResult();\n }\n};\n</code></pre>\n\n<p>Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.</p>\n" }, { "answer_id": 28805055, "author": "mahbub_siddique", "author_id": 2081867, "author_profile": "https://Stackoverflow.com/users/2081867", "pm_score": 4, "selected": false, "text": "<p><strong>Try it:</strong></p>\n\n<pre><code>&lt;input type=\"text\" id=\"txtSearch\"/&gt;\n&lt;input type=\"button\" id=\"btnSearch\" Value=\"Search\"/&gt;\n\n&lt;script&gt; \n window.onload = function() {\n document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {\n if (event.keyCode == 13) {\n document.getElementById('btnSearch').click();\n }\n };\n\n document.getElementById('btnSearch').onclick =doSomething;\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 29409637, "author": "Stephen Ngethe", "author_id": 2398620, "author_profile": "https://Stackoverflow.com/users/2398620", "pm_score": 3, "selected": false, "text": "<p>This in-case you want also diable the enter button from Posting to server and execute the Js script. </p>\n\n<pre><code>&lt;input type=\"text\" id=\"txtSearch\" onkeydown=\"if (event.keyCode == 13)\n {document.getElementById('btnSearch').click(); return false;}\"/&gt;\n&lt;input type=\"button\" id=\"btnSearch\" value=\"Search\" onclick=\"doSomething();\" /&gt;\n</code></pre>\n" }, { "answer_id": 30809553, "author": "clickbait", "author_id": 4356188, "author_profile": "https://Stackoverflow.com/users/4356188", "pm_score": 2, "selected": false, "text": "<p>To do it with jQuery:</p>\n\n<pre><code>$(\"#txtSearch\").on(\"keyup\", function (event) {\n if (event.keyCode==13) {\n $(\"#btnSearch\").get(0).click();\n }\n});\n</code></pre>\n\n<p>To do it with normal JavaScript:</p>\n\n<pre><code>document.getElementById(\"txtSearch\").addEventListener(\"keyup\", function (event) {\n if (event.keyCode==13) { \n document.getElementById(\"#btnSearch\").click();\n }\n});\n</code></pre>\n" }, { "answer_id": 32155821, "author": "AlikElzin-kilaka", "author_id": 435605, "author_profile": "https://Stackoverflow.com/users/435605", "pm_score": 4, "selected": false, "text": "<p>In <strong>Angular2</strong>:</p>\n\n<pre><code>(keyup.enter)=\"doSomething()\"\n</code></pre>\n\n<p>If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.</p>\n\n<p>Also, the id isn't needed - another NG2 way of separating between the view and the model.</p>\n" }, { "answer_id": 34441952, "author": "ruffin", "author_id": 1028230, "author_profile": "https://Stackoverflow.com/users/1028230", "pm_score": 3, "selected": false, "text": "<p>To add a completely plain JavaScript solution that addressed <a href=\"https://stackoverflow.com/revisions/20064004/2\">@icedwater's issue with form submission</a>, here's a complete solution <em>with <code>form</code></em>.</p>\n<blockquote>\n<p><strong>NOTE:</strong> This is for &quot;modern browsers&quot;, including IE9+. The IE8 version isn't much more complicated, and can be <a href=\"https://stackoverflow.com/a/21814964/1028230\">learned here</a>.</p>\n</blockquote>\n<hr>\n<p>Fiddle: <a href=\"https://jsfiddle.net/rufwork/gm6h25th/1/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/rufwork/gm6h25th/1/</a></p>\n<h3>HTML</h3>\n<pre><code>&lt;body&gt;\n &lt;form&gt;\n &lt;input type=&quot;text&quot; id=&quot;txt&quot; /&gt;\n &lt;input type=&quot;button&quot; id=&quot;go&quot; value=&quot;Click Me!&quot; /&gt;\n &lt;div id=&quot;outige&quot;&gt;&lt;/div&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n</code></pre>\n<h3>JavaScript</h3>\n<pre><code>// The document.addEventListener replicates $(document).ready() for\n// modern browsers (including IE9+), and is slightly more robust than `onload`.\n// More here: https://stackoverflow.com/a/21814964/1028230\ndocument.addEventListener(&quot;DOMContentLoaded&quot;, function() {\n var go = document.getElementById(&quot;go&quot;),\n txt = document.getElementById(&quot;txt&quot;),\n outige = document.getElementById(&quot;outige&quot;);\n\n // Note that jQuery handles &quot;empty&quot; selections &quot;for free&quot;.\n // Since we're plain JavaScripting it, we need to make sure this DOM exists first.\n if (txt &amp;&amp; go) {\n txt.addEventListener(&quot;keypress&quot;, function (e) {\n if (event.keyCode === 13) {\n go.click();\n e.preventDefault(); // &lt;&lt;&lt; Most important missing piece from icedwater\n }\n });\n\n go.addEventListener(&quot;click&quot;, function () {\n if (outige) {\n outige.innerHTML += &quot;Clicked!&lt;br /&gt;&quot;;\n }\n });\n }\n});\n</code></pre>\n" }, { "answer_id": 38252483, "author": "NVRM", "author_id": 2494754, "author_profile": "https://Stackoverflow.com/users/2494754", "pm_score": 3, "selected": false, "text": "<p>Nobody noticed the html attibute \"accesskey\" which is available since a while.</p>\n\n<p>This is a no javascript way to keyboard shortcuts stuffs.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Yb7GA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yb7GA.png\" alt=\"accesskey_browsers\"></a></p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/accesskey\" rel=\"nofollow noreferrer\">The accesskey attributes shortcuts on MDN</a></p>\n\n<p>Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny <a href=\"https://github.com/ded/bowser\" rel=\"nofollow noreferrer\">bowser</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let client = navigator.userAgent.toLowerCase(),\r\n isLinux = client.indexOf(\"linux\") &gt; -1,\r\n isWin = client.indexOf(\"windows\") &gt; -1,\r\n isMac = client.indexOf(\"apple\") &gt; -1,\r\n isFirefox = client.indexOf(\"firefox\") &gt; -1,\r\n isWebkit = client.indexOf(\"webkit\") &gt; -1,\r\n isOpera = client.indexOf(\"opera\") &gt; -1,\r\n input = document.getElementById('guestInput');\r\n\r\nif(isFirefox) {\r\n input.setAttribute(\"placeholder\", \"ALT+SHIFT+Z\");\r\n} else if (isWin) {\r\n input.setAttribute(\"placeholder\", \"ALT+Z\");\r\n} else if (isMac) {\r\n input.setAttribute(\"placeholder\", \"CTRL+ALT+Z\");\r\n} else if (isOpera) {\r\n input.setAttribute(\"placeholder\", \"SHIFT+ESCAPE-&gt;Z\");\r\n} else {'Point me to operate...'}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"text\" id=\"guestInput\" accesskey=\"z\" placeholder=\"Acces shortcut:\"&gt;&lt;/input&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 48488107, "author": "Alexandr Tsyganok", "author_id": 4645226, "author_profile": "https://Stackoverflow.com/users/4645226", "pm_score": 3, "selected": false, "text": "<p>For those who may like brevity and modern js approach.</p>\n\n<pre><code>input.addEventListener('keydown', (e) =&gt; {if (e.keyCode == 13) doSomething()});\n</code></pre>\n\n<p>where <strong>input</strong> is a variable containing your input element.</p>\n" }, { "answer_id": 48855408, "author": "Gibolt", "author_id": 974045, "author_profile": "https://Stackoverflow.com/users/974045", "pm_score": 5, "selected": false, "text": "<h1>Use <code>keypress</code> and <code>event.key === &quot;Enter&quot;</code> with modern JS!</h1>\n<pre><code>const textbox = document.getElementById(&quot;txtSearch&quot;);\ntextbox.addEventListener(&quot;keypress&quot;, function onEvent(event) {\n if (event.key === &quot;Enter&quot;) {\n document.getElementById(&quot;btnSearch&quot;).click();\n }\n});\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\" rel=\"noreferrer\">Mozilla Docs</a></p>\n<p><a href=\"http://caniuse.com/#feat=keyboardevent-key\" rel=\"noreferrer\">Supported Browsers</a></p>\n" }, { "answer_id": 51254652, "author": "Unmitigated", "author_id": 9513184, "author_profile": "https://Stackoverflow.com/users/9513184", "pm_score": 2, "selected": false, "text": "<p>In jQuery, you can use <code>event.which==13</code>. If you have a <code>form</code>, you could use <code>$('#formid').submit()</code> (with the correct event listeners added to the submission of said form).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('#textfield').keyup(function(event){\r\n if(event.which==13){\r\n $('#submit').click();\r\n }\r\n});\r\n$('#submit').click(function(e){\r\n if($('#textfield').val().trim().length){\r\n alert(\"Submitted!\");\r\n } else {\r\n alert(\"Field can not be empty!\");\r\n }\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;label for=\"textfield\"&gt;\r\nEnter Text:&lt;/label&gt;\r\n&lt;input id=\"textfield\" type=\"text\"&gt;\r\n&lt;button id=\"submit\"&gt;\r\nSubmit\r\n&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 54422802, "author": "MCCCS", "author_id": 6557621, "author_profile": "https://Stackoverflow.com/users/6557621", "pm_score": 4, "selected": false, "text": "<p>In modern, undeprecated (without <code>keyCode</code> or <code>onkeydown</code>) Javascript:</p>\n\n<pre><code>&lt;input onkeypress=\"if(event.key == 'Enter') {console.log('Test')}\"&gt;\n</code></pre>\n" }, { "answer_id": 59156750, "author": "Ravi Makwana", "author_id": 6631280, "author_profile": "https://Stackoverflow.com/users/6631280", "pm_score": -1, "selected": false, "text": "<p>I have developed custom javascript to achieve this feature by just adding class</p>\n<p>Example: <code>&lt;button type=&quot;button&quot; class=&quot;ctrl-p&quot;&gt;Custom Print&lt;/button&gt;</code></p>\n<p>Here Check it out <a href=\"https://jsfiddle.net/RaviMakwana/k6zL1q9t/\" rel=\"nofollow noreferrer\">Fiddle</a> <br/></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// find elements\nvar banner = $(\"#banner-message\")\nvar button = $(\"button\")\n\n// handle click and add class\nbutton.on(\"click\", function(){\n if(banner.hasClass(\"alt\"))\n banner.removeClass(\"alt\")\n else\n banner.addClass(\"alt\")\n})\n\n$(document).ready(function(){\n $(document).on('keydown', function (e) {\n \n if (e.ctrlKey) {\n $('[class*=\"ctrl-\"]:not([data-ctrl])').each(function (idx, item) {\n var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();\n $(item).attr(\"data-ctrl\", Key);\n $(item).append('&lt;div class=\"tooltip fade top in tooltip-ctrl alter-info\" role=\"tooltip\" style=\"margin-top: -61px; display: block; visibility: visible;\"&gt;&lt;div class=\"tooltip-arrow\" style=\"left: 49.5935%;\"&gt;&lt;/div&gt;&lt;div class=\"tooltip-inner\"&gt; CTRL + ' + Key + '&lt;/div&gt;&lt;/div&gt;')\n });\n }\n \n if (e.ctrlKey &amp;&amp; e.which != 17) {\n var Key = String.fromCharCode(e.which).toLowerCase();\n if( $('.ctrl-'+Key).length == 1) {\n e.preventDefault();\n if (!$('#divLoader').is(\":visible\"))\n $('.ctrl-'+Key).click();\n console.log(\"You pressed ctrl + \"+Key );\n }\n }\n });\n $(document).on('keyup', function (e) {\n if(!e.ctrlKey ){\n $('[class*=\"ctrl-\"]').removeAttr(\"data-ctrl\");\n $(\".tooltip-ctrl\").remove();\n }\n })\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#banner-message {\n background: #fff;\n border-radius: 4px;\n padding: 20px;\n font-size: 25px;\n text-align: center;\n transition: all 0.2s;\n margin: 0 auto;\n width: 300px;\n}\n\n#banner-message.alt {\n background: #0084ff;\n color: #fff;\n margin-top: 40px;\n width: 200px;\n}\n\n#banner-message.alt button {\n background: #fff;\n color: #000;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;div id=\"banner-message\"&gt;\n &lt;p&gt;Hello World&lt;/p&gt;\n &lt;button class=\"ctrl-s\" title=\"s\"&gt;Change color&lt;/button&gt;&lt;br/&gt;&lt;br/&gt;\n &lt;span&gt;Press CTRL+S to trigger click event of button&lt;/span&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>-- or -- <br/>\ncheck out running example\n<a href=\"https://stackoverflow.com/a/58010042/6631280\">https://stackoverflow.com/a/58010042/6631280</a></p>\n<blockquote>\n<p>Note: on current logic, you need to press <kbd>Ctrl</kbd> +\n<kbd>Enter</kbd></p>\n</blockquote>\n" }, { "answer_id": 62578092, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 4, "selected": false, "text": "<h1>Short working pure JS</h1>\n<pre><code>txtSearch.onkeydown= e =&gt; (e.key==&quot;Enter&quot;) ? btnSearch.click() : 1\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>txtSearch.onkeydown= e =&gt; (e.key==\"Enter\") ? btnSearch.click() : 1\n\nfunction doSomething() {\n console.log('');\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"text\" id=\"txtSearch\" /&gt;\n&lt;input type=\"button\" id=\"btnSearch\" value=\"Search\" onclick=\"doSomething();\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63446199, "author": "Daniel De León", "author_id": 980442, "author_profile": "https://Stackoverflow.com/users/980442", "pm_score": 2, "selected": false, "text": "<p>These day the <code>change</code> event is the way!</p>\n<pre><code>document.getElementById(&quot;txtSearch&quot;).addEventListener('change',\n () =&gt; document.getElementById(&quot;btnSearch&quot;).click()\n);\n</code></pre>\n" }, { "answer_id": 72821294, "author": "RustyH", "author_id": 1272209, "author_profile": "https://Stackoverflow.com/users/1272209", "pm_score": 0, "selected": false, "text": "<p>My reusable Vanilla JS solution. so you can change which button gets hit depending on what element/textbox is active.</p>\n<pre><code> &lt;input type=&quot;text&quot; id=&quot;message&quot; onkeypress=&quot;enterKeyHandler(event,'sendmessage')&quot; /&gt;\n &lt;input type=&quot;button&quot; id=&quot;sendmessage&quot; value=&quot;Send&quot;/&gt;\n</code></pre>\n<hr />\n<pre><code>function enterKeyHandler(e,button) {\n e = e || window.event;\n if (e.key == 'Enter') {\n document.getElementById(button).click();\n }\n}\n</code></pre>\n" }, { "answer_id": 73601824, "author": "rsmdh", "author_id": 10995048, "author_profile": "https://Stackoverflow.com/users/10995048", "pm_score": 0, "selected": false, "text": "<p>You can try below code in jQuery.</p>\n<pre><code>$(&quot;#txtSearch&quot;).keyup(function(e) {\n e.preventDefault();\n var keycode = (e.keyCode ? e.keyCode : e.which);\n if (keycode === 13 || e.key === 'Enter') \n {\n $(&quot;#btnSearch&quot;).click();\n }\n});\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23947/" ]
I have one text input and one button (see below). How can I use JavaScript to **trigger the button's click event** when the `Enter` key is pressed inside the text box? There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I *only* want the `Enter` key to click this specific button if it is pressed from within this one text box, nothing else. ``` <input type="text" id="txtSearch" /> <input type="button" id="btnSearch" value="Search" onclick="doSomething();" /> ```
In jQuery, the following would work: ``` $("#id_of_textbox").keyup(function(event) { if (event.keyCode === 13) { $("#id_of_button").click(); } }); ``` ```js $("#pw").keyup(function(event) { if (event.keyCode === 13) { $("#myButton").click(); } }); $("#myButton").click(function() { alert("Button code executed."); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password:&nbsp;<input id="pw" type="password"><br> <button id="myButton">Submit</button> ``` Or in plain JavaScript, the following would work: ``` document.getElementById("id_of_textbox") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("id_of_button").click(); } }); ``` ```js document.getElementById("pw") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("myButton").click(); } }); function buttonCode() { alert("Button code executed."); } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password:&nbsp;<input id="pw" type="password"><br> <button id="myButton" onclick="buttonCode()">Submit</button> ```
155,191
<p>I have written something that uses the following includes:</p> <pre><code>#include &lt;math.h&gt; #include &lt;time.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;windows.h&gt; #include &lt;commctrl.h&gt; </code></pre> <p>This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of windows (VMs of course). It dies with the quite familiar:</p> <pre><code>--------------------------- C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe --------------------------- C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. --------------------------- OK --------------------------- </code></pre> <p>How can I make it run on clean installs? Which dll is it using which it can't find? My bet is on commctrl, but can someone enlighten me on why it's isn't with every windows?</p> <p>Further more, if anyone has tips on how to debug such a thing, as my CPP is already rusty, as it seems :)</p> <p>Edit - What worked for me is downloading the Redistributable for Visual Studio 2008. I don't think it's a good solution - downloading a 2MB file and an install to run a simple 11K tool. I think I'll change the code to use LoadLibrary to get the 2 or 3 functions I need from comctl32.dll. Thanks everyone :)</p>
[ { "answer_id": 155200, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "<p>I suspect it is trying to find a version of common controls that isn't installed. You may need a manifest file to map the version of common controls to your target operating system. Also, you may need to make sure you have installed the same VC runtimes that you were linked to.</p>\n\n<p><a href=\"http://blogs.msdn.com/cjacks/archive/2006/08/21/711240.aspx\" rel=\"nofollow noreferrer\">Chris Jackson blog</a></p>\n\n<p>EDIT: A little searching and I've confirmed (mostly) that it is the version of your VC++ runtimes that is to blame. You need to distribute the versions that you built with. The platform SDK usually includes a merge module of these for that purpose, but there is often a VCRedist.exe for them as well. Try looking Microsoft's downloads.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/948854\" rel=\"nofollow noreferrer\">KB94885</a></p>\n" }, { "answer_id": 155213, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 4, "selected": true, "text": "<p>Use Dependency Walker. Download and install from <a href=\"http://www.dependencywalker.com/\" rel=\"noreferrer\">http://www.dependencywalker.com/</a> (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable.</p>\n\n<p>If you use VS2005, most cases will be covered by <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&amp;displaylang=en\" rel=\"noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&amp;displaylang=en</a> which includes everything needed to run EXEs created with VS2005. Using depends.exe you may find a more lightweight solution, though.</p>\n" }, { "answer_id": 155431, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p><strong>Common controls is a red herring</strong>. Your problem is that the Visual C++ 8.0 runtime - I assume you're using Visual Studio 2005 - isn't installed. Either statically link to the C/C++ runtime library, or distribute the runtime DLL.</p>\n\n<p>You will have this problem with any C or C++ program that uses the DLL. You could get away with it in VS 6.0 as <code>msvcrt.dll</code> came with the OS from Windows 2000 up, and in VS.NET 2003 as <code>msvcr71.dll</code> came with .NET Framework 1.1. No more. Visual Studio 2005 and later use side-by-side assemblies to prevent DLL Hell, but that means you can't rely even on .NET 2.0 installing the exact version of C runtime that your program's built-in manifest uses. .NET 2.0's <code>mscorwks.dll</code> binds to version 8.0.50608.0 in its manifest; a VS-generated application binds to 8.0.50727.762 as of VS2005 SP1. My recollection is it used some pre-release version in the original (RTM) release of VS2005, which meant you had to deploy a Publisher Policy merge module if you were using the merge modules, to redirect the binding to the version actually in the released C run-time merge module.</p>\n\n<p>See also <a href=\"http://msdn.microsoft.com/en-us/library/ms235299(VS.80).aspx\" rel=\"nofollow noreferrer\">Redistributing Visual C++ Files</a> on MSDN.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23942/" ]
I have written something that uses the following includes: ``` #include <math.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <commctrl.h> ``` This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of windows (VMs of course). It dies with the quite familiar: ``` --------------------------- C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe --------------------------- C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. --------------------------- OK --------------------------- ``` How can I make it run on clean installs? Which dll is it using which it can't find? My bet is on commctrl, but can someone enlighten me on why it's isn't with every windows? Further more, if anyone has tips on how to debug such a thing, as my CPP is already rusty, as it seems :) Edit - What worked for me is downloading the Redistributable for Visual Studio 2008. I don't think it's a good solution - downloading a 2MB file and an install to run a simple 11K tool. I think I'll change the code to use LoadLibrary to get the 2 or 3 functions I need from comctl32.dll. Thanks everyone :)
Use Dependency Walker. Download and install from <http://www.dependencywalker.com/> (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable. If you use VS2005, most cases will be covered by <http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en> which includes everything needed to run EXEs created with VS2005. Using depends.exe you may find a more lightweight solution, though.
155,203
<p>What is a good error handling practice for an asp.net site? Examples? Thanks!</p>
[ { "answer_id": 155223, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 2, "selected": false, "text": "<p>One practice that I find to be especially useful is to create a generic error page, and then set your defaultRedirect on the customErrors node of the web.config to that error page. </p>\n\n<p>Then setup your global.asax for logging all unhandled exceptions and then put them (the unhandled exceptions) in a static property on some class (I have a class called ErrorUtil with a static LastError property). Your error page can then look at this property to determine what to display to the user.</p>\n\n<p>More details here: <a href=\"http://www.codeproject.com/KB/aspnet/JcGlobalErrorHandling.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/JcGlobalErrorHandling.aspx</a></p>\n" }, { "answer_id": 155238, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 4, "selected": true, "text": "<p>As with any .net project I find the best way is to only catch specific error types if they are may to happen on the given page. </p>\n\n<p>For example you could catch Format Exceptions for a users given input (just incase JavaScript validation fails and you have not use tryparse) but always leave the catching of the top level Exception to the global error handler.</p>\n\n<pre><code> try\n {\n //Code that could error here\n }\n catch (FormatException ex)\n {\n //Code to tell user of their error\n //all other errors will be handled \n //by the global error handler\n }\n</code></pre>\n\n<p>You can use the open source <a href=\"http://code.google.com/p/elmah/\" rel=\"nofollow noreferrer\">elmah</a> (Error Logging Modules and Handlers) for ASP.Net to do this top level/global error catching for you if you want. </p>\n\n<p>Using <a href=\"http://code.google.com/p/elmah/\" rel=\"nofollow noreferrer\">elmah</a> it can create a log of errors that is viewable though a simple to configure web interface. You can also filter different types of errors and have custom error pages of your own for different error types. </p>\n" }, { "answer_id": 155242, "author": "MrBoJangles", "author_id": 13578, "author_profile": "https://Stackoverflow.com/users/13578", "pm_score": 0, "selected": false, "text": "<p>Well, that's pretty wide open, which is completely cool. I'll refer you to a word .doc you can download from <a href=\"http://www.dotnetspider.com/tutorials/BestPractices.aspx\" rel=\"nofollow noreferrer\">Dot Net Spider</a>, which is actually the basis for my small company's code standard. The standard includes some very useful error handling tips.</p>\n\n<p>One such example for exceptions (I don't recall if this is original to the document or if we added it to the doc):\nNever do a “catch exception and do nothing.” If you hide an exception, you will never know if the exception happened. You should always try to avoid exceptions by checking all the error conditions programmatically.</p>\n\n<p>Example of what not to do:</p>\n\n<pre><code>try\n{\n ...\n}\ncatch{}\n</code></pre>\n\n<p>Very naughty unless you have a good reason for it.</p>\n" }, { "answer_id": 155266, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 0, "selected": false, "text": "<p>You should make sure that you can catch most of the errors that are generated by your application and display a friendly message to the users. But of course you cannot catch all the errors for that you can use web.config and defaultRedirect by another user. Another very handy tool to log the errors is ELMAH. ELMAH will log all the errors generated by your application and show it to you in a very readable way. Plugging ELMAH in your application is as simple as adding few lines of code in web.config file and attaching the assembly. You should definitely give ELMAH a try it will literally save you hours and hours of pain. </p>\n\n<p><a href=\"http://code.google.com/p/elmah/\" rel=\"nofollow noreferrer\">http://code.google.com/p/elmah/</a></p>\n" }, { "answer_id": 155289, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>Code defensively within each page for exceptions that you expect could happen and deal with them appropriately, so not to disrupt the user every time an exception occurs.</p></li>\n<li><p>Log all exceptions, with a reference.</p></li>\n<li><p>Provide a generic error page, for any unhandled exceptions, which provides a reference to use for support (support can identify details from logs). Don't display the actual exception, as most users will not understand it but is a potential security risk as it exposes information about your system (potentially passwords etc).</p></li>\n<li><p>Don't catch all exceptions and do nothing with them (as in the above answer). There is almost never a good reason to do this, occasionally you may want to catch a specific exception and not do any deliberately but this should be used wisely. </p></li>\n</ol>\n" }, { "answer_id": 155750, "author": "Chris Westbrook", "author_id": 16891, "author_profile": "https://Stackoverflow.com/users/16891", "pm_score": 0, "selected": false, "text": "<p>It is not always a good idea to redirect the user to a standard error page. If a user is working on a form, they may not want to be redirected away from the form they are working on. I put all code that could cause an exception inside a try/catch block, and inside the catch block I spit out an alert message alerting the user that an error has occurred as well as log the exception in a database including form input, query string, etc. I am developing an internal site, however, so most users just call me if they are having a problem. For a public site, you may wish to use something like elmah.</p>\n" }, { "answer_id": 1747662, "author": "234234", "author_id": 212739, "author_profile": "https://Stackoverflow.com/users/212739", "pm_score": 0, "selected": false, "text": "<pre><code>public string BookLesson(Customer_Info oCustomerInfo, CustLessonBook_Info oCustLessonBookInfo)\n {\n string authenticationID = string.Empty;\n int customerID = 0;\n string message = string.Empty;\n DA_Customer oDACustomer = new DA_Customer();\n\n using (TransactionScope scope = new TransactionScope())\n {\n if (oDACustomer.ValidateCustomerLoginName(oCustomerInfo.CustId, oCustomerInfo.CustLoginName) == \"Y\")\n {\n // if a new student\n if (oCustomerInfo.CustId == 0)\n {\n oCustomerInfo.CustPassword = General.GeneratePassword(6, 8);\n oCustomerInfo.CustPassword = new DA_InternalUser().GetPassword(oCustomerInfo.CustPassword, false);\n authenticationID = oDACustomer.Register(oCustomerInfo, ref customerID);\n oCustLessonBookInfo.CustId = customerID;\n }\n else // if existing student\n {\n oCustomerInfo.UpdatedByCustomer = \"Y\";\n authenticationID = oDACustomer.CustomerUpdateProfile(oCustomerInfo);\n }\n message = authenticationID;\n // insert lesson booking details\n new DA_Lesson().BookLesson(oCustLessonBookInfo);\n }\n\n else\n {\n message = \"login exists\";\n }\n scope.Complete();\n return message;\n }\n\n }\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is a good error handling practice for an asp.net site? Examples? Thanks!
As with any .net project I find the best way is to only catch specific error types if they are may to happen on the given page. For example you could catch Format Exceptions for a users given input (just incase JavaScript validation fails and you have not use tryparse) but always leave the catching of the top level Exception to the global error handler. ``` try { //Code that could error here } catch (FormatException ex) { //Code to tell user of their error //all other errors will be handled //by the global error handler } ``` You can use the open source [elmah](http://code.google.com/p/elmah/) (Error Logging Modules and Handlers) for ASP.Net to do this top level/global error catching for you if you want. Using [elmah](http://code.google.com/p/elmah/) it can create a log of errors that is viewable though a simple to configure web interface. You can also filter different types of errors and have custom error pages of your own for different error types.
155,209
<p>I'm trying to get my multithreading understanding locked down. I'm doing my best to teach myself, but some of these issues need clarification. </p> <p>I've gone through three iterations with a piece of code, experimenting with locking.</p> <p>In this code, the only thing that needs locking is this.managerThreadPriority.</p> <p>First, the simple, procedural approach, with minimalistic locking.</p> <pre><code>var managerThread = new Thread ( new ThreadStart(this.ManagerThreadEntryPoint) ); lock (this.locker) { managerThread.Priority = this.managerThreadPriority; } managerThread.Name = string.Format("Manager Thread ({0})", managerThread.GetHashCode()); managerThread.Start(); </code></pre> <p>Next, a single statement to create and launch a new thread, but the lock appears to be scoped too large, to include the creation and launching of the thread. The compiler doesn't somehow magically know that the lock can be released after this.managerThreadPriority is used.</p> <p>This kind of naive locking should be avoided, I would assume.</p> <pre><code>lock (this.locker) { new Thread ( new ThreadStart(this.ManagerThreadEntryPoint) ) { Priority = this.managerThreadPriority, Name = string.Format("Manager Thread ({0})", GetHashCode()) } .Start(); } </code></pre> <p>Last, a single statement to create and launch a new thread, with a "embedded" lock only around the shared field.</p> <pre><code>new Thread ( new ThreadStart(this.ManagerThreadEntryPoint) ) { Priority = new Func&lt;ThreadPriorty&gt;(() =&gt; { lock (this.locker) { return this.managerThreadPriority; } })(), Name = string.Format("Manager Thread ({0})", GetHashCode()) } .Start(); </code></pre> <p>Care to comment about the scoping of lock statements? For example, if I need to use a field in an <code>if</code> statement and that field needs to be locked, should I avoid locking the entire <code>if</code> statement? E.g.</p> <pre><code>bool isDumb; lock (this.locker) isDumb = this.FieldAccessibleByMultipleThreads; if (isDumb) ... </code></pre> <p>Vs.</p> <pre><code>lock (this.locker) { if (this.FieldAccessibleByMultipleThreads) ... } </code></pre>
[ { "answer_id": 155225, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>1) Before you even start the other thread, you don't have to worry about shared access to it at all.</p>\n\n<p>2) Yes, you should lock <em>all</em> access to shared mutable data. (If it's immutable, no locking is required.)</p>\n\n<p>3) Don't use GetHashCode() to indicate a thread ID. Use Thread.ManagedThreadId. I know, there are books which recommend Thread.GetHashCode() - but look at the docs.</p>\n" }, { "answer_id": 155269, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 0, "selected": false, "text": "<p>There is no need to lock anything before you have started any threads.</p>\n\n<p>If you are only going to read a variable there's no need for locks either. It's when you mix reads and writes that you need to use mutexes and similar locking, and you need to lock in both the reading and the writing thread.</p>\n" }, { "answer_id": 156270, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Care to comment about the scoping of lock statements? For example, if I\n need to use a field in an if statement and that field needs to be locked,\n should I avoid locking the entire if statement?</p>\n</blockquote>\n\n<p>In general, it should be scoped for the portion of code that needs the resource being guarded, and no more than that. This is so it can be available for other threads to make use of it as soon as possible.</p>\n\n<p>But <strong>it depends on whether the resource you are locking is part of a bigger picture that has to maintain consistency, or whether it is a standalone resource not related directly to any other</strong>.</p>\n\n<p><em>If you have interrelated parts that need to all change in a synchronized manner, that whole set of parts needs to be locked for the duration of the whole process. \nIf you have an independent, single item uncoupled to anything else, then only that one item needs to be locked long enough for a portion of the process to access it.</em></p>\n\n<p>Another way to say it is, <strong>are you protecting synchronous or asynchronous access to the resource</strong>?</p>\n\n<p>Synchronous access needs to hold on to it longer in general because it cares about a bigger picture that the resource is a part of. It must maintain consistency with related resources. You may very well wrap an entire for-loop in such a case if you want to prevent interruptions until all are processed.</p>\n\n<p>Asynchronous access should hold onto it as briefly as possible. Thus, the more appropriate place for the lock would be inside portions of code, such as inside a for-loop or if-statement so you can free up the individual elements right away even before other ones are processed.</p>\n\n<hr>\n\n<p>Aside from these two considerations, I would add one more. <strong>Avoid nesting of locks involving two different locking objects</strong>. I have learned by experience that it is a likely source of deadlocks, particularly if other parts of the code use them. If the two objects are part of a group that needs to be treated as a single whole all the time, such nesting should be refactored out. </p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
I'm trying to get my multithreading understanding locked down. I'm doing my best to teach myself, but some of these issues need clarification. I've gone through three iterations with a piece of code, experimenting with locking. In this code, the only thing that needs locking is this.managerThreadPriority. First, the simple, procedural approach, with minimalistic locking. ``` var managerThread = new Thread ( new ThreadStart(this.ManagerThreadEntryPoint) ); lock (this.locker) { managerThread.Priority = this.managerThreadPriority; } managerThread.Name = string.Format("Manager Thread ({0})", managerThread.GetHashCode()); managerThread.Start(); ``` Next, a single statement to create and launch a new thread, but the lock appears to be scoped too large, to include the creation and launching of the thread. The compiler doesn't somehow magically know that the lock can be released after this.managerThreadPriority is used. This kind of naive locking should be avoided, I would assume. ``` lock (this.locker) { new Thread ( new ThreadStart(this.ManagerThreadEntryPoint) ) { Priority = this.managerThreadPriority, Name = string.Format("Manager Thread ({0})", GetHashCode()) } .Start(); } ``` Last, a single statement to create and launch a new thread, with a "embedded" lock only around the shared field. ``` new Thread ( new ThreadStart(this.ManagerThreadEntryPoint) ) { Priority = new Func<ThreadPriorty>(() => { lock (this.locker) { return this.managerThreadPriority; } })(), Name = string.Format("Manager Thread ({0})", GetHashCode()) } .Start(); ``` Care to comment about the scoping of lock statements? For example, if I need to use a field in an `if` statement and that field needs to be locked, should I avoid locking the entire `if` statement? E.g. ``` bool isDumb; lock (this.locker) isDumb = this.FieldAccessibleByMultipleThreads; if (isDumb) ... ``` Vs. ``` lock (this.locker) { if (this.FieldAccessibleByMultipleThreads) ... } ```
1) Before you even start the other thread, you don't have to worry about shared access to it at all. 2) Yes, you should lock *all* access to shared mutable data. (If it's immutable, no locking is required.) 3) Don't use GetHashCode() to indicate a thread ID. Use Thread.ManagedThreadId. I know, there are books which recommend Thread.GetHashCode() - but look at the docs.
155,220
<p>We are trying to update our classic asp search engine to protect it from SQL injection. We have a VB 6 function which builds a query dynamically by concatenating a query together based on the various search parameters. We have converted this to a stored procedure using dynamic sql for all parameters except for the keywords.</p> <p>The problem with keywords is that there are a variable number words supplied by the user and we want to search several columns for each keyword. Since we cannot create a separate parameter for each keyword, how can we build a safe query?</p> <p>Example:</p> <pre><code>@CustomerId AS INT @Keywords AS NVARCHAR(MAX) @sql = 'SELECT event_name FROM calendar WHERE customer_id = @CustomerId ' --(loop through each keyword passed in and concatenate) @sql = @sql + 'AND (event_name LIKE ''%' + @Keywords + '%'' OR event_details LIKE ''%' + @Keywords + '%'')' EXEC sp_executesql @sql N'@CustomerId INT, @CustomerId = @CustomerId </code></pre> <p>What is the best way to handle this and maintaining protection from SQL injection? </p>
[ { "answer_id": 155332, "author": "Rikalous", "author_id": 4271, "author_profile": "https://Stackoverflow.com/users/4271", "pm_score": 2, "selected": false, "text": "<p>You may not like to hear this, but it might be better for you to go back to dynamically constructing your SQL query in code before issuing against the database. If you use parameter placeholders in the SQL string you get the protection against SQL injection attacks.</p>\n\n<p>Example:</p>\n\n<pre><code>string sql = \"SELECT Name, Title FROM Staff WHERE UserName=@UserId\";\nusing (SqlCommand cmd = new SqlCommand(sql))\n{\n cmd.Parameters.Add(\"@UserId\", SqlType.VarChar).Value = \"smithj\";\n</code></pre>\n\n<p>You can build the SQL string depending on the set of columns you need to query and then add the parameter values once the string is complete. This is a bit of a pain to do, but I think it is much easier than having really complicated TSQL which unpicks lots of possible permutations of possible inputs.</p>\n" }, { "answer_id": 155362, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 1, "selected": false, "text": "<p>You have 3 options here. </p>\n\n<ol>\n<li><p>Use a <a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html\" rel=\"nofollow noreferrer\">function that converts lists tables</a> and join into it. So you will have something like this.</p>\n\n<pre><code>SELECT * \nFROM calendar c\n JOIN dbo.fnListToTable(@Keywords) k \n ON c.keyword = k.keyword \n</code></pre></li>\n<li><p>Have a fixed set of params, and only allow the maximum of N keywords to be searched on</p>\n\n<pre><code>CREATE PROC spTest\n@Keyword1 varchar(100),\n@Keyword2 varchar(100),\n.... \n</code></pre></li>\n<li><p>Write an escaping string function in TSQL and escape your keywords. </p></li>\n</ol>\n" }, { "answer_id": 156314, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>Unless you need it, you could simply strip out any character that's not in [a-zA-Z ] - most of those things won't be in searches and you should not be able to be injected that way, nor do you have to worry about keywords or anything like that. If you allow quotes, however, you will need to be more careful.</p></li>\n<li><p>Similar to sambo99's #1, you can insert the keywords into a temporary table or table variable and join to it (even using wildcards) without danger of injection:</p></li>\n</ul>\n\n<p>This isn't really dynamic:</p>\n\n<pre><code>SELECT DISTINCT event_name\nFROM calendar\nINNER JOIN #keywords\n ON event_name LIKE '%' + #keywords.keyword + '%'\n OR event_description LIKE '%' + #keywords.keyword + '%'\n</code></pre>\n\n<ul>\n<li><p>You can actually generate an SP with a large number of parameters instead of coding it by hand (set the defaults to '' or NULL depending on your preference in coding your searches). If you found you needed more parameters, it would be simple to increase the number of parameters it generated.</p></li>\n<li><p>You can move the search to a full-text index outside the database like Lucene and then use the Lucene results to pull the matching database rows.</p></li>\n</ul>\n" }, { "answer_id": 3955689, "author": "Ajascopee", "author_id": 478838, "author_profile": "https://Stackoverflow.com/users/478838", "pm_score": 0, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>SELECT * FROM [tablename] WHERE LIKE % +keyword%\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23918/" ]
We are trying to update our classic asp search engine to protect it from SQL injection. We have a VB 6 function which builds a query dynamically by concatenating a query together based on the various search parameters. We have converted this to a stored procedure using dynamic sql for all parameters except for the keywords. The problem with keywords is that there are a variable number words supplied by the user and we want to search several columns for each keyword. Since we cannot create a separate parameter for each keyword, how can we build a safe query? Example: ``` @CustomerId AS INT @Keywords AS NVARCHAR(MAX) @sql = 'SELECT event_name FROM calendar WHERE customer_id = @CustomerId ' --(loop through each keyword passed in and concatenate) @sql = @sql + 'AND (event_name LIKE ''%' + @Keywords + '%'' OR event_details LIKE ''%' + @Keywords + '%'')' EXEC sp_executesql @sql N'@CustomerId INT, @CustomerId = @CustomerId ``` What is the best way to handle this and maintaining protection from SQL injection?
You may not like to hear this, but it might be better for you to go back to dynamically constructing your SQL query in code before issuing against the database. If you use parameter placeholders in the SQL string you get the protection against SQL injection attacks. Example: ``` string sql = "SELECT Name, Title FROM Staff WHERE UserName=@UserId"; using (SqlCommand cmd = new SqlCommand(sql)) { cmd.Parameters.Add("@UserId", SqlType.VarChar).Value = "smithj"; ``` You can build the SQL string depending on the set of columns you need to query and then add the parameter values once the string is complete. This is a bit of a pain to do, but I think it is much easier than having really complicated TSQL which unpicks lots of possible permutations of possible inputs.
155,234
<p>I have a cluster of three mongrels running under nginx, and I deploy the app using Capistrano 2.4.3. When I "cap deploy" when there is a running system, the behavior is: </p> <ol> <li>The app is deployed. The code is successfully updated. </li> <li><p>In the cap deploy output, there is this: </p> <ul> <li>executing "sudo -p 'sudo password: ' mongrel_rails cluster::restart -C /var/www/rails/myapp/current/config/mongrel_cluster.yml"</li> <li>servers: ["myip"]</li> <li>[myip] executing command</li> <li>** [out :: myip] stopping port 9096</li> <li>** [out :: myip] stopping port 9097</li> <li>** [out :: myip] stopping port 9098</li> <li>** [out :: myip] already started port 9096</li> <li>** [out :: myip] already started port 9097</li> <li>** [out :: myip] already started port 9098</li> </ul></li> <li>I check immediately on the server and find that Mongrel is still running, and the PID files are still present for the previous three instances. </li> <li>A short time later (less than one minute), I find that Mongrel is no longer running, the PID files are gone, and it has failed to restart. </li> <li>If I start mongrel on the server by hand, the app starts up just fine. </li> </ol> <p>It seems like 'mongrel_rails cluster::restart' isn't properly waiting for a full stop before attempting a restart of the cluster. How do I diagnose and fix this issue?</p> <p>EDIT: Here's the answer: </p> <p>mongrel_cluster, in the "restart" task, simply does this: </p> <pre><code> def run stop start end </code></pre> <p>It doesn't do any waiting or checking to see that the process exited before invoking "start". This is <a href="http://rubyforge.org/tracker/index.php?func=detail&amp;aid=19657&amp;group_id=1336&amp;atid=5291" rel="nofollow noreferrer">a known bug with an outstanding patch submitted</a>. I applied the patch to Mongrel Cluster and the problem disappeared. </p>
[ { "answer_id": 155401, "author": "salt.racer", "author_id": 757, "author_profile": "https://Stackoverflow.com/users/757", "pm_score": 0, "selected": false, "text": "<p>I hate to be so basic, but it sounds like the pid files are still hanging around when it is trying to start. Make sure that mongrel is stopped by hand. Clean up the pid files by hand. Then do a cap deploy.</p>\n" }, { "answer_id": 156017, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 1, "selected": false, "text": "<p>First, narrow the scope of what your testing by only calling <code>cap deploy:restart</code>. You might want to pass the <code>--debug</code> option to prompt before remote execution or the <code>--dry-run</code> option just to see what's going on as you tweak your settings. </p>\n\n<p>At first glance, this sounds like a permissions issue on the pid files or mongrel processes, but it's difficult to know for sure. A couple things that catch my eye are:</p>\n\n<ul>\n<li><strong>the <code>:runner</code> variable is explicity set to <code>nil</code></strong> -- Was there a specific reason for this?</li>\n<li>Capistrano <strong>2.4 introduced a new behavior for the <code>:admin_runner</code> variable</strong>. Without seeing the entire recipe, is this possibly related to your problem?\n\n<blockquote>\n <p><strong>:runner vs. :admin_runner</strong> (from <a href=\"http://weblog.jamisbuck.org/2008/6/13/capistrano-2-4-0\" rel=\"nofollow noreferrer\">capistrano 2.4 release</a>)\n Some cappers have noted that having deploy:setup and deploy:cleanup run as the :runner user messed up their carefully crafted permissions. I agreed that this was a problem. With this release, deploy:start, deploy:stop, and deploy:restart all continue to use the :runner user when sudoing, but deploy:setup and deploy:cleanup will use the :admin_runner user. The :admin_runner variable is unset, by default, meaning those tasks will sudo as root, but if you want them to run as :runner, just do “set :admin_runner, runner”.</p>\n</blockquote></li>\n</ul>\n\n<p>My recommendation for what to do next. Manually stop the mongrels and clean up the PIDs. Start the mongrels manually. Next, continue to run <code>cap deploy:restart</code> while debugging the problem. Repeat as necessary.</p>\n" }, { "answer_id": 157964, "author": "rwc9u", "author_id": 7778, "author_profile": "https://Stackoverflow.com/users/7778", "pm_score": 3, "selected": true, "text": "<p>You can explicitly tell the mongrel_cluster recipes to remove the pid files before a start by adding the following in your capistrano recipes:</p>\n\n<pre><code># helps keep mongrel pid files clean\nset :mongrel_clean, true\n</code></pre>\n\n<p>This causes it to pass the --clean option to mongrel_cluster_ctl.</p>\n\n<p>I went back and looked at one of my deployment recipes and noticed that I had also changed the way my restart task worked. Take a look at the following message in the mongrel users group:</p>\n\n<p><a href=\"http://rubyforge.org/pipermail/mongrel-users/2007-October/004260.html\" rel=\"nofollow noreferrer\">mongrel users discussion of restart</a></p>\n\n<p>The following is my deploy:restart task. I admit it's a bit of a hack.</p>\n\n<pre><code>namespace :deploy do\n desc \"Restart the Mongrel processes on the app server.\"\n task :restart, :roles =&gt; :app do\n mongrel.cluster.stop\n sleep 2.5\n mongrel.cluster.start\n end\nend\n</code></pre>\n" }, { "answer_id": 257620, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 1, "selected": false, "text": "<p>Either way, my mongrels are starting before the previous stop command has finished shutting 'em all down.</p>\n\n<p>sleep 2.5 is not a good solution, if it takes longer than 2.5 seconds to halt all running mongrels.</p>\n\n<p>There seems to be a need for:</p>\n\n<pre><code>stop &amp;&amp; start\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>stop; start\n</code></pre>\n\n<p>(this is how bash works, &amp;&amp; waits for the first command to finish w/o error, while \";\" simply runs the next command).</p>\n\n<p>I wonder if there is a:</p>\n\n<pre><code>wait cluster_stop\nthen cluster_start\n</code></pre>\n" }, { "answer_id": 257621, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 0, "selected": false, "text": "<p>Good discussion: <a href=\"http://www.ruby-forum.com/topic/139734#745030\" rel=\"nofollow noreferrer\">http://www.ruby-forum.com/topic/139734#745030</a></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13472/" ]
I have a cluster of three mongrels running under nginx, and I deploy the app using Capistrano 2.4.3. When I "cap deploy" when there is a running system, the behavior is: 1. The app is deployed. The code is successfully updated. 2. In the cap deploy output, there is this: * executing "sudo -p 'sudo password: ' mongrel\_rails cluster::restart -C /var/www/rails/myapp/current/config/mongrel\_cluster.yml" * servers: ["myip"] * [myip] executing command * \*\* [out :: myip] stopping port 9096 * \*\* [out :: myip] stopping port 9097 * \*\* [out :: myip] stopping port 9098 * \*\* [out :: myip] already started port 9096 * \*\* [out :: myip] already started port 9097 * \*\* [out :: myip] already started port 9098 3. I check immediately on the server and find that Mongrel is still running, and the PID files are still present for the previous three instances. 4. A short time later (less than one minute), I find that Mongrel is no longer running, the PID files are gone, and it has failed to restart. 5. If I start mongrel on the server by hand, the app starts up just fine. It seems like 'mongrel\_rails cluster::restart' isn't properly waiting for a full stop before attempting a restart of the cluster. How do I diagnose and fix this issue? EDIT: Here's the answer: mongrel\_cluster, in the "restart" task, simply does this: ``` def run stop start end ``` It doesn't do any waiting or checking to see that the process exited before invoking "start". This is [a known bug with an outstanding patch submitted](http://rubyforge.org/tracker/index.php?func=detail&aid=19657&group_id=1336&atid=5291). I applied the patch to Mongrel Cluster and the problem disappeared.
You can explicitly tell the mongrel\_cluster recipes to remove the pid files before a start by adding the following in your capistrano recipes: ``` # helps keep mongrel pid files clean set :mongrel_clean, true ``` This causes it to pass the --clean option to mongrel\_cluster\_ctl. I went back and looked at one of my deployment recipes and noticed that I had also changed the way my restart task worked. Take a look at the following message in the mongrel users group: [mongrel users discussion of restart](http://rubyforge.org/pipermail/mongrel-users/2007-October/004260.html) The following is my deploy:restart task. I admit it's a bit of a hack. ``` namespace :deploy do desc "Restart the Mongrel processes on the app server." task :restart, :roles => :app do mongrel.cluster.stop sleep 2.5 mongrel.cluster.start end end ```
155,243
<p>As a follow up to a <a href="https://stackoverflow.com/questions/151590/java-how-do-detect-a-remote-side-socket-close">recent question</a>, I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO <code>Socket</code> or the NIO <code>SocketChannel</code>.</p> <p>When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know about the fact. The server-side (the one that initiates the shutdown) ends up in state <code>FIN_WAIT2</code>, whereas the client-side (the one that does not explicitly respond to the shutdown) ends up in state <code>CLOSE_WAIT</code>. Why isn't there a method in <code>Socket</code> or <code>SocketChannel</code> that can query the TCP stack to see whether the underlying TCP connection has been terminated? Is it that the TCP stack doesn't provide such status information? Or is it a design decision to avoid a costly call into the kernel?</p> <p>With the help of the users who have already posted some answers to this question, I think I see where the issue might be coming from. The side that doesn't explicitly close the connection ends up in TCP state <code>CLOSE_WAIT</code> meaning that the connection is in the process of shutting down and waits for the side to issue its own <code>CLOSE</code> operation. I suppose it's fair enough that <code>isConnected</code> returns <code>true</code> and <code>isClosed</code> returns <code>false</code>, but why isn't there something like <code>isClosing</code>?</p> <p>Below are the test classes that use pre-NIO sockets. But identical results are obtained using NIO.</p> <pre><code>import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws Exception { final ServerSocket ss = new ServerSocket(12345); final Socket cs = ss.accept(); System.out.println("Accepted connection"); Thread.sleep(5000); cs.close(); System.out.println("Closed connection"); ss.close(); Thread.sleep(100000); } } import java.net.Socket; public class MyClient { public static void main(String[] args) throws Exception { final Socket s = new Socket("localhost", 12345); for (int i = 0; i &lt; 10; i++) { System.out.println("connected: " + s.isConnected() + ", closed: " + s.isClosed()); Thread.sleep(1000); } Thread.sleep(100000); } } </code></pre> <p>When the test client connects to the test server the output remains unchanged even after the server initiates the shutdown of the connection:</p> <pre><code>connected: true, closed: false connected: true, closed: false ... </code></pre>
[ { "answer_id": 155328, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 4, "selected": false, "text": "<p>The underlying sockets API doesn't have such a notification. </p>\n\n<p>The sending TCP stack won't send the FIN bit until the last packet anyway, so there could be a lot of data buffered from when the sending application logically closed its socket before that data is even sent. Likewise, data that's buffered because the network is quicker than the receiving application (I don't know, maybe you're relaying it over a slower connection) could be significant to the receiver and you wouldn't want the receiving application to discard it just because the FIN bit has been received by the stack.</p>\n" }, { "answer_id": 155342, "author": "Lorenzo Boccaccia", "author_id": 2273540, "author_profile": "https://Stackoverflow.com/users/2273540", "pm_score": 2, "selected": false, "text": "<p>It's an interesting topic. I've dug through the java code just now to check. From my finding, there are two distinct problems: the first is the TCP RFC itself, which allows for remotely closed socket to transmit data in half-duplex, so a remotely closed socket is still half open. As per the RFC, RST doesn't close the connection, you need to send an explicit ABORT command; so Java allow for sending data through half closed socket </p>\n\n<p>(There are two methods for reading the close status at both of the endpoint.) </p>\n\n<p>The other problem is that the implementation say that this behavior is optional. As Java strives to be portable, they implemented the best common feature. Maintaining a map of (OS, implementation of half duplex) would have been a problem, I guess.</p>\n" }, { "answer_id": 156403, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 4, "selected": false, "text": "<p>I think this is more of a socket programming question. Java is just following the socket programming tradition.</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/Transmission_Control_Protocol\" rel=\"noreferrer\">Wikipedia</a>: </p>\n\n<blockquote>\n <p>TCP provides reliable, ordered\n delivery of a stream of bytes from one\n program on one computer to another\n program on another computer.</p>\n</blockquote>\n\n<p>Once the handshake is done, TCP does not make any distinction between two end points (client and server). The term \"client\" and \"server\" is mostly for convenience. So, the \"server\" could be sending data and \"client\" could be sending some other data simultaneously to each other.</p>\n\n<p>The term \"Close\" is also misleading. There's only FIN declaration, which means \"I am not going to send you any more stuff.\" But this does not mean that there are no packets in flight, or the other has no more to say. If you implement snail mail as the data link layer, or if your packet traveled different routes, it's possible that the receiver receives packets in wrong order. TCP knows how to fix this for you.</p>\n\n<p>Also you, as a program, may not have time to keep checking what's in the buffer. So, at your convenience you can check what's in the buffer. All in all, current socket implementation is not so bad. If there actually were isPeerClosed(), that's extra call you have to make every time you want to call read.</p>\n" }, { "answer_id": 157139, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 2, "selected": false, "text": "<p>The reason for this behaviour (which is not Java specific) is the fact that you don't get any status information from the TCP stack. After all, a socket is just another file handle and you can't find out if there's actual data to read from it without actually trying to (<code>select(2)</code> won't help there, it only signals that you can try without blocking). </p>\n\n<p>For more information see the <a href=\"http://www.unixguide.net/network/socketfaq/\" rel=\"nofollow noreferrer\">Unix socket FAQ</a>.</p>\n" }, { "answer_id": 157534, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 3, "selected": false, "text": "<p>Since none of the answers so far fully answer the question, I'm summarizing my current understanding of the issue.</p>\n\n<p>When a TCP connection is established and one peer calls <code>close()</code> or <code>shutdownOutput()</code> on its socket, the socket on the other side of the connection transitions into <code>CLOSE_WAIT</code> state. In principle, it's possible to find out from the TCP stack whether a socket is in <code>CLOSE_WAIT</code> state without calling <code>read/recv</code> (e.g., <code>getsockopt()</code> on Linux: <a href=\"http://www.developerweb.net/forum/showthread.php?t=4395\" rel=\"noreferrer\">http://www.developerweb.net/forum/showthread.php?t=4395</a>), but that's not portable.</p>\n\n<p>Java's <code>Socket</code> class seems to be designed to provide an abstraction comparable to a BSD TCP socket, probably because this is the level of abstraction to which people are used to when programming TCP/IP applications. BSD sockets are a generalization supporting sockets other than just INET (e.g., TCP) ones, so they don't provide a portable way of finding out the TCP state of a socket.</p>\n\n<p>There's no method like <code>isCloseWait()</code> because people used to programming TCP applications at the level of abstraction offered by BSD sockets don't expect Java to provide any extra methods.</p>\n" }, { "answer_id": 192392, "author": "Ray", "author_id": 13327, "author_profile": "https://Stackoverflow.com/users/13327", "pm_score": 0, "selected": false, "text": "<p>Only writes require that packets be exchanged which allows for the loss of connection to be determined. A common work around is to use the KEEP ALIVE option.</p>\n" }, { "answer_id": 476674, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 2, "selected": false, "text": "<p>This is a flaw of Java's (and all others' that I've looked at) OO socket classes -- no access to the select system call.</p>\n\n<p>Correct answer in C:</p>\n\n<pre><code>struct timeval tp; \nfd_set in; \nfd_set out; \nfd_set err; \n\nFD_ZERO (in); \nFD_ZERO (out); \nFD_ZERO (err); \n\nFD_SET(socket_handle, err); \n\ntp.tv_sec = 0; /* or however long you want to wait */ \ntp.tv_usec = 0; \nselect(socket_handle + 1, in, out, err, &amp;tp); \n\nif (FD_ISSET(socket_handle, err) { \n /* handle closed socket */ \n} \n</code></pre>\n" }, { "answer_id": 1085322, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>the Java IO stack definitely sends FIN when it gets destructed on an abrupt teardown. It just makes no sense that you can't detect this, b/c most clients only send the FIN if they are shutting down the connection.</p>\n\n<p>...another reason i am really beginning to hate the NIO Java classes. It seems like everything is a little half-ass. </p>\n" }, { "answer_id": 7010761, "author": "Uncle Per", "author_id": 887863, "author_profile": "https://Stackoverflow.com/users/887863", "pm_score": 3, "selected": false, "text": "<p>Detecting whether the remote side of a (TCP) socket connection has closed can be done with the java.net.Socket.sendUrgentData(int) method, and catching the IOException it throws if the remote side is down. This has been tested between Java-Java, and Java-C.</p>\n\n<p>This avoids the problem of designing the communication protocol to use some sort of pinging mechanism. By disabling OOBInline on a socket (setOOBInline(false), any OOB data received is silently discarded, but OOB data can still be sent. If the remote side is closed, a connection reset is attempted, fails, and causes some IOException to be thrown.</p>\n\n<p>If you actually use OOB data in your protocol, then your mileage may vary.</p>\n" }, { "answer_id": 7914693, "author": "JimmyB", "author_id": 1015327, "author_profile": "https://Stackoverflow.com/users/1015327", "pm_score": -1, "selected": false, "text": "<p>When it comes to dealing with half-open Java sockets, one might want to have a look at\n<a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#isInputShutdown%28%29\" rel=\"nofollow\">isInputShutdown()</a> and <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#isOutputShutdown%28%29\" rel=\"nofollow\">isOutputShutdown()</a>.</p>\n" }, { "answer_id": 9399617, "author": "Matthieu", "author_id": 1098603, "author_profile": "https://Stackoverflow.com/users/1098603", "pm_score": 5, "selected": false, "text": "<p>I have been using Sockets often, mostly with Selectors, and though not a Network OSI expert, from my understanding, calling <code>shutdownOutput()</code> on a Socket actually sends something on the network (FIN) that wakes up my Selector on the other side (same behaviour in C language). Here you have <strong>detection</strong>: actually detecting a read operation that will fail when you try it.</p>\n\n<p>In the code you give, closing the socket will shutdown both input and output streams, without possibilities of reading the data that might be available, therefore loosing them. The Java <code>Socket.close()</code> method performs a \"graceful\" disconnection (opposite as what I initially thought) in that the data left in the output stream will be sent <em>followed by a FIN</em> to signal its close. The FIN will be ACK'd by the other side, as any regular packet would<sup>1</sup>.</p>\n\n<p>If you need to wait for the other side to close its socket, you need to wait for its FIN. And to achieve that, you <strong>have to</strong> detect <code>Socket.getInputStream().read() &lt; 0</code>, which means you should <em>not</em> close your socket, as it would <strong>close its <code>InputStream</code></strong>.</p>\n\n<p>From what I did in C, and now in Java, achieving such a synchronized close should be done like this:</p>\n\n<ol>\n<li>Shutdown socket output (sends FIN on the other end, this is the last thing that will ever be sent by this socket). Input is still open so you can <code>read()</code> and detect the remote <code>close()</code></li>\n<li>Read the socket <code>InputStream</code> until we receive the reply-FIN from the other end (as it will detect the FIN, it will go through the same graceful diconnection process). This is important on some OS as they don't actually close the socket as long as one of its buffer still contains data. They're called \"ghost\" socket and use up descriptor numbers in the OS (that might not be an issue anymore with modern OS)</li>\n<li>Close the socket (by either calling <code>Socket.close()</code> or closing its <code>InputStream</code> or <code>OutputStream</code>)</li>\n</ol>\n\n<p>As shown in the following Java snippet:</p>\n\n<pre><code>public void synchronizedClose(Socket sok) {\n InputStream is = sok.getInputStream();\n sok.shutdownOutput(); // Sends the 'FIN' on the network\n while (is.read() &gt; 0) ; // \"read()\" returns '-1' when the 'FIN' is reached\n sok.close(); // or is.close(); Now we can close the Socket\n}\n</code></pre>\n\n<p>Of course both sides <em>have to</em> use the same way of closing, or the sending part might always be sending enough data to keep the <code>while</code> loop busy (e.g. if the sending part is only sending data and never reading to detect connection termination. Which is clumsy, but you might not have control on that).</p>\n\n<p>As @WarrenDew pointed out in his comment, discarding the data in the program (application layer) induces a non-graceful disconnection at application layer: though all data were received at TCP layer (the <code>while</code> loop), they are discarded.</p>\n\n<p><sup>1</sup>: From \"<a href=\"http://www.springer.com/us/book/9781846280306\" rel=\"nofollow noreferrer\">Fundamental Networking in Java</a>\": see fig. 3.3 p.45, and the whole §3.7, pp 43-48</p>\n" }, { "answer_id": 12112656, "author": "Dean Hiller", "author_id": 517781, "author_profile": "https://Stackoverflow.com/users/517781", "pm_score": 2, "selected": false, "text": "<p>Here is a lame workaround. Use SSL ;) and SSL does a close handshake on teardown so you are notified of the socket being closed (most implementations seem to do a propert handshake teardown that is).</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16724/" ]
As a follow up to a [recent question](https://stackoverflow.com/questions/151590/java-how-do-detect-a-remote-side-socket-close), I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO `Socket` or the NIO `SocketChannel`. When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know about the fact. The server-side (the one that initiates the shutdown) ends up in state `FIN_WAIT2`, whereas the client-side (the one that does not explicitly respond to the shutdown) ends up in state `CLOSE_WAIT`. Why isn't there a method in `Socket` or `SocketChannel` that can query the TCP stack to see whether the underlying TCP connection has been terminated? Is it that the TCP stack doesn't provide such status information? Or is it a design decision to avoid a costly call into the kernel? With the help of the users who have already posted some answers to this question, I think I see where the issue might be coming from. The side that doesn't explicitly close the connection ends up in TCP state `CLOSE_WAIT` meaning that the connection is in the process of shutting down and waits for the side to issue its own `CLOSE` operation. I suppose it's fair enough that `isConnected` returns `true` and `isClosed` returns `false`, but why isn't there something like `isClosing`? Below are the test classes that use pre-NIO sockets. But identical results are obtained using NIO. ``` import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws Exception { final ServerSocket ss = new ServerSocket(12345); final Socket cs = ss.accept(); System.out.println("Accepted connection"); Thread.sleep(5000); cs.close(); System.out.println("Closed connection"); ss.close(); Thread.sleep(100000); } } import java.net.Socket; public class MyClient { public static void main(String[] args) throws Exception { final Socket s = new Socket("localhost", 12345); for (int i = 0; i < 10; i++) { System.out.println("connected: " + s.isConnected() + ", closed: " + s.isClosed()); Thread.sleep(1000); } Thread.sleep(100000); } } ``` When the test client connects to the test server the output remains unchanged even after the server initiates the shutdown of the connection: ``` connected: true, closed: false connected: true, closed: false ... ```
I have been using Sockets often, mostly with Selectors, and though not a Network OSI expert, from my understanding, calling `shutdownOutput()` on a Socket actually sends something on the network (FIN) that wakes up my Selector on the other side (same behaviour in C language). Here you have **detection**: actually detecting a read operation that will fail when you try it. In the code you give, closing the socket will shutdown both input and output streams, without possibilities of reading the data that might be available, therefore loosing them. The Java `Socket.close()` method performs a "graceful" disconnection (opposite as what I initially thought) in that the data left in the output stream will be sent *followed by a FIN* to signal its close. The FIN will be ACK'd by the other side, as any regular packet would1. If you need to wait for the other side to close its socket, you need to wait for its FIN. And to achieve that, you **have to** detect `Socket.getInputStream().read() < 0`, which means you should *not* close your socket, as it would **close its `InputStream`**. From what I did in C, and now in Java, achieving such a synchronized close should be done like this: 1. Shutdown socket output (sends FIN on the other end, this is the last thing that will ever be sent by this socket). Input is still open so you can `read()` and detect the remote `close()` 2. Read the socket `InputStream` until we receive the reply-FIN from the other end (as it will detect the FIN, it will go through the same graceful diconnection process). This is important on some OS as they don't actually close the socket as long as one of its buffer still contains data. They're called "ghost" socket and use up descriptor numbers in the OS (that might not be an issue anymore with modern OS) 3. Close the socket (by either calling `Socket.close()` or closing its `InputStream` or `OutputStream`) As shown in the following Java snippet: ``` public void synchronizedClose(Socket sok) { InputStream is = sok.getInputStream(); sok.shutdownOutput(); // Sends the 'FIN' on the network while (is.read() > 0) ; // "read()" returns '-1' when the 'FIN' is reached sok.close(); // or is.close(); Now we can close the Socket } ``` Of course both sides *have to* use the same way of closing, or the sending part might always be sending enough data to keep the `while` loop busy (e.g. if the sending part is only sending data and never reading to detect connection termination. Which is clumsy, but you might not have control on that). As @WarrenDew pointed out in his comment, discarding the data in the program (application layer) induces a non-graceful disconnection at application layer: though all data were received at TCP layer (the `while` loop), they are discarded. 1: From "[Fundamental Networking in Java](http://www.springer.com/us/book/9781846280306)": see fig. 3.3 p.45, and the whole §3.7, pp 43-48
155,246
<p>I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data. </p> <p>What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic.</p>
[ { "answer_id": 155270, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "<p>This is <em>one</em> way to do it... there are likely 10 others that are better/more efficient, but it sounds like this is done very infrequently, so here goes...</p>\n\n<p>get a list of the <code>tables</code> from <code>sysobjects</code>, then loop over those with a cursor, calling <code>sp_execsql('truncate table ' + @table_name)</code> for each <code>iteration</code>.</p>\n" }, { "answer_id": 155275, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 9, "selected": true, "text": "<p>For SQL 2005, </p>\n\n<pre><code>EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'\n</code></pre>\n\n<p>Couple more links for <a href=\"http://www.databasejournal.com/scripts/article.php/2226781\" rel=\"noreferrer\">2000</a> and <a href=\"http://www.keithrull.com/2007/09/07/HowToTruncateMultipleTablesInSQLServerAndTheMagicOfSpMSforeachtable.aspx\" rel=\"noreferrer\">2005/2008</a>..</p>\n" }, { "answer_id": 155327, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 4, "selected": false, "text": "<p>Truncating all of the tables will only work if you don't have any foreign key relationships between your tables, as SQL Server will not allow you to truncate a table with a foreign key.</p>\n\n<p>An alternative to this is to determine the tables with foreign keys and delete from these first, you can then truncate the tables without foreign keys afterwards.</p>\n\n<p>See <a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=65341\" rel=\"noreferrer\">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=65341</a> and <a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=72957\" rel=\"noreferrer\">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=72957</a> for further details.</p>\n" }, { "answer_id": 156813, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 9, "selected": false, "text": "<p>When dealing with deleting data from tables which have foreign key relationships - which is basically the case with any properly designed database - we can disable all the constraints, delete all the data and then re-enable constraints</p>\n\n<pre><code>-- disable all constraints\nEXEC sp_MSForEachTable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\n\n-- delete data in all tables\nEXEC sp_MSForEachTable \"DELETE FROM ?\"\n\n-- enable all constraints\nexec sp_MSForEachTable \"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"\n</code></pre>\n\n<p>More on disabling constraints and triggers <a href=\"https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger#123966\">here</a></p>\n\n<p>if some of the tables have identity columns we may want to reseed them</p>\n\n<pre><code>EXEC sp_MSForEachTable \"DBCC CHECKIDENT ( '?', RESEED, 0)\"\n</code></pre>\n\n<p>Note that the behaviour of RESEED differs between brand new table, and one which had had some data inserted previously from <a href=\"http://msdn.microsoft.com/en-us/library/aa258817(SQL.80).aspx\" rel=\"noreferrer\">BOL</a>:</p>\n\n<blockquote>\n <p><strong>DBCC CHECKIDENT ('table_name', RESEED, newReseedValue)</strong></p>\n \n <p>The current identity value is set to\n the newReseedValue. If no rows have\n been inserted to the table since it\n was created, the first row inserted\n after executing DBCC CHECKIDENT will\n use newReseedValue as the identity.\n Otherwise, the next row inserted will\n use newReseedValue + 1. If the value\n of newReseedValue is less than the\n maximum value in the identity column,\n error message 2627 will be generated\n on subsequent references to the table.</p>\n</blockquote>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/23566/robert-claypool\">Robert</a> for pointing out the fact that disabling constraints does not allow to use truncate, the constraints would have to be dropped, and then recreated</p>\n" }, { "answer_id": 161482, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Don't do this! Really, not a good idea.</p>\n\n<p>If you know which tables you want to truncate, create a stored procedure which truncates them. You can fix the order to avoid foreign key problems.</p>\n\n<p>If you really want to truncate them all (so you can BCP load them for example) you would be just as quick to drop the database and create a new one from scratch, which would have the additional benefit that you know exactly where you are.</p>\n" }, { "answer_id": 1075421, "author": "Brian Spencer", "author_id": 128856, "author_profile": "https://Stackoverflow.com/users/128856", "pm_score": 0, "selected": false, "text": "<p>I do not see why clearing data would be better than a script to drop and re-create each table.</p>\n\n<p>That or keep a back up of your empty DB and restore it over old one</p>\n" }, { "answer_id": 1262252, "author": "Chris Chilvers", "author_id": 35233, "author_profile": "https://Stackoverflow.com/users/35233", "pm_score": 3, "selected": false, "text": "<p>An alternative option I like to use with MSSQL Server Deveploper or Enterprise is to create a snapshot of the database immediately after creating the empty schema. At that point you can just keep restoring the database back to the snapshot.</p>\n" }, { "answer_id": 1262640, "author": "A-K", "author_id": 108977, "author_profile": "https://Stackoverflow.com/users/108977", "pm_score": 2, "selected": false, "text": "<p>It is much easier (and possibly even faster) to script out your database, then just drop and create it from the script.</p>\n" }, { "answer_id": 1262993, "author": "onupdatecascade", "author_id": 139938, "author_profile": "https://Stackoverflow.com/users/139938", "pm_score": 2, "selected": false, "text": "<p>Make an empty \"template\" database, take a full backup. When you need to refresh, just restore using WITH REPLACE. Fast, simple, bulletproof. And if a couple tables here or there need some base data(e.g. config information, or just basic information that makes your app run) it handles that too.</p>\n" }, { "answer_id": 12719464, "author": "Chris KL", "author_id": 58110, "author_profile": "https://Stackoverflow.com/users/58110", "pm_score": 6, "selected": false, "text": "<p>Here's the king daddy of database wiping scripts. It will clear all tables and reseed them correctly:</p>\n\n<pre><code>SET QUOTED_IDENTIFIER ON;\nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? NOCHECK CONSTRAINT ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? DISABLE TRIGGER ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; DELETE FROM ?' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? CHECK CONSTRAINT ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? ENABLE TRIGGER ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON';\n\nIF NOT EXISTS (\n SELECT\n *\n FROM\n SYS.IDENTITY_COLUMNS\n JOIN SYS.TABLES ON SYS.IDENTITY_COLUMNS.Object_ID = SYS.TABLES.Object_ID\n WHERE\n SYS.TABLES.Object_ID = OBJECT_ID('?') AND SYS.IDENTITY_COLUMNS.Last_Value IS NULL\n)\nAND OBJECTPROPERTY( OBJECT_ID('?'), 'TableHasIdentity' ) = 1\n\n DBCC CHECKIDENT ('?', RESEED, 0) WITH NO_INFOMSGS;\n</code></pre>\n\n<p>Enjoy, but be careful!</p>\n" }, { "answer_id": 13045333, "author": "Edward Weinert", "author_id": 898739, "author_profile": "https://Stackoverflow.com/users/898739", "pm_score": 0, "selected": false, "text": "<p>Before truncating the tables you have to remove all foreign keys. Use this <a href=\"http://social.technet.microsoft.com/wiki/contents/articles/2958.script-to-create-all-foreign-keys-en-us.aspx\" rel=\"nofollow\">script</a> to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.</p>\n" }, { "answer_id": 13524593, "author": "Somendra Tiwari", "author_id": 1731719, "author_profile": "https://Stackoverflow.com/users/1731719", "pm_score": 0, "selected": false, "text": "<p>select 'delete from ' +TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'</p>\n\n<p>where result come.</p>\n\n<p>Copy and paste on query window and run the command</p>\n" }, { "answer_id": 18344855, "author": "Chris Smith", "author_id": 194872, "author_profile": "https://Stackoverflow.com/users/194872", "pm_score": 2, "selected": false, "text": "<p>If you want to keep data in a particular table (i.e. a static lookup table) while deleting/truncating data in other tables within the same db, then you need a loop with the exceptions in it. This is what I was looking for when I stumbled onto this question. </p>\n\n<p>sp_MSForEachTable seems buggy to me (i.e. inconsistent behavior with IF statements) which is probably why its undocumented by MS.</p>\n\n<pre><code>declare @LastObjectID int = 0\ndeclare @TableName nvarchar(100) = ''\nset @LastObjectID = (select top 1 [object_id] from sys.tables where [object_id] &gt; @LastObjectID order by [object_id])\nwhile(@LastObjectID is not null)\nbegin\n set @TableName = (select top 1 [name] from sys.tables where [object_id] = @LastObjectID)\n\n if(@TableName not in ('Profiles', 'ClientDetails', 'Addresses', 'AgentDetails', 'ChainCodes', 'VendorDetails'))\n begin\n exec('truncate table [' + @TableName + ']')\n end \n\n set @LastObjectID = (select top 1 [object_id] from sys.tables where [object_id] &gt; @LastObjectID order by [object_id])\nend\n</code></pre>\n" }, { "answer_id": 21463625, "author": "Steve Hood", "author_id": 2871082, "author_profile": "https://Stackoverflow.com/users/2871082", "pm_score": 1, "selected": false, "text": "<p>Run the commented out section once, populate the _TruncateList table with the tables you want truncated, then run the rest of the script. The _ScriptLog table will need to be cleaned up over time if you do this a lot.</p>\n\n<p>You can modify this if you want to do all tables, just put in SELECT name INTO #TruncateList FROM sys.tables. However, you usually don't want to do them all.</p>\n\n<p>Also, this will affect all foreign keys in the database, and you can modify that as well if it's too blunt-force for your application. It's not for my purposes.</p>\n\n<pre><code>/*\nCREATE TABLE _ScriptLog \n(\n ID Int NOT NULL Identity(1,1)\n , DateAdded DateTime2 NOT NULL DEFAULT GetDate()\n , Script NVarChar(4000) NOT NULL\n)\n\nCREATE UNIQUE CLUSTERED INDEX IX_ScriptLog_DateAdded_ID_U_C ON _ScriptLog\n(\n DateAdded\n , ID\n)\n\nCREATE TABLE _TruncateList\n(\n TableName SysName PRIMARY KEY\n)\n*/\nIF OBJECT_ID('TempDB..#DropFK') IS NOT NULL BEGIN\n DROP TABLE #DropFK\nEND\n\nIF OBJECT_ID('TempDB..#TruncateList') IS NOT NULL BEGIN\n DROP TABLE #TruncateList\nEND\n\nIF OBJECT_ID('TempDB..#CreateFK') IS NOT NULL BEGIN\n DROP TABLE #CreateFK\nEND\n\nSELECT Scripts = 'ALTER TABLE ' + '[' + OBJECT_NAME(f.parent_object_id)+ ']'+\n' DROP CONSTRAINT ' + '[' + f.name + ']'\nINTO #DropFK\nFROM .sys.foreign_keys AS f\nINNER JOIN .sys.foreign_key_columns AS fc\nON f.OBJECT_ID = fc.constraint_object_id\n\nSELECT TableName\nINTO #TruncateList\nFROM _TruncateList\n\nSELECT Scripts = 'ALTER TABLE ' + const.parent_obj + '\n ADD CONSTRAINT ' + const.const_name + ' FOREIGN KEY (\n ' + const.parent_col_csv + '\n ) REFERENCES ' + const.ref_obj + '(' + const.ref_col_csv + ')\n'\nINTO #CreateFK\nFROM (\n SELECT QUOTENAME(fk.NAME) AS [const_name]\n ,QUOTENAME(schParent.NAME) + '.' + QUOTENAME(OBJECT_name(fkc.parent_object_id)) AS [parent_obj]\n ,STUFF((\n SELECT ',' + QUOTENAME(COL_NAME(fcP.parent_object_id, fcp.parent_column_id))\n FROM sys.foreign_key_columns AS fcP\n WHERE fcp.constraint_object_id = fk.object_id\n FOR XML path('')\n ), 1, 1, '') AS [parent_col_csv]\n ,QUOTENAME(schRef.NAME) + '.' + QUOTENAME(OBJECT_NAME(fkc.referenced_object_id)) AS [ref_obj]\n ,STUFF((\n SELECT ',' + QUOTENAME(COL_NAME(fcR.referenced_object_id, fcR.referenced_column_id))\n FROM sys.foreign_key_columns AS fcR\n WHERE fcR.constraint_object_id = fk.object_id\n FOR XML path('')\n ), 1, 1, '') AS [ref_col_csv]\n FROM sys.foreign_key_columns AS fkc\n INNER JOIN sys.foreign_keys AS fk ON fk.object_id = fkc.constraint_object_id\n INNER JOIN sys.objects AS oParent ON oParent.object_id = fkc.parent_object_id\n INNER JOIN sys.schemas AS schParent ON schParent.schema_id = oParent.schema_id\n INNER JOIN sys.objects AS oRef ON oRef.object_id = fkc.referenced_object_id\n INNER JOIN sys.schemas AS schRef ON schRef.schema_id = oRef.schema_id\n GROUP BY fkc.parent_object_id\n ,fkc.referenced_object_id\n ,fk.NAME\n ,fk.object_id\n ,schParent.NAME\n ,schRef.NAME\n ) AS const\nORDER BY const.const_name\n\nINSERT INTO _ScriptLog (Script)\nSELECT Scripts\nFROM #CreateFK\n\nDECLARE @Cmd NVarChar(4000)\n , @TableName SysName\n\nWHILE 0 &lt; (SELECT Count(1) FROM #DropFK) BEGIN\n SELECT TOP 1 @Cmd = Scripts \n FROM #DropFK\n\n EXEC (@Cmd)\n\n DELETE #DropFK WHERE Scripts = @Cmd\nEND\n\nWHILE 0 &lt; (SELECT Count(1) FROM #TruncateList) BEGIN\n SELECT TOP 1 @Cmd = N'TRUNCATE TABLE ' + TableName\n , @TableName = TableName\n FROM #TruncateList\n\n EXEC (@Cmd)\n\n DELETE #TruncateList WHERE TableName = @TableName\nEND\n\nWHILE 0 &lt; (SELECT Count(1) FROM #CreateFK) BEGIN\n SELECT TOP 1 @Cmd = Scripts \n FROM #CreateFK\n\n EXEC (@Cmd)\n\n DELETE #CreateFK WHERE Scripts = @Cmd\nEND\n</code></pre>\n" }, { "answer_id": 22527902, "author": "Captain Kenpachi", "author_id": 1131949, "author_profile": "https://Stackoverflow.com/users/1131949", "pm_score": 6, "selected": false, "text": "<p>The simplest way of doing this is to </p>\n\n<ol>\n<li>open up SQL Management Studio</li>\n<li>navigate to your database</li>\n<li>Right-click and select Tasks->Generate Scripts (pic 1)</li>\n<li>On the \"choose Objects\" screen, select the \"select specific objects\" option and check \"tables\" (pic 2)</li>\n<li>on the next screen, select \"advanced\" and then change the \"Script DROP and CREATE\" option to \"Script DROP and CREATE\" (pic 3)</li>\n<li>Choose to save script to a new editor window or a file and run as necessary.</li>\n</ol>\n\n<p>this will give you a script that drops and recreates all your tables without the need to worry about debugging or whether you've included everything. While this performs more than just a truncate, the results are the same. Just keep in mind that your auto-incrementing primary keys will start at 0, as opposed to truncated tables which will remember the last value assigned. You can also execute this from code if you don't have access to Management studio on your PreProd or Production environments.</p>\n\n<p>1.</p>\n\n<p><img src=\"https://i.stack.imgur.com/KWXSP.png\" alt=\"enter image description here\"></p>\n\n<p>2.</p>\n\n<p><img src=\"https://i.stack.imgur.com/fwUxD.png\" alt=\"enter image description here\"></p>\n\n<p>3.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Jq2E0.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 23136284, "author": "Scott Allen", "author_id": 1700309, "author_profile": "https://Stackoverflow.com/users/1700309", "pm_score": 2, "selected": false, "text": "<p>The hardest part of truncating all tables is removing and re-ading the foreign key constraints.</p>\n\n<p>The following query creates the drop &amp; create statements for each constraint relating to each table name in @myTempTable. If you would like to generate these for all the tables, you may simple use information schema to gather these table names instead.</p>\n\n<pre><code>DECLARE @myTempTable TABLE (tableName varchar(200))\nINSERT INTO @myTempTable(tableName) VALUES\n('TABLE_ONE'),\n('TABLE_TWO'),\n('TABLE_THREE')\n\n\n-- DROP FK Contraints\nSELECT 'alter table '+quotename(schema_name(ob.schema_id))+\n '.'+quotename(object_name(ob.object_id))+ ' drop constraint ' + quotename(fk.name) \n FROM sys.objects ob INNER JOIN sys.foreign_keys fk ON fk.parent_object_id = ob.object_id\n WHERE fk.referenced_object_id IN \n (\n SELECT so.object_id \n FROM sys.objects so JOIN sys.schemas sc\n ON so.schema_id = sc.schema_id\n WHERE so.name IN (SELECT * FROM @myTempTable) AND sc.name=N'dbo' AND type in (N'U'))\n\n\n -- CREATE FK Contraints\n SELECT 'ALTER TABLE [PIMSUser].[dbo].[' +cast(c.name as varchar(255)) + '] WITH NOCHECK ADD CONSTRAINT ['+ cast(f.name as varchar(255)) +'] FOREIGN KEY (['+ cast(fc.name as varchar(255)) +'])\n REFERENCES [PIMSUser].[dbo].['+ cast(p.name as varchar(255)) +'] (['+cast(rc.name as varchar(255))+'])'\nFROM sysobjects f\n INNER JOIN sys.sysobjects c ON f.parent_obj = c.id\n INNER JOIN sys.sysreferences r ON f.id = r.constid\n INNER JOIN sys.sysobjects p ON r.rkeyid = p.id\n INNER JOIN sys.syscolumns rc ON r.rkeyid = rc.id and r.rkey1 = rc.colid\n INNER JOIN sys.syscolumns fc ON r.fkeyid = fc.id and r.fkey1 = fc.colid\nWHERE \n f.type = 'F'\n AND\n cast(p.name as varchar(255)) IN (SELECT * FROM @myTempTable)\n</code></pre>\n\n<p>I then just copy out the statements to run - but with a bit of dev effort you could use a cursor to run them dynamically.</p>\n" }, { "answer_id": 51174785, "author": "Mohit", "author_id": 1001188, "author_profile": "https://Stackoverflow.com/users/1001188", "pm_score": 1, "selected": false, "text": "<p>It is a little late but it might help someone.\nI created a procedure sometimes back which does the following using T-SQL:</p>\n\n<ol>\n<li>Store all constraints in a Temporary table</li>\n<li>Drop All Constraints</li>\n<li>Truncate all tables with exception of some tables, which does not need truncation</li>\n<li>Recreate all Constraints.</li>\n</ol>\n\n<p>I have listed it on my blog <a href=\"http://mohitleekha.blogspot.com/2018/07/truncate-microsoft-sql-database-without.html\" rel=\"nofollow noreferrer\">here</a></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data. What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic.
For SQL 2005, ``` EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' ``` Couple more links for [2000](http://www.databasejournal.com/scripts/article.php/2226781) and [2005/2008](http://www.keithrull.com/2007/09/07/HowToTruncateMultipleTablesInSQLServerAndTheMagicOfSpMSforeachtable.aspx)..
155,260
<p>I have been learning about the basics of C# but haven't come across a good explanation of what this is:</p> <pre><code>var l = new List&lt;string&gt;(); </code></pre> <p>I don't know what the <code>&lt;string&gt;</code> is doing or if it's the <code>List</code> that is doing the magic. I have also seen objects been thrown within the <code>&lt; &gt;</code> tags.</p> <p>Can someone explain this to me with examples, please?</p>
[ { "answer_id": 155280, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>This is .NET Generics. The type within the &lt; > denotes the type of element contained in the list.</p>\n\n<p>with ArrayList you'd have to cast the elements inside... </p>\n\n<pre><code>int x = (int)myArrayList[4];\n</code></pre>\n\n<p>with List you can avoid that step because the compiler already knows the type.</p>\n\n<pre><code>int x = myList[4];\n</code></pre>\n\n<p>Generics are available in .NET 2.0 and later.</p>\n" }, { "answer_id": 155286, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>Those are generics. You are making a List that only contains strings. You could also say</p>\n\n<pre><code>List&lt;int&gt;\n</code></pre>\n\n<p>and get a list that only contains ints. </p>\n\n<p>Generics is a huge topic, too big for a single answer here.</p>\n" }, { "answer_id": 155292, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 1, "selected": false, "text": "<p>Those are known as Generics (specifically <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"nofollow noreferrer\">List</a> is a generic class).</p>\n\n<p>Reading from MSDN</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/512aeb7t.aspx\" rel=\"nofollow noreferrer\">Generics (C# Programming Guide)</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms379564.aspx\" rel=\"nofollow noreferrer\">An Introduction to C# Generics</a> </li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms172192.aspx\" rel=\"nofollow noreferrer\">Generics in the .NET Framework</a> </li>\n</ul>\n" }, { "answer_id": 155295, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>It's <em>generics</em> - it's a form of type parameterisation. In your example, it's making l refer to a list of strings - the list will only ever contain strings: the compiler treats it (pretty much) as if everywhere that the API docs mention \"T\" it actually says \"string\". So, you can only add strings to it, and if you use the indexer you don't need to cast to string, etc.</p>\n\n<p>To be honest, giving generics detailed coverage on an online forum is pretty much impossible. (In C# in Depth, I take nearly 50 pages talking about generics.) However, armed with the name of the feature, you should be in a much better position to find out more. The MSDN <a href=\"http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx\" rel=\"nofollow noreferrer\">\"Introduction to C# Generics\"</a> is probably a good starting point.</p>\n\n<p>Asking specific questions about generics on SO is likely to yield good results - I just don't think it can really be covered properly in one question/answer.</p>\n" }, { "answer_id": 155296, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "<p>That is the generic syntax for C#.</p>\n\n<p>The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.</p>\n\n<p>For example, the old way:</p>\n\n<pre><code>ArrayList foos = new Arraylist();\nfoos.Add(\"Test\");\n</code></pre>\n\n<p>worked by making ArrayList store a list of System.Objects (The base type for all things .NET).</p>\n\n<p>So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:</p>\n\n<pre><code>foos.Add(\"Test\" as System.Object);\nstring s = foos[1] as String.\n</code></pre>\n\n<p>This causes a performance penalty from the casting, and its also unsafe because I can do this:</p>\n\n<pre><code>ArrayList listOfStrings = new ArrayList();\nlistOfStrings.Add(1);\nlistOfStrings.Add(\"Test\");\n</code></pre>\n\n<p>This will compile just fine, even though I put an integer in listOfStrings.</p>\n\n<p>Generics changed all of this, now using Generics I can declare what Type my collection expects:</p>\n\n<pre><code>List&lt;int&gt; listOfIntegers = new List&lt;int&gt;();\nList&lt;String&gt; listOfStrings = new List&lt;String&gt;();\n\nlistOfIntegers.add(1);\n\n// Compile time error.\nlistOfIntegers.add(\"test\");\n</code></pre>\n\n<p>This provides compile-time type safety, as well as avoids expensive casting operations.</p>\n\n<p>The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic \"Add Two Things\" class.</p>\n\n<pre><code>public class Adder&lt;T&gt;\n{\n public T AddTwoThings(T t1, T t2)\n {\n return t1 + t2;\n }\n}\n\nAdder&lt;String&gt; stringAdder = new Adder&lt;String&gt;();\nConsole.Writeline(stringAdder.AddTwoThings(\"Test,\"123\"));\n\nAdder&lt;int&gt; intAdder = new Adder&lt;int&gt;();\nConsole.Writeline(intAdder.AddTwoThings(2,2));\n</code></pre>\n\n<p>For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.</p>\n" }, { "answer_id": 155298, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 1, "selected": false, "text": "<p>This is generics in action. A regular List stores items of type Object. This requires casting between types. This also will allow you to store any kind of item in one instance of a list. When you are iterating through items in that list you cannot be sure that they are all of a certain type (at least not without casting each item). For instance lets say you create a list like this:</p>\n\n<pre><code>List listOfStrings = new List();\n</code></pre>\n\n<p>Nothing prevents someone from doing something like this:</p>\n\n<pre><code>listOfStrings.add(6); //Not a string\n</code></pre>\n\n<p>A generic list would allow you to specify a strongly-typed list.</p>\n\n<pre><code>List&lt;string&gt; listOfStrings = new List&lt;string&gt;();\nlistOfStrings.add(\"my name\"); //OK\nlistofStrings.add(6); //Throws a compiler error\n</code></pre>\n\n<p>There is a more thorough examples on here <a href=\"http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx\" rel=\"nofollow noreferrer\">Generics</a></p>\n" }, { "answer_id": 155304, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 0, "selected": false, "text": "<p>&lt; > is for generics. In your specific example, it means that the List is a List of strings, not say a list of ints.</p>\n\n<p>Generics are used to allow a type to be, well, generic. It's used ALOT in Collections to allow them to take different types so that they can function much like a normal array and still catch invalid types being assigned at compile time. Basically it allows a class to say \"I need to be associated with some specific type T, but I don't want to hard code exactly what that type is, and let the user select it.\". A simple array for instance might look something like:</p>\n\n<pre><code>public class MyArray&lt;T&gt; {\n private T[] _list;\n\n public MyArray() : this.MyArray(10);\n public MyArray(int capacity)\n { _list = new T[capacity]; }\n\n T this[int index] {\n get { return _list[index]; }\n set { _list[index] = value; }\n }\n}\n</code></pre>\n\n<p>Here, we have a private list of type T that is accessed by using our class like a normal array. We don't care what type it is, it doesn't matter to our code. But anyone using the class could use it as, say <code>MyArray&lt;string&gt;</code> to create a list of strings, while someone else might use it as <code>MyArray&lt;bool&gt;</code> and create a list of flags.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22459/" ]
I have been learning about the basics of C# but haven't come across a good explanation of what this is: ``` var l = new List<string>(); ``` I don't know what the `<string>` is doing or if it's the `List` that is doing the magic. I have also seen objects been thrown within the `< >` tags. Can someone explain this to me with examples, please?
That is the generic syntax for C#. The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time. For example, the old way: ``` ArrayList foos = new Arraylist(); foos.Add("Test"); ``` worked by making ArrayList store a list of System.Objects (The base type for all things .NET). So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this: ``` foos.Add("Test" as System.Object); string s = foos[1] as String. ``` This causes a performance penalty from the casting, and its also unsafe because I can do this: ``` ArrayList listOfStrings = new ArrayList(); listOfStrings.Add(1); listOfStrings.Add("Test"); ``` This will compile just fine, even though I put an integer in listOfStrings. Generics changed all of this, now using Generics I can declare what Type my collection expects: ``` List<int> listOfIntegers = new List<int>(); List<String> listOfStrings = new List<String>(); listOfIntegers.add(1); // Compile time error. listOfIntegers.add("test"); ``` This provides compile-time type safety, as well as avoids expensive casting operations. The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class. ``` public class Adder<T> { public T AddTwoThings(T t1, T t2) { return t1 + t2; } } Adder<String> stringAdder = new Adder<String>(); Console.Writeline(stringAdder.AddTwoThings("Test,"123")); Adder<int> intAdder = new Adder<int>(); Console.Writeline(intAdder.AddTwoThings(2,2)); ``` For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.
155,279
<p>I have an AdvancedDataGrid that uses customer grouping of data. Not all of the groups will be at the same level in the hierarchy, and groups can contain both groups and members. We have a sort callback, but it's not being called except for groups at the leaf-most levels. See code below for an example -- expand all of the groups, then click the sort column on "date of birth" to get a reverse sort by date of birth. (Oddly, for some unfathomable reason, the first ascending sort works.)</p> <p>We're not getting called for any of the data that's grouped at the same level as a group member.</p> <p>How do I fix this?</p> <p>Thanks.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" &gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn; import mx.collections.HierarchicalData; import mx.utils.ObjectUtil; private var arrData : Array = [ { name: "User A", dob: "04/14/1980" }, { name: "User B", dob: "01/02/1975" }, { name: "Group A", children: [ { name: "User E", dob: "09/13/1972" }, { name: "User F", dob: "11/22/1993" } ] }, { name: "Group B", children: [ { name: "Group B1", children: [ { name: "User I", dob: "01/23/1984" }, { name: "User J", dob: "11/10/1948" } ] }, { name: "User G", dob: "04/09/1989" }, { name: "User H", dob: "06/20/1963" } ] }, { name: "User C", dob: "12/30/1977" }, { name: "User D", dob: "10/27/1968" } ]; private function date_sortCompareFunc(itemA:Object, itemB:Object):int { if ( itemA.hasOwnProperty("dob") &amp;&amp; itemB.hasOwnProperty("dob")) { var dateA:Date = new Date(Date.parse(itemA.dob)); var dateB:Date = new Date(Date.parse(itemB.dob)); return ObjectUtil.dateCompare(dateA, dateB); } else if ( itemA.hasOwnProperty("dob")) { return 1; } else if (itemB.hasOwnProperty("dob")) { return -1; } return ObjectUtil.stringCompare(itemA.name, itemB.name); } private function date_dataTipFunc(item:Object):String { if (item.hasOwnProperty("dob")) { return dateFormatter.format(item.dob); } return ""; } private function label_dob(item:Object, col:AdvancedDataGridColumn):String { var dob:String=""; if(item.hasOwnProperty("dob")) { dob=item.dob; } return dob; } ]]&gt; &lt;/mx:Script&gt; &lt;mx:DateFormatter id="dateFormatter" formatString="MMMM D, YYYY" /&gt; &lt;mx:AdvancedDataGrid id="adgTest" dataProvider="{new HierarchicalData(this.arrData)}" designViewDataType="tree" width="746" height="400"&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn headerText="Name" dataField="name"/&gt; &lt;mx:AdvancedDataGridColumn dataField="dob" headerText="Date of birth" labelFunction="label_dob" sortCompareFunction="date_sortCompareFunc" showDataTips="true" dataTipFunction="date_dataTipFunc" /&gt; &lt;/mx:columns&gt; &lt;/mx:AdvancedDataGrid&gt; &lt;/mx:Application&gt; </code></pre>
[ { "answer_id": 156283, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 0, "selected": false, "text": "<p>This has something to do with the logic of the SortCompareFunction.</p>\n\n<p>Put <code>dob:\"01/01/1970\"</code> for all the group nodes and the sort works as expected, is that correct?</p>\n" }, { "answer_id": 1406772, "author": "Invalid Character", "author_id": 9610, "author_profile": "https://Stackoverflow.com/users/9610", "pm_score": 2, "selected": false, "text": "<p>It seems as if the first row contains null data or an empty string, and the advanceddatagrid is set to use grouped data, then the sort function doesn't get called.</p>\n\n<p>it's a bit of a hack, yes, but if you can put in an unrealistic (say 1/1/1770), constant piece of data that you could insert at the database/file read/data input level then use the column labelFunction to render as null if the data matches that column, it should work, or at least the sort function will get called.</p>\n\n<pre><code> public function dateCellLabel(item:Object, column:AdvancedDataGridColumn):String\n {\n var date:String = item[column.dataField];\n\n if (date==\"1/1/1770\") \n return null; \n else\n return date;\n }\n</code></pre>\n\n<p>Sorry about answering this so late, but at least if somebody else tries to find the answer, they might see this.</p>\n" }, { "answer_id": 5328784, "author": "Darren Bishop", "author_id": 133330, "author_profile": "https://Stackoverflow.com/users/133330", "pm_score": 0, "selected": false, "text": "<p>I don't think the problem is to do with sorting grouped data with null or empty string values (which are perfectly valid values); the \ndocs clearly state the property represented by <code>dataField</code> must be a valid property on the dataProvider [item] i.e. it must exist, null or otherwise.</p>\n\n<p>While I give RaySir my vote, I don't quite agree that it's a hack, but rather you're normalizing your data, which I think is a perfectly fine presentation-layer thing to do.</p>\n\n<p>Here's is a re-worked example:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n layout=\"vertical\" \n verticalAlign=\"middle\" \n backgroundColor=\"white\" &gt;\n &lt;mx:Script&gt;\n &lt;![CDATA[\n import mx.collections.HierarchicalData;\n import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;\n import mx.utils.ObjectUtil;\n\n private var arrData : Array = [\n { name: \"User A\", dob: \"04/14/1980\" },\n { name: \"User B\", dob: \"01/02/1975\" },\n { name: \"Group A\", dob: null, children: [\n { name: \"User E\", dob: \"09/13/1972\" },\n { name: \"User F\", dob: \"11/22/1993\" }\n ]\n },\n { name: \"Group B\", dob: null, children: [\n { name: \"Group B1\", dob: null, children: [\n { name: \"User I\", dob: \"01/23/1984\" },\n { name: \"User J\", dob: \"11/10/1948\" }\n ]\n },\n { name: \"User G\", dob: \"04/09/1989\" },\n { name: \"User H\", dob: \"06/20/1963\" }\n ]\n },\n { name: \"User C\", dob: \"12/30/1977\" },\n { name: \"User D\", dob: \"10/27/1968\" }\n ];\n\n private function dob_sort(itemA:Object, itemB:Object):int {\n var dateA:Date = itemA.dob ? new Date(itemA.dob) : null;\n var dateB:Date = itemB.dob ? new Date(itemB.dob) : null;\n return ObjectUtil.dateCompare(dateA, dateB);\n }\n\n private function dob_dataTip(item:Object):String {\n if (!item.hasOwnProperty('children') &amp;&amp; item.hasOwnProperty(\"dob\")) {\n return dateFormatter.format(item.dob);\n }\n return null;\n }\n\n private function dob_label(item:Object, col:AdvancedDataGridColumn):String {\n if(!item.hasOwnProperty('children') &amp;&amp; item.hasOwnProperty(\"dob\")) {\n return item.dob;\n }\n return null;\n }\n ]]&gt;\n &lt;/mx:Script&gt;\n\n &lt;mx:DateFormatter id=\"dateFormatter\" formatString=\"MMMM D, YYYY\" /&gt;\n\n &lt;mx:AdvancedDataGrid id=\"adgTest\" dataProvider=\"{new HierarchicalData(arrData)}\" designViewDataType=\"tree\" width=\"746\" height=\"400\"&gt;\n &lt;mx:columns&gt;\n &lt;mx:AdvancedDataGridColumn headerText=\"Name\" dataField=\"name\"/&gt;\n &lt;mx:AdvancedDataGridColumn headerText=\"Date of birth\" dataField=\"dob\"\n labelFunction=\"dob_label\" \n dataTipFunction=\"dob_dataTip\"\n sortCompareFunction=\"dob_sort\"\n showDataTips=\"true\" /&gt;\n\n &lt;/mx:columns&gt;\n &lt;/mx:AdvancedDataGrid&gt;\n&lt;/mx:Application&gt;\n</code></pre>\n" }, { "answer_id": 19431345, "author": "dkropfuntucht", "author_id": 338899, "author_profile": "https://Stackoverflow.com/users/338899", "pm_score": 0, "selected": false, "text": "<p>While it doesn't appear to be the case in this example, a missing dataField on a column will prevent sort from happening. The systems are precisely as described, the sortCompareFunction is never called. </p>\n\n<p>If you have a custom column renderer that is pulling fields out of data on its own, it's easy to overlook filling in a dataField attribute. Everything will work fine, in that case, until you go to sort. The sortCompareFunction will not be called.</p>\n\n<p>Check by debuggging HierarchicalCollectionView.as, at line 1259 or so, in sortCanBeApplied.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22809/" ]
I have an AdvancedDataGrid that uses customer grouping of data. Not all of the groups will be at the same level in the hierarchy, and groups can contain both groups and members. We have a sort callback, but it's not being called except for groups at the leaf-most levels. See code below for an example -- expand all of the groups, then click the sort column on "date of birth" to get a reverse sort by date of birth. (Oddly, for some unfathomable reason, the first ascending sort works.) We're not getting called for any of the data that's grouped at the same level as a group member. How do I fix this? Thanks. ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" > <mx:Script> <![CDATA[ import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn; import mx.collections.HierarchicalData; import mx.utils.ObjectUtil; private var arrData : Array = [ { name: "User A", dob: "04/14/1980" }, { name: "User B", dob: "01/02/1975" }, { name: "Group A", children: [ { name: "User E", dob: "09/13/1972" }, { name: "User F", dob: "11/22/1993" } ] }, { name: "Group B", children: [ { name: "Group B1", children: [ { name: "User I", dob: "01/23/1984" }, { name: "User J", dob: "11/10/1948" } ] }, { name: "User G", dob: "04/09/1989" }, { name: "User H", dob: "06/20/1963" } ] }, { name: "User C", dob: "12/30/1977" }, { name: "User D", dob: "10/27/1968" } ]; private function date_sortCompareFunc(itemA:Object, itemB:Object):int { if ( itemA.hasOwnProperty("dob") && itemB.hasOwnProperty("dob")) { var dateA:Date = new Date(Date.parse(itemA.dob)); var dateB:Date = new Date(Date.parse(itemB.dob)); return ObjectUtil.dateCompare(dateA, dateB); } else if ( itemA.hasOwnProperty("dob")) { return 1; } else if (itemB.hasOwnProperty("dob")) { return -1; } return ObjectUtil.stringCompare(itemA.name, itemB.name); } private function date_dataTipFunc(item:Object):String { if (item.hasOwnProperty("dob")) { return dateFormatter.format(item.dob); } return ""; } private function label_dob(item:Object, col:AdvancedDataGridColumn):String { var dob:String=""; if(item.hasOwnProperty("dob")) { dob=item.dob; } return dob; } ]]> </mx:Script> <mx:DateFormatter id="dateFormatter" formatString="MMMM D, YYYY" /> <mx:AdvancedDataGrid id="adgTest" dataProvider="{new HierarchicalData(this.arrData)}" designViewDataType="tree" width="746" height="400"> <mx:columns> <mx:AdvancedDataGridColumn headerText="Name" dataField="name"/> <mx:AdvancedDataGridColumn dataField="dob" headerText="Date of birth" labelFunction="label_dob" sortCompareFunction="date_sortCompareFunc" showDataTips="true" dataTipFunction="date_dataTipFunc" /> </mx:columns> </mx:AdvancedDataGrid> </mx:Application> ```
It seems as if the first row contains null data or an empty string, and the advanceddatagrid is set to use grouped data, then the sort function doesn't get called. it's a bit of a hack, yes, but if you can put in an unrealistic (say 1/1/1770), constant piece of data that you could insert at the database/file read/data input level then use the column labelFunction to render as null if the data matches that column, it should work, or at least the sort function will get called. ``` public function dateCellLabel(item:Object, column:AdvancedDataGridColumn):String { var date:String = item[column.dataField]; if (date=="1/1/1770") return null; else return date; } ``` Sorry about answering this so late, but at least if somebody else tries to find the answer, they might see this.
155,291
<p>I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.</p> <p>I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.</p>
[ { "answer_id": 155301, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 9, "selected": false, "text": "<p><code>READONLY</code> doesn't work on checkboxes as it prevents you from editing a field's <em>value</em>, but with a checkbox you're actually editing the field's <em>state</em> (on || off)</p>\n\n<p>From <a href=\"http://www.faqs.org/docs/htmltut/forms/_INPUT_DISABLED.html\" rel=\"noreferrer\">faqs.org</a>:</p>\n\n<blockquote>\n <p>It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field.</p>\n</blockquote>\n\n<p>If you don't want to use <code>disabled</code> but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g.</p>\n\n<pre><code>// user allowed change\nif($user_allowed_edit)\n{\n echo '&lt;input type=\"checkbox\" name=\"my_check\"&gt; Check value';\n}\nelse\n{\n // Not allowed change - submit value..\n echo '&lt;input type=\"hidden\" name=\"my_check\" value=\"1\" /&gt;';\n // .. and show user the value being submitted\n echo '&lt;input type=\"checkbox\" disabled readonly&gt; Check value';\n}\n</code></pre>\n" }, { "answer_id": 155305, "author": "Mayowa", "author_id": 18593, "author_profile": "https://Stackoverflow.com/users/18593", "pm_score": -1, "selected": false, "text": "<p>No, but you might be able to use javascript events to achieve something similar</p>\n" }, { "answer_id": 155313, "author": "Walden Leverich", "author_id": 2673770, "author_profile": "https://Stackoverflow.com/users/2673770", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I just don't want the client to be able to change them under certain circumstances.</p>\n</blockquote>\n\n<p>READONLY itself won't work. You may be able to do something funky w/CSS but we usually just make them disabled. </p>\n\n<p>WARNING: If they're posted back then the client can change them, period. You can't rely on readonly to prevent a user from changing something. The could always use fiddler or just chane the html w/firebug or some such thing.</p>\n" }, { "answer_id": 155324, "author": "powtac", "author_id": 22470, "author_profile": "https://Stackoverflow.com/users/22470", "pm_score": 9, "selected": false, "text": "<p>This is a checkbox you can't change: </p>\n\n<pre><code>&lt;input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\"&gt;\n</code></pre>\n\n<p>Just add <code>disabled=\"disabled\"</code> as an attribute.</p>\n\n<p><br/>\n<strong>Edit to address the comments:</strong></p>\n\n<p>If you want the data to be posted back, than a simple solutions is to apply the same name to a hidden input:</p>\n\n<pre><code>&lt;input name=\"myvalue\" type=\"checkbox\" disabled=\"disabled\" checked=\"checked\"/&gt;\n&lt;input name=\"myvalue\" type=\"hidden\" value=\"true\"/&gt;\n</code></pre>\n\n<p>This way, when the checkbox is set to 'disabled', it only serves the purpose of a visual representation of the data, instead of actually being 'linked' to the data. In the post back, the value of the hidden input is being sent when the checkbox is disabled.</p>\n" }, { "answer_id": 155337, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": false, "text": "<p>This presents a bit of a usability issue.</p>\n\n<p>If you want to display a checkbox, but not let it be interacted with, why even a checkbox then? </p>\n\n<p>However, my approach would be to use disabled (The user expects a disabled checkbox to not be editable, instead of using JS to make an enabled one not work), and add a form submit handler using javascript that enables checkboxes right before the form is submitted. This way you you do get your values posted.</p>\n\n<p>ie something like this:</p>\n\n<pre><code>var form = document.getElementById('yourform');\nform.onSubmit = function () \n{ \n var formElems = document.getElementsByTagName('INPUT');\n for (var i = 0; i , formElems.length; i++)\n { \n if (formElems[i].type == 'checkbox')\n { \n formElems[i].disabled = false;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 155347, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": -1, "selected": false, "text": "<p>You could always use a small image that looks like a check box.</p>\n" }, { "answer_id": 155349, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 6, "selected": false, "text": "<pre><code>&lt;input type=\"checkbox\" onclick=\"this.checked=!this.checked;\"&gt;\n</code></pre>\n\n<p>But you absolutely MUST validate the data on the server to ensure it hasn't been changed.</p>\n" }, { "answer_id": 734223, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>When posting an HTML checkbox to the server, it has a string value of 'on' or ''. </p>\n\n<p>Readonly does not stop the user editing the checkbox, and disabled stops the value being posted back.<br>\nOne way around this is to have a hidden element to store the actual value and the displayed checkbox is a dummy which is disabled. This way the checkbox state is persisted between posts. </p>\n\n<p>Here is a function to do this. It uses a string of 'T' or 'F' and you can change this any way you like. This has been used in an ASP page using server side VB script.</p>\n\n<pre><code>public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)\n\n dim strThisCheckedValue\n\n if (i_strChecked_TorF = \"T\") then\n strThisCheckedValue = \" checked \"\n i_strChecked_TorF = \"on\"\n else\n strThisCheckedValue = \"\"\n i_strChecked_TorF = \"\"\n end if\n\n MakeDummyReadonlyCheckbox = \"&lt;input type='hidden' id='\" &amp; i_strName &amp; \"' name='\" &amp; i_strName &amp; \"' \" &amp; _\n \"value='\" &amp; i_strChecked_TorF &amp; \"'&gt;\" &amp; _\n \"&lt;input type='checkbox' disabled id='\" &amp; i_strName &amp; \"Dummy' name='\" &amp; i_strName &amp; \"Dummy' \" &amp; _\n strThisCheckedValue &amp; \"&gt;\" \nend function\n\npublic function GetCheckbox(i_objCheckbox)\n\n select case trim(i_objCheckbox)\n\n case \"\"\n GetCheckbox = \"F\"\n\n case else\n GetCheckbox = \"T\"\n\n end select\n\nend function\n</code></pre>\n\n<p>At the top of an ASP page you can pickup the persisted value...</p>\n\n<pre><code>strDataValue = GetCheckbox(Request.Form(\"chkTest\"))\n</code></pre>\n\n<p>and when you want to output your checkbox you can do this...</p>\n\n<pre><code>response.write MakeDummyReadonlyCheckbox(\"chkTest\", strDataValue)\n</code></pre>\n\n<p>I have tested this and it works just fine. It also does not rely upon JavaScript.</p>\n" }, { "answer_id": 1273173, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;input name=\"isActive\" id=\"isActive\" type=\"checkbox\" value=\"1\" checked=\"checked\" onclick=\"return false\"/&gt;\n</code></pre>\n" }, { "answer_id": 1480542, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 0, "selected": false, "text": "<p>If you need the checkbox to be submitted with the form but effectively read-only to the user, I recommend setting them to disabled and using javascript to re-enable them when the form is submitted.</p>\n\n<p>This is for two reasons. First and most important, your users benefit from seeing a visible difference between checkboxes they can change and checkboxes which are read-only. Disabled does this.</p>\n\n<p>Second reason is that the disabled state is built into the browser so you need less code to execute when the user clicks on something. This is probably more of a personal preference than anything else. You'll still need some javascript to un-disable these when submitting the form.</p>\n\n<p>It seems easier to me to use some javascript when the form is submitted to un-disable the checkboxes than to use a hidden input to carry the value.</p>\n" }, { "answer_id": 2775421, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": -1, "selected": false, "text": "<p>My solution is actually the opposite of FlySwat's solution, but I'm not sure if it will work for your situation. I have a group of checkboxes, and each has an onClick handler that submits the form (they're used for changing filter settings for a table). I don't want to allow multiple clicks, since subsequent clicks after the first are ignored. So I disable all checkboxes after the first click, and after submitting the form:</p>\n\n<p><code>onclick=\"document.forms['form1'].submit(); $('#filters input').each(function() {this.disabled = true});\"</code></p>\n\n<p>The checkboxes are in a span element with an ID of \"filters\" - the second part of the code is a jQuery statement that iterates through the checkboxes and disables each one. This way, the checkbox values are still submitted via the form (since the form was submitted before disabling them), and it prevents the user from changing them until the page reloads.</p>\n" }, { "answer_id": 3027466, "author": "Jan", "author_id": 51795, "author_profile": "https://Stackoverflow.com/users/51795", "pm_score": 5, "selected": false, "text": "<pre><code>&lt;input type=\"checkbox\" readonly=\"readonly\" name=\"...\" /&gt;\n</code></pre>\n\n<p>with jquery:</p>\n\n<pre><code>$(':checkbox[readonly]').click(function(){\n return false;\n });\n</code></pre>\n\n<p>it still might be a good idea to give some visual hint (css, text,...), that the control won't accept inputs.</p>\n" }, { "answer_id": 3292768, "author": "Sandman", "author_id": 397109, "author_profile": "https://Stackoverflow.com/users/397109", "pm_score": 3, "selected": false, "text": "<pre><code>onclick=\"javascript: return false;\"\n</code></pre>\n" }, { "answer_id": 4069837, "author": "user493687", "author_id": 493687, "author_profile": "https://Stackoverflow.com/users/493687", "pm_score": -1, "selected": false, "text": "<p>Simplest (in my view):</p>\n\n<pre><code>onclick=\"javascript:{this.checked = this.defaultChecked;}\"\n</code></pre>\n" }, { "answer_id": 4126451, "author": "Tim", "author_id": 500973, "author_profile": "https://Stackoverflow.com/users/500973", "pm_score": 0, "selected": false, "text": "<p>The main reason people would like a read-only check-box and (as well) a read-only radio-group is so that information that cannot be changed can be presented back to the user in the form it was entered. </p>\n\n<p>OK disabled will do this -- unfortunately disabled controls are not keyboard navigable and therefore fall foul of all accessibility legislation. This is the BIGGEST hangup in HTML that I know of.</p>\n" }, { "answer_id": 5437656, "author": "Jason", "author_id": 677379, "author_profile": "https://Stackoverflow.com/users/677379", "pm_score": 0, "selected": false, "text": "<p>Contributing very very late...but anyway. On page load, use jquery to disable all checkboxes except the currently selected one. Then set the currently selected one as read only so it has a similar look as the disabled ones. User cannot change the value, and the selected value still submits.</p>\n" }, { "answer_id": 6550080, "author": "fdaines", "author_id": 661143, "author_profile": "https://Stackoverflow.com/users/661143", "pm_score": -1, "selected": false, "text": "<p>In old HTML you can use</p>\n\n<pre><code>&lt;input type=\"checkbox\" disabled checked&gt;text\n</code></pre>\n\n<p>but actually is not recommended to use just simply old HTML, now you should use XHTML.</p>\n\n<p>In well formed XHTML you have to use</p>\n\n<pre><code>&lt;input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\" /&gt;text &lt;!-- if yu have a checked box--&gt;\n&lt;input type=\"checkbox\" disabled=\"disabled\" /&gt;text &lt;!-- if you have a unchecked box --&gt;\n</code></pre>\n\n<p>well formed XHTML requires a XML form, thats the reason to use disabled=\"disabled\" instead of simply use disabled.</p>\n" }, { "answer_id": 6905050, "author": "Yanni", "author_id": 689782, "author_profile": "https://Stackoverflow.com/users/689782", "pm_score": 9, "selected": false, "text": "<p>you can use this:</p>\n\n<pre><code>&lt;input type=\"checkbox\" onclick=\"return false;\"/&gt;\n</code></pre>\n\n<p>This works because returning false from the click event stops the chain of execution continuing.</p>\n" }, { "answer_id": 8146615, "author": "kazinix", "author_id": 724689, "author_profile": "https://Stackoverflow.com/users/724689", "pm_score": -1, "selected": false, "text": "<p>When submitting the form, we actually pass the value of the checkbox, not the state (checked/unchecked). Readonly attribute prevents us to edit the value, but not the state. If you want to have a read-only field that will represent the value you want to submit, use readonly text.</p>\n" }, { "answer_id": 9172619, "author": "Devner", "author_id": 212889, "author_profile": "https://Stackoverflow.com/users/212889", "pm_score": -1, "selected": false, "text": "<p>Try this to make the checkbox read-only and yet disallow user from checking. This will let you POST the checkbox value. You need to select the default state of the checkbox as Checked in order to do so.</p>\n\n<pre><code>&lt;input type=\"checkbox\" readonly=\"readonly\" onclick=\"this.checked =! this.checked;\"&gt;\n</code></pre>\n\n<p>If you want the above functionality + dont want to receive the checkbox data, try the below:</p>\n\n<pre><code>&lt;input type=\"checkbox\" readonly=\"readonly\" disabled=\"disabled\" onclick=\"this.checked =! this.checked;\"&gt;\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 10327995, "author": "Rinto George", "author_id": 510754, "author_profile": "https://Stackoverflow.com/users/510754", "pm_score": 3, "selected": false, "text": "<p><code>&lt;input type=\"checkbox\" onclick=\"return false\" /&gt;</code> will work for you , I am using this </p>\n" }, { "answer_id": 10377324, "author": "Kamalam", "author_id": 1235160, "author_profile": "https://Stackoverflow.com/users/1235160", "pm_score": -1, "selected": false, "text": "<p>The following works if you know that the checkbox is always checked:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input type=&quot;checkbox&quot; name=&quot;Name&quot; checked onchange='this.checked = true;'&gt;\n</code></pre>\n" }, { "answer_id": 10832156, "author": "Osama Javed", "author_id": 832000, "author_profile": "https://Stackoverflow.com/users/832000", "pm_score": 5, "selected": false, "text": "<p>I used this to achieve the results:</p>\n\n<pre><code>&lt;input type=checkbox onclick=\"return false;\" onkeydown=\"return false;\" /&gt;\n</code></pre>\n" }, { "answer_id": 11385229, "author": "Ryan", "author_id": 1510358, "author_profile": "https://Stackoverflow.com/users/1510358", "pm_score": -1, "selected": false, "text": "<p>What none of you are thinking about here is that you are all using JavaScript, which can be very easily bypassed by any user.</p>\n\n<p>Simply disabling it disables all JQuery/Return False statements.</p>\n\n<p>Your only option for readonly checkboxes is server side.</p>\n\n<p>Display them, let them change them but don't accept the new post data from them.</p>\n" }, { "answer_id": 11678624, "author": "sksallaj", "author_id": 1449587, "author_profile": "https://Stackoverflow.com/users/1449587", "pm_score": 2, "selected": false, "text": "<p>Some of the answers on here seem a bit roundabout, but here's a small hack.</p>\n\n<pre><code>&lt;form id=\"aform\" name=\"aform\" method=\"POST\"&gt;\n &lt;input name=\"chkBox_1\" type=\"checkbox\" checked value=\"1\" disabled=\"disabled\" /&gt;\n &lt;input id=\"submitBttn\" type=\"button\" value=\"Submit\" onClick='return submitPage();'&gt;\n&lt;/form&gt;​\n</code></pre>\n\n<p>then in jquery you can either choose one of two options:</p>\n\n<pre><code>$(document).ready(function(){\n //first option, you don't need the disabled attribute, this will prevent\n //the user from changing the checkbox values\n $(\"input[name^='chkBox_1']\").click(function(e){\n e.preventDefault();\n });\n\n //second option, keep the disabled attribute, and disable it upon submit\n $(\"#submitBttn\").click(function(){\n $(\"input[name^='chkBox_1']\").attr(\"disabled\",false);\n $(\"#aform\").submit();\n });\n\n});\n</code></pre>\n\n<p>​</p>\n\n<p>demo:\n<a href=\"http://jsfiddle.net/5WFYt/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/5WFYt/</a></p>\n" }, { "answer_id": 12971018, "author": "summsel", "author_id": 1758805, "author_profile": "https://Stackoverflow.com/users/1758805", "pm_score": 6, "selected": false, "text": "<p>another \"simple solution\":</p>\n\n<pre><code>&lt;!-- field that holds the data --&gt;\n&lt;input type=\"hidden\" name=\"my_name\" value=\"1\" /&gt; \n&lt;!-- visual dummy for the user --&gt;\n&lt;input type=\"checkbox\" name=\"my_name_visual_dummy\" value=\"1\" checked=\"checked\" disabled=\"disabled\" /&gt;\n</code></pre>\n\n<blockquote>\n <p>disabled=\"disabled\" / disabled=true</p>\n</blockquote>\n" }, { "answer_id": 13650019, "author": "Derrick", "author_id": 561759, "author_profile": "https://Stackoverflow.com/users/561759", "pm_score": 2, "selected": false, "text": "<p>Building on the above answers, if using jQuery, this may be an good solution for all inputs:</p>\n\n<pre><code>&lt;script&gt;\n $(function () {\n $('.readonly input').attr('readonly', 'readonly');\n $('.readonly textarea').attr('readonly', 'readonly');\n $('.readonly input:checkbox').click(function(){return false;});\n $('.readonly input:checkbox').keydown(function () { return false; });\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>I'm using this with Asp.Net MVC to set some form elements read only. The above works for text and check boxes by setting any parent container as .readonly such as the following scenarios:</p>\n\n<pre><code>&lt;div class=\"editor-field readonly\"&gt;\n &lt;input id=\"Date\" name=\"Date\" type=\"datetime\" value=\"11/29/2012 4:01:06 PM\" /&gt;\n&lt;/div&gt;\n&lt;fieldset class=\"flags-editor readonly\"&gt;\n &lt;input checked=\"checked\" class=\"flags-editor\" id=\"Flag1\" name=\"Flags\" type=\"checkbox\" value=\"Flag1\" /&gt;\n&lt;/fieldset&gt;\n</code></pre>\n" }, { "answer_id": 14588872, "author": "Richard Maxwell", "author_id": 902960, "author_profile": "https://Stackoverflow.com/users/902960", "pm_score": -1, "selected": false, "text": "<p>If anyone else is using MVC and an editor template, this is how I control displaying a read only property (I use a custom attribute to get the value in the if statement)</p>\n\n<pre><code>@if (true)\n{\n @Html.HiddenFor(m =&gt; m)\n @(ViewData.Model ? Html.Raw(\"Yes\") : Html.Raw(\"No\"))\n} \nelse\n{ \n @Html.CheckBoxFor(m =&gt; m)\n}\n</code></pre>\n" }, { "answer_id": 16693321, "author": "jortsc", "author_id": 1913266, "author_profile": "https://Stackoverflow.com/users/1913266", "pm_score": 0, "selected": false, "text": "<p>Or just:</p>\n\n<pre><code>$('your selector').click(function(evt){evt.preventDefault()});\n</code></pre>\n" }, { "answer_id": 17796857, "author": "frag", "author_id": 451232, "author_profile": "https://Stackoverflow.com/users/451232", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;input type=\"radio\" name=\"alwaysOn\" onchange=\"this.checked=true\" checked=\"checked\"&gt;\n&lt;input type=\"radio\" name=\"alwaysOff\" onchange=\"this.checked=false\" &gt;\n</code></pre>\n" }, { "answer_id": 22821064, "author": "Gotham's Reckoning", "author_id": 2673410, "author_profile": "https://Stackoverflow.com/users/2673410", "pm_score": 4, "selected": false, "text": "<p>I happened to notice the solution given below. In found it my research for the same issue. \nI don't who had posted it but it wasn't made by me. It uses jQuery:</p>\n\n<pre><code>$(document).ready(function() {\n $(\":checkbox\").bind(\"click\", false);\n});\n</code></pre>\n\n<p>This would make the checkboxes read only which would be helpful for showing readonly data to the client.</p>\n" }, { "answer_id": 23885043, "author": "Md Rahman", "author_id": 2791039, "author_profile": "https://Stackoverflow.com/users/2791039", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;input name=\"testName\" type=\"checkbox\" disabled&gt;\n</code></pre>\n" }, { "answer_id": 24750387, "author": "brad", "author_id": 1823390, "author_profile": "https://Stackoverflow.com/users/1823390", "pm_score": -1, "selected": false, "text": "<p>Why not cover the input with a blank div on top.</p>\n\n<pre><code>&lt;div id='checkbox_wrap'&gt;\n &lt;div class='click_block'&gt;&lt;/div&gt;\n &lt;input type='checkbox' /&gt; \n&lt;/div&gt;\n</code></pre>\n\n<p>then something like this with CSS</p>\n\n<pre><code> #checkbox_wrap{\n height:10px;\n width:10px;\n }\n .click_block{\n height: 10px;\n width: 10px;\n position: absolute;\n z-index: 100;\n}\n</code></pre>\n" }, { "answer_id": 26019627, "author": "bowlturner", "author_id": 3825871, "author_profile": "https://Stackoverflow.com/users/3825871", "pm_score": 1, "selected": false, "text": "<p>Very late to the party but I found an answer for MVC (5) \nI disabled the CheckBox and added a HiddenFor BEFORE the checkbox, so when it is posting if finds the Hidden field first and uses that value. This does work.</p>\n\n<pre><code> &lt;div class=\"form-group\"&gt;\n @Html.LabelFor(model =&gt; model.Carrier.Exists, new { @class = \"control-label col-md-2\" })\n &lt;div class=\"col-md-10\"&gt;\n @Html.HiddenFor(model =&gt; model.Carrier.Exists)\n @Html.CheckBoxFor(model =&gt; model.Carrier.Exists, new { @disabled = \"disabled\" })\n @Html.ValidationMessageFor(model =&gt; model.Carrier.Exists)\n &lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 27324260, "author": "David N. Jafferian", "author_id": 1590397, "author_profile": "https://Stackoverflow.com/users/1590397", "pm_score": 2, "selected": false, "text": "<p>I would have commented on ConroyP's answer, but that requires 50 reputation which I don't have. I do have enough reputation to post another answer. Sorry.</p>\n\n<p>The problem with ConroyP's answer is that the checkbox is rendered unchangeable by not even including it on the page. Although Electrons_Ahoy does not stipulate as much, the best answer would be one in which the unchangeable checkbox would look similar, if not the same as, the changeable checkbox, as is the case when the \"disabled\" attribute is applied. A solution which addresses the two reasons Electrons_Ahoy gives for not wanting to use the \"disabled\" attribute would <em>not</em> necessarily be invalid because it utilized the \"disabled\" attribute.</p>\n\n<p>Assume two boolean variables, $checked and $disabled :</p>\n\n<pre><code>if ($checked &amp;&amp; $disabled)\n echo '&lt;input type=\"hidden\" name=\"my_name\" value=\"1\" /&gt;';\necho '&lt;input type=\"checkbox\" name=\"my_name\" value=\"1\" ',\n $checked ? 'checked=\"checked\" ' : '',\n $disabled ? 'disabled=\"disabled\" ' : '', '/&gt;';\n</code></pre>\n\n<p>The checkbox is displayed as checked if $checked is true. The checkbox is displayed as unchecked if $checked is false. The user can change the state of the checkbox if and only if $disabled is false. The \"my_name\" parameter is not posted when the checkbox is unchecked, by the user or not. The \"my_name=1\" parameter is posted when the checkbox is checked, by the user or not. I believe this is what Electrons_Ahoy was looking for.</p>\n" }, { "answer_id": 28844799, "author": "NL3294", "author_id": 1270756, "author_profile": "https://Stackoverflow.com/users/1270756", "pm_score": 2, "selected": false, "text": "<p>I know that \"disabled\" isn't an acceptable answer, since the op wants it to post. However, you're always going to have to validate values on the server side EVEN if you have the readonly option set. This is because you can't stop a malicious user from posting values using the readonly attribute.</p>\n\n<p>I suggest storing the original value (server side), and setting it to disabled. Then, when they submit the form, ignore any values posted and take the original values that you stored. </p>\n\n<p>It'll look and behave like it's a readonly value. And it handles (ignores) posts from malicious users. You're killing 2 birds with one stone.</p>\n" }, { "answer_id": 48861270, "author": "Kavi", "author_id": 2771583, "author_profile": "https://Stackoverflow.com/users/2771583", "pm_score": -1, "selected": false, "text": "<p>Latest jQuery has this feature</p>\n\n<pre><code>$(\"#txtname\").prop('readonly', false);\n</code></pre>\n" }, { "answer_id": 52288861, "author": "Timo Huovinen", "author_id": 175071, "author_profile": "https://Stackoverflow.com/users/175071", "pm_score": 2, "selected": false, "text": "<p>No, input checkboxes can't be readonly.</p>\n\n<p>But you can make them readonly with javascript!</p>\n\n<p>Add this code anywhere at any time to make checkboxes readonly work as assumed, by preventing the user from modifying it in any way.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>jQuery(document).on('click', function(e){\r\n // check for type, avoid selecting the element for performance\r\n if(e.target.type == 'checkbox') {\r\n var el = jQuery(e.target);\r\n if(el.prop('readonly')) {\r\n // prevent it from changing state\r\n e.preventDefault();\r\n }\r\n }\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input[type=checkbox][readonly] {\r\n cursor: not-allowed;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;label&gt;&lt;input type=\"checkbox\" checked readonly&gt; I'm readonly!&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You can add this script at any time after jQuery has loaded.</p>\n\n<p>It will work for dynamically added elements.</p>\n\n<p>It works by picking up the click event (that happens before the change event) on any element on the page, it then checks if this element is a readonly checkbox, and if it is, then it blocks the change.</p>\n\n<p>There are so many ifs to make it not affect the performance of the page.</p>\n" }, { "answer_id": 53953323, "author": "Nirbhay Rana", "author_id": 5358054, "author_profile": "https://Stackoverflow.com/users/5358054", "pm_score": 0, "selected": false, "text": "<p>Just use simple disabled tag like this below.</p>\n\n<pre><code>&lt;input type=\"checkbox\" name=\"email\" disabled&gt;\n</code></pre>\n" }, { "answer_id": 54182054, "author": "Daniel Ribeiro", "author_id": 2175874, "author_profile": "https://Stackoverflow.com/users/2175874", "pm_score": 2, "selected": false, "text": "<p>If you want ALL your checkboxes to be \"locked\" so user can't change the \"checked\" state if \"readonly\" attibute is present, then you can use jQuery:</p>\n\n<pre><code>$(':checkbox').click(function () {\n if (typeof ($(this).attr('readonly')) != \"undefined\") {\n return false;\n }\n});\n</code></pre>\n\n<p>Cool thing about this code is that it allows you to change the \"readonly\" attribute all over your code without having to rebind every checkbox.</p>\n\n<p>It works for radio buttons as well.</p>\n" }, { "answer_id": 55009355, "author": "Qwertiy", "author_id": 4928642, "author_profile": "https://Stackoverflow.com/users/4928642", "pm_score": 3, "selected": false, "text": "<p>If you want them to be submitted to the server with form but be not interacive for user, you can use <code>pointer-events: none</code> in css (<a href=\"https://caniuse.com/#feat=pointer-events\" rel=\"noreferrer\">works in all modern browsers except IE10- and Opera 12-</a>) and set tab-index to <code>-1</code> to prevent changing via keyboard. Also note that you can't use <code>label</code> tag as click on it will change the state anyway.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input[type=\"checkbox\"][readonly] {\r\n pointer-events: none !important;\r\n}\r\n\r\ntd {\r\n min-width: 5em;\r\n text-align: center;\r\n}\r\n\r\ntd:last-child {\r\n text-align: left;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;table&gt;\r\n &lt;tr&gt;\r\n &lt;th&gt;usual\r\n &lt;th&gt;readonly\r\n &lt;th&gt;disabled\r\n &lt;/tr&gt;&lt;tr&gt;\r\n &lt;td&gt;&lt;input type=checkbox /&gt;\r\n &lt;td&gt;&lt;input type=checkbox readonly tabindex=-1 /&gt;\r\n &lt;td&gt;&lt;input type=checkbox disabled /&gt;\r\n &lt;td&gt;works\r\n &lt;/tr&gt;&lt;tr&gt;\r\n &lt;td&gt;&lt;input type=checkbox checked /&gt;\r\n &lt;td&gt;&lt;input type=checkbox readonly checked tabindex=-1 /&gt;\r\n &lt;td&gt;&lt;input type=checkbox disabled checked /&gt;\r\n &lt;td&gt;also works\r\n &lt;/tr&gt;&lt;tr&gt;\r\n &lt;td&gt;&lt;label&gt;&lt;input type=checkbox checked /&gt;&lt;/label&gt;\r\n &lt;td&gt;&lt;label&gt;&lt;input type=checkbox readonly checked tabindex=-1 /&gt;&lt;/label&gt;\r\n &lt;td&gt;&lt;label&gt;&lt;input type=checkbox disabled checked /&gt;&lt;/label&gt;\r\n &lt;td&gt;broken - don't use label tag\r\n &lt;/tr&gt;\r\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 56304217, "author": "gordie", "author_id": 782013, "author_profile": "https://Stackoverflow.com/users/782013", "pm_score": 5, "selected": false, "text": "<p>I would use the readonly attribute</p>\n\n<pre><code>&lt;input type=\"checkbox\" readonly&gt;\n</code></pre>\n\n<p>Then use CSS to disable interactions:</p>\n\n<pre><code>input[type='checkbox'][readonly]{\n pointer-events: none;\n}\n</code></pre>\n\n<p>Note that using the pseudo-class :read-only doesn't work here.</p>\n\n<pre><code>input[type='checkbox']:read-only{ /*not working*/\n pointer-events: none;\n}\n</code></pre>\n" }, { "answer_id": 56322578, "author": "Patanjali", "author_id": 4188092, "author_profile": "https://Stackoverflow.com/users/4188092", "pm_score": 5, "selected": false, "text": "<p>Belated answer, but most answers seem to over complicate it.</p>\n\n<p>As I understand it, the OP was basically wanting:</p>\n\n<ol>\n<li>Readonly checkbox to show status.</li>\n<li>Value returned with form.</li>\n</ol>\n\n<p>It should be noted that:</p>\n\n<ol>\n<li>The OP preferred not to use the <code>disabled</code> attribute, because they 'want the checked check boxes to be submitted with the rest of the form'.</li>\n<li>Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked.</li>\n<li>A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it.</li>\n<li>The value of a checkbox is not limited to indicating its status, such as <code>yes</code> or <code>false</code>, but can be any text.</li>\n</ol>\n\n<p>Therefore, since the <code>readonly</code> attribute does not work, the best solution, requiring no javascript, is:</p>\n\n<ol>\n<li>A disabled checkbox, with no name or value.</li>\n<li>If the checkbox is to be displayed as checked, a hidden field with the name and value as stored on the server.</li>\n</ol>\n\n<p>So for a checked checkbox:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"checkbox\" checked=\"checked\" disabled=\"disabled\" /&gt;\r\n&lt;input type=\"hidden\" name=\"fieldname\" value=\"fieldvalue\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For an unchecked checkbox:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"checkbox\" disabled=\"disabled\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as <code>Status: none</code> or <code>Status: implemented</code>, but including the hidden input above when the latter is used, such as:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;Status: Implemented&lt;input type=\"hidden\" name=\"status\" value=\"implemented\" /&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57916318, "author": "little_birdie", "author_id": 2945815, "author_profile": "https://Stackoverflow.com/users/2945815", "pm_score": 4, "selected": false, "text": "<p><strong>Most of the current answers have one or more of these problems:</strong></p>\n\n<ol>\n<li>Only check for mouse not keyboard.</li>\n<li>Check only on page load.</li>\n<li>Hook the ever-popular change or submit events which won't always work out if something else has them hooked.</li>\n<li>Require a hidden input or other special elements/attributes that you have to undo in order to re-enable the checkbox using javascript.</li>\n</ol>\n\n<p><strong>The following is simple and has none of those problems.</strong></p>\n\n<pre><code>$('input[type=\"checkbox\"]').on('click keyup keypress keydown', function (event) {\n if($(this).is('[readonly]')) { return false; }\n});\n</code></pre>\n\n<p>If the checkbox is readonly, it won't change. If it's not, it will. It does use jquery, but you're probably using that already...</p>\n\n<p><strong>It works.</strong></p>\n" }, { "answer_id": 65436265, "author": "Tayyeb", "author_id": 9950751, "author_profile": "https://Stackoverflow.com/users/9950751", "pm_score": -1, "selected": false, "text": "<p>@(Model.IsEnabled)\nUse this condition for dynamically check and uncheck and set readonly if check box is already checked.</p>\n<pre><code> &lt;input id=&quot;abc&quot; name=&quot;abc&quot; type=&quot;checkbox&quot; @(Model.IsEnabled ? &quot;checked=checked onclick=this.checked=!this.checked;&quot; : string.Empty) &gt;\n</code></pre>\n" }, { "answer_id": 66783703, "author": "groovyDynamics", "author_id": 6493171, "author_profile": "https://Stackoverflow.com/users/6493171", "pm_score": 2, "selected": false, "text": "<p><code>readonly</code> does not work with <code>&lt;input type='checkbox'&gt;</code></p>\n<p>So, if you need to submit values from disabled checkboxes in a form, you can use jQuery:</p>\n<pre><code>$('form').submit(function(e) {\n $('input[type=&quot;checkbox&quot;]:disabled').each(function(e) {\n $(this).removeAttr('disabled');\n })\n});\n</code></pre>\n<p>This way the disabled attributes are removed from the elements when submitting the form.</p>\n" }, { "answer_id": 71119242, "author": "vincent salomon", "author_id": 18183749, "author_profile": "https://Stackoverflow.com/users/18183749", "pm_score": 0, "selected": false, "text": "<p>Extract from <a href=\"https://stackoverflow.com/a/71086058/18183749\">https://stackoverflow.com/a/71086058/18183749</a></p>\n<blockquote>\n<p>If you can't use the 'disabled' attribut (as it erases the value's\ninput at POST), and noticed that html attribut 'readonly' works only\non textarea and some input(text, password, search, as far I've seen),\nand finally, if you don't want to bother with duplicating all your\nselect, checkbox and radio with hidden input logics, you might find\nthe following function or any of his inner logics to your liking :</p>\n</blockquote>\n<pre><code> addReadOnlyToFormElements = function (idElement) {\n \n // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items\n $('#' + idElement + ' input[type=&quot;checkbox&quot;]:not(:checked)').prop('disabled',true); \n \n // and, on the selected ones, to disable mouse/keyoard events and mimic readOnly appearance\n $('#' + idElement + ' input[type=&quot;checkbox&quot;]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');\n }\n</code></pre>\n<p>And there's nothing easier than to remove these readonly</p>\n<pre><code>removeReadOnlyFromFormElements = function (idElement) {\n\n // Remove the disabled attribut on non-selected\n $('#' + idElement + ' input[type=&quot;checkbox&quot;]:not(:checked)').prop('disabled',false);\n\n // Restore mouse/keyboard events and remove readOnly appearance on selected ones\n $('#' + idElement + ' input[type=&quot;checkbox&quot;]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');\n}\n</code></pre>\n" }, { "answer_id": 72115101, "author": "Rodolfo Jorge Nemer Nogueira", "author_id": 1102037, "author_profile": "https://Stackoverflow.com/users/1102037", "pm_score": 2, "selected": false, "text": "<p>This works for me on Chrome:</p>\n<pre><code>&lt;input type=&quot;checkbox&quot; onclick=&quot;return false&quot;&gt;\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything. I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.
`READONLY` doesn't work on checkboxes as it prevents you from editing a field's *value*, but with a checkbox you're actually editing the field's *state* (on || off) From [faqs.org](http://www.faqs.org/docs/htmltut/forms/_INPUT_DISABLED.html): > > It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field. > > > If you don't want to use `disabled` but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g. ``` // user allowed change if($user_allowed_edit) { echo '<input type="checkbox" name="my_check"> Check value'; } else { // Not allowed change - submit value.. echo '<input type="hidden" name="my_check" value="1" />'; // .. and show user the value being submitted echo '<input type="checkbox" disabled readonly> Check value'; } ```
155,303
<p>How do I go from this string: "ThisIsMyCapsDelimitedString"</p> <p>...to this string: "This Is My Caps Delimited String"</p> <p>Fewest lines of code in VB.net is preferred but C# is also welcome.</p> <p>Cheers!</p>
[ { "answer_id": 155331, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 0, "selected": false, "text": "<p>There's probably a more elegant solution, but this is what I come up with off the top of my head:</p>\n\n<pre><code>string myString = \"ThisIsMyCapsDelimitedString\";\n\nfor (int i = 1; i &lt; myString.Length; i++)\n{\n if (myString[i].ToString().ToUpper() == myString[i].ToString())\n {\n myString = myString.Insert(i, \" \");\n i++;\n }\n}\n</code></pre>\n" }, { "answer_id": 155336, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 4, "selected": false, "text": "<p>Grant Wagner's excellent comment aside:</p>\n\n<pre><code>Dim s As String = RegularExpressions.Regex.Replace(\"ThisIsMyCapsDelimitedString\", \"([A-Z])\", \" $1\")\n</code></pre>\n" }, { "answer_id": 155338, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<pre><code>string s = \"ThisIsMyCapsDelimitedString\";\nstring t = Regex.Replace(s, \"([A-Z])\", \" $1\").Substring(1);\n</code></pre>\n" }, { "answer_id": 155340, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 5, "selected": false, "text": "<pre><code>Regex.Replace(\"ThisIsMyCapsDelimitedString\", \"(\\\\B[A-Z])\", \" $1\")\n</code></pre>\n" }, { "answer_id": 155350, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 1, "selected": false, "text": "<p>Naive regex solution. Will not handle O'Conner, and adds a space at the start of the string as well. </p>\n\n<pre><code>s = \"ThisIsMyCapsDelimitedString\"\nsplit = Regex.Replace(s, \"[A-Z0-9]\", \" $&amp;\");\n</code></pre>\n" }, { "answer_id": 155486, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 4, "selected": false, "text": "<p>Just for a little variety... Here's an extension method that doesn't use a regex.</p>\n\n<pre><code>public static class CamelSpaceExtensions\n{\n public static string SpaceCamelCase(this String input)\n {\n return new string(Enumerable.Concat(\n input.Take(1), // No space before initial cap\n InsertSpacesBeforeCaps(input.Skip(1))\n ).ToArray());\n }\n\n private static IEnumerable&lt;char&gt; InsertSpacesBeforeCaps(IEnumerable&lt;char&gt; input)\n {\n foreach (char c in input)\n {\n if (char.IsUpper(c)) \n { \n yield return ' '; \n }\n\n yield return c;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 155487, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 9, "selected": true, "text": "<p>I made this a while ago. It matches each component of a CamelCase name.</p>\n\n<pre><code>/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>\"SimpleHTTPServer\" =&gt; [\"Simple\", \"HTTP\", \"Server\"]\n\"camelCase\" =&gt; [\"camel\", \"Case\"]\n</code></pre>\n\n<p>To convert that to just insert spaces between the words:</p>\n\n<pre><code>Regex.Replace(s, \"([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))\", \"$1 \")\n</code></pre>\n\n<hr>\n\n<p>If you need to handle digits:</p>\n\n<pre><code>/([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g\n\nRegex.Replace(s,\"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))\",\"$1 \")\n</code></pre>\n" }, { "answer_id": 156029, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "<p>For more variety, using plain old C# objects, the following produces the same output as @MizardX's excellent regular expression.</p>\n\n<pre><code>public string FromCamelCase(string camel)\n{ // omitted checking camel for null\n StringBuilder sb = new StringBuilder();\n int upperCaseRun = 0;\n foreach (char c in camel)\n { // append a space only if we're not at the start\n // and we're not already in an all caps string.\n if (char.IsUpper(c))\n {\n if (upperCaseRun == 0 &amp;&amp; sb.Length != 0)\n {\n sb.Append(' ');\n }\n upperCaseRun++;\n }\n else if( char.IsLower(c) )\n {\n if (upperCaseRun &gt; 1) //The first new word will also be capitalized.\n {\n sb.Insert(sb.Length - 1, ' ');\n }\n upperCaseRun = 0;\n }\n else\n {\n upperCaseRun = 0;\n }\n sb.Append(c);\n }\n\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 291870, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 4, "selected": false, "text": "<p>Great answer, MizardX! I tweaked it slightly to treat numerals as separate words, so that \"AddressLine1\" would become \"Address Line 1\" instead of \"Address Line1\":</p>\n\n<pre><code>Regex.Replace(s, \"([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))\", \"$1 \")\n</code></pre>\n" }, { "answer_id": 25479858, "author": "Erxin", "author_id": 1602830, "author_profile": "https://Stackoverflow.com/users/1602830", "pm_score": 0, "selected": false, "text": "<p>Try to use</p>\n\n<pre><code>\"([A-Z]*[^A-Z]*)\"\n</code></pre>\n\n<p>The result will fit for alphabet mix with numbers</p>\n\n<pre><code>Regex.Replace(\"AbcDefGH123Weh\", \"([A-Z]*[^A-Z]*)\", \"$1 \");\nAbc Def GH123 Weh \n\nRegex.Replace(\"camelCase\", \"([A-Z]*[^A-Z]*)\", \"$1 \");\ncamel Case \n</code></pre>\n" }, { "answer_id": 26876094, "author": "Dan Malcolm", "author_id": 146280, "author_profile": "https://Stackoverflow.com/users/146280", "pm_score": 3, "selected": false, "text": "<p>I needed a solution that supports acronyms and numbers. This Regex-based solution treats the following patterns as individual \"words\":</p>\n\n<ul>\n<li>A capital letter followed by lowercase letters</li>\n<li>A sequence of consecutive numbers</li>\n<li>Consecutive capital letters (interpreted as acronyms) - a new word can begin using the last capital, e.g. HTMLGuide => \"HTML Guide\", \"TheATeam\" => \"The A Team\"</li>\n</ul>\n\n<p>You <em>could</em> do it as a one-liner:</p>\n\n<pre><code>Regex.Replace(value, @\"(?&lt;!^)((?&lt;!\\d)\\d|(?(?&lt;=[A-Z])[A-Z](?=[a-z])|[A-Z]))\", \" $1\")\n</code></pre>\n\n<p>A more readable approach might be better:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nnamespace Demo\n{\n public class IntercappedStringHelper\n {\n private static readonly Regex SeparatorRegex;\n\n static IntercappedStringHelper()\n {\n const string pattern = @\"\n (?&lt;!^) # Not start\n (\n # Digit, not preceded by another digit\n (?&lt;!\\d)\\d \n |\n # Upper-case letter, followed by lower-case letter if\n # preceded by another upper-case letter, e.g. 'G' in HTMLGuide\n (?(?&lt;=[A-Z])[A-Z](?=[a-z])|[A-Z])\n )\";\n\n var options = RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled;\n\n SeparatorRegex = new Regex(pattern, options);\n }\n\n public static string SeparateWords(string value, string separator = \" \")\n {\n return SeparatorRegex.Replace(value, separator + \"$1\");\n }\n }\n}\n</code></pre>\n\n<p>Here's an extract from the (XUnit) tests:</p>\n\n<pre><code>[Theory]\n[InlineData(\"PurchaseOrders\", \"Purchase-Orders\")]\n[InlineData(\"purchaseOrders\", \"purchase-Orders\")]\n[InlineData(\"2Unlimited\", \"2-Unlimited\")]\n[InlineData(\"The2Unlimited\", \"The-2-Unlimited\")]\n[InlineData(\"Unlimited2\", \"Unlimited-2\")]\n[InlineData(\"222Unlimited\", \"222-Unlimited\")]\n[InlineData(\"The222Unlimited\", \"The-222-Unlimited\")]\n[InlineData(\"Unlimited222\", \"Unlimited-222\")]\n[InlineData(\"ATeam\", \"A-Team\")]\n[InlineData(\"TheATeam\", \"The-A-Team\")]\n[InlineData(\"TeamA\", \"Team-A\")]\n[InlineData(\"HTMLGuide\", \"HTML-Guide\")]\n[InlineData(\"TheHTMLGuide\", \"The-HTML-Guide\")]\n[InlineData(\"TheGuideToHTML\", \"The-Guide-To-HTML\")]\n[InlineData(\"HTMLGuide5\", \"HTML-Guide-5\")]\n[InlineData(\"TheHTML5Guide\", \"The-HTML-5-Guide\")]\n[InlineData(\"TheGuideToHTML5\", \"The-Guide-To-HTML-5\")]\n[InlineData(\"TheUKAllStars\", \"The-UK-All-Stars\")]\n[InlineData(\"AllStarsUK\", \"All-Stars-UK\")]\n[InlineData(\"UKAllStars\", \"UK-All-Stars\")]\n</code></pre>\n" }, { "answer_id": 31796173, "author": "Brantley Blanchard", "author_id": 1191709, "author_profile": "https://Stackoverflow.com/users/1191709", "pm_score": 2, "selected": false, "text": "<p>Below is a prototype that converts the following to Title Case:</p>\n\n<ul>\n<li>snake_case</li>\n<li>camelCase</li>\n<li>PascalCase</li>\n<li>sentence case</li>\n<li>Title Case (keep current formatting)</li>\n</ul>\n\n<p>Obviously you would only need the \"ToTitleCase\" method yourself.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n public static void Main()\n {\n var examples = new List&lt;string&gt; { \n \"THEQuickBrownFox\",\n \"theQUICKBrownFox\",\n \"TheQuickBrownFOX\",\n \"TheQuickBrownFox\",\n \"the_quick_brown_fox\",\n \"theFOX\",\n \"FOX\",\n \"QUICK\"\n };\n\n foreach (var example in examples)\n {\n Console.WriteLine(ToTitleCase(example));\n }\n }\n\n private static string ToTitleCase(string example)\n {\n var fromSnakeCase = example.Replace(\"_\", \" \");\n var lowerToUpper = Regex.Replace(fromSnakeCase, @\"(\\p{Ll})(\\p{Lu})\", \"$1 $2\");\n var sentenceCase = Regex.Replace(lowerToUpper, @\"(\\p{Lu}+)(\\p{Lu}\\p{Ll})\", \"$1 $2\");\n return new CultureInfo(\"en-US\", false).TextInfo.ToTitleCase(sentenceCase);\n }\n}\n</code></pre>\n\n<p>The console out would be as follows:</p>\n\n<blockquote>\n<pre><code>THE Quick Brown Fox\nThe QUICK Brown Fox\nThe Quick Brown FOX\nThe Quick Brown Fox\nThe Quick Brown Fox\nThe FOX\nFOX\nQUICK\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://brantleytec.blogspot.com/2015/07/pascalcase-or-camelcase-to-title-case.html\" rel=\"nofollow\">Blog Post Referenced</a></p>\n" }, { "answer_id": 37231964, "author": "shinzou", "author_id": 4279201, "author_profile": "https://Stackoverflow.com/users/4279201", "pm_score": 0, "selected": false, "text": "<p>Implementing the psudo code from: <a href=\"https://stackoverflow.com/a/5796394/4279201\">https://stackoverflow.com/a/5796394/4279201</a></p>\n\n<pre><code> private static StringBuilder camelCaseToRegular(string i_String)\n {\n StringBuilder output = new StringBuilder();\n int i = 0;\n foreach (char character in i_String)\n {\n if (character &lt;= 'Z' &amp;&amp; character &gt;= 'A' &amp;&amp; i &gt; 0)\n {\n output.Append(\" \");\n }\n output.Append(character);\n i++;\n }\n return output;\n }\n</code></pre>\n" }, { "answer_id": 43970785, "author": "Slai", "author_id": 1383168, "author_profile": "https://Stackoverflow.com/users/1383168", "pm_score": 0, "selected": false, "text": "<p>To match between non-uppercase and <a href=\"https://msdn.microsoft.com/en-us/library/20bw873z.aspx#SupportedUnicodeGeneralCategories\" rel=\"nofollow noreferrer\">Uppercase Letter Unicode Category</a> : <a href=\"https://regex101.com/r/zahL4H/1\" rel=\"nofollow noreferrer\"><code>(?&lt;=\\P{Lu})(?=\\p{Lu})</code></a></p>\n\n<pre><code>Dim s = Regex.Replace(\"CorrectHorseBatteryStaple\", \"(?&lt;=\\P{Lu})(?=\\p{Lu})\", \" \")\n</code></pre>\n" }, { "answer_id": 46567461, "author": "Zar Shardan", "author_id": 913845, "author_profile": "https://Stackoverflow.com/users/913845", "pm_score": 2, "selected": false, "text": "<p>Regex is about 10-12 times slower than a simple loop:</p>\n\n<pre><code> public static string CamelCaseToSpaceSeparated(this string str)\n {\n if (string.IsNullOrEmpty(str))\n {\n return str;\n }\n\n var res = new StringBuilder();\n\n res.Append(str[0]);\n for (var i = 1; i &lt; str.Length; i++)\n {\n if (char.IsUpper(str[i]))\n {\n res.Append(' ');\n }\n res.Append(str[i]);\n\n }\n return res.ToString();\n }\n</code></pre>\n" }, { "answer_id": 48185710, "author": "Patrick from NDepend team", "author_id": 27194, "author_profile": "https://Stackoverflow.com/users/27194", "pm_score": 0, "selected": false, "text": "<p>Procedural and fast impl:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Get the words in a code &lt;paramref name=\"identifier\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"identifier\"&gt;The code &lt;paramref name=\"identifier\"/&gt;&lt;/param&gt; to extract words from.\n public static string[] GetWords(this string identifier) {\n Contract.Ensures(Contract.Result&lt;string[]&gt;() != null, \"returned array of string is not null but can be empty\");\n if (identifier == null) { return new string[0]; }\n if (identifier.Length == 0) { return new string[0]; }\n\n const int MIN_WORD_LENGTH = 2; // Ignore one letter or one digit words\n\n var length = identifier.Length;\n var list = new List&lt;string&gt;(1 + length/2); // Set capacity, not possible more words since we discard one char words\n var sb = new StringBuilder();\n CharKind cKindCurrent = GetCharKind(identifier[0]); // length is not zero here\n CharKind cKindNext = length == 1 ? CharKind.End : GetCharKind(identifier[1]);\n\n for (var i = 0; i &lt; length; i++) {\n var c = identifier[i];\n CharKind cKindNextNext = (i &gt;= length - 2) ? CharKind.End : GetCharKind(identifier[i + 2]);\n\n // Process cKindCurrent\n switch (cKindCurrent) {\n case CharKind.Digit:\n case CharKind.LowerCaseLetter:\n sb.Append(c); // Append digit or lowerCaseLetter to sb\n if (cKindNext == CharKind.UpperCaseLetter) {\n goto TURN_SB_INTO_WORD; // Finish word if next char is upper\n }\n goto CHAR_PROCESSED;\n case CharKind.Other:\n goto TURN_SB_INTO_WORD;\n default: // charCurrent is never Start or End\n Debug.Assert(cKindCurrent == CharKind.UpperCaseLetter);\n break;\n }\n\n // Here cKindCurrent is UpperCaseLetter\n // Append UpperCaseLetter to sb anyway\n sb.Append(c); \n\n switch (cKindNext) {\n default:\n goto CHAR_PROCESSED;\n\n case CharKind.UpperCaseLetter: \n // \"SimpleHTTPServer\" when we are at 'P' we need to see that NextNext is 'e' to get the word!\n if (cKindNextNext == CharKind.LowerCaseLetter) {\n goto TURN_SB_INTO_WORD;\n }\n goto CHAR_PROCESSED;\n\n case CharKind.End:\n case CharKind.Other:\n break; // goto TURN_SB_INTO_WORD;\n }\n\n //------------------------------------------------\n\n TURN_SB_INTO_WORD:\n string word = sb.ToString();\n sb.Length = 0;\n if (word.Length &gt;= MIN_WORD_LENGTH) { \n list.Add(word);\n }\n\n CHAR_PROCESSED:\n // Shift left for next iteration!\n cKindCurrent = cKindNext;\n cKindNext = cKindNextNext;\n }\n\n string lastWord = sb.ToString();\n if (lastWord.Length &gt;= MIN_WORD_LENGTH) {\n list.Add(lastWord);\n }\n return list.ToArray();\n }\n private static CharKind GetCharKind(char c) {\n if (char.IsDigit(c)) { return CharKind.Digit; }\n if (char.IsLetter(c)) {\n if (char.IsUpper(c)) { return CharKind.UpperCaseLetter; }\n Debug.Assert(char.IsLower(c));\n return CharKind.LowerCaseLetter;\n }\n return CharKind.Other;\n }\n enum CharKind {\n End, // For end of string\n Digit,\n UpperCaseLetter,\n LowerCaseLetter,\n Other\n }\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code> [TestCase((string)null, \"\")]\n [TestCase(\"\", \"\")]\n\n // Ignore one letter or one digit words\n [TestCase(\"A\", \"\")]\n [TestCase(\"4\", \"\")]\n [TestCase(\"_\", \"\")]\n [TestCase(\"Word_m_Field\", \"Word Field\")]\n [TestCase(\"Word_4_Field\", \"Word Field\")]\n\n [TestCase(\"a4\", \"a4\")]\n [TestCase(\"ABC\", \"ABC\")]\n [TestCase(\"abc\", \"abc\")]\n [TestCase(\"AbCd\", \"Ab Cd\")]\n [TestCase(\"AbcCde\", \"Abc Cde\")]\n [TestCase(\"ABCCde\", \"ABC Cde\")]\n\n [TestCase(\"Abc42Cde\", \"Abc42 Cde\")]\n [TestCase(\"Abc42cde\", \"Abc42cde\")]\n [TestCase(\"ABC42Cde\", \"ABC42 Cde\")]\n [TestCase(\"42ABC\", \"42 ABC\")]\n [TestCase(\"42abc\", \"42abc\")]\n\n [TestCase(\"abc_cde\", \"abc cde\")]\n [TestCase(\"Abc_Cde\", \"Abc Cde\")]\n [TestCase(\"_Abc__Cde_\", \"Abc Cde\")]\n [TestCase(\"ABC_CDE_FGH\", \"ABC CDE FGH\")]\n [TestCase(\"ABC CDE FGH\", \"ABC CDE FGH\")] // Should not happend (white char) anything that is not a letter/digit/'_' is considered as a separator\n [TestCase(\"ABC,CDE;FGH\", \"ABC CDE FGH\")] // Should not happend (,;) anything that is not a letter/digit/'_' is considered as a separator\n [TestCase(\"abc&lt;cde\", \"abc cde\")]\n [TestCase(\"abc&lt;&gt;cde\", \"abc cde\")]\n [TestCase(\"abc&lt;D&gt;cde\", \"abc cde\")] // Ignore one letter or one digit words\n [TestCase(\"abc&lt;Da&gt;cde\", \"abc Da cde\")]\n [TestCase(\"abc&lt;cde&gt;\", \"abc cde\")]\n\n [TestCase(\"SimpleHTTPServer\", \"Simple HTTP Server\")]\n [TestCase(\"SimpleHTTPS2erver\", \"Simple HTTPS2erver\")]\n [TestCase(\"camelCase\", \"camel Case\")]\n [TestCase(\"m_Field\", \"Field\")]\n [TestCase(\"mm_Field\", \"mm Field\")]\n public void Test_GetWords(string identifier, string expectedWordsStr) {\n var expectedWords = expectedWordsStr.Split(' ');\n if (identifier == null || identifier.Length &lt;= 1) {\n expectedWords = new string[0];\n }\n\n var words = identifier.GetWords();\n Assert.IsTrue(words.SequenceEqual(expectedWords));\n }\n</code></pre>\n" }, { "answer_id": 52978450, "author": "John Smith", "author_id": 3739391, "author_profile": "https://Stackoverflow.com/users/3739391", "pm_score": 0, "selected": false, "text": "<p>A simple solution, which should be order(s) of magnitude faster than a regex solution (based on the tests I ran against the top solutions in this thread), especially as the size of the input string grows:</p>\n\n<pre><code>string s1 = \"ThisIsATestStringAbcDefGhiJklMnoPqrStuVwxYz\";\nstring s2;\nStringBuilder sb = new StringBuilder();\n\nforeach (char c in s1)\n sb.Append(char.IsUpper(c)\n ? \" \" + c.ToString()\n : c.ToString());\n\ns2 = sb.ToString();\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235/" ]
How do I go from this string: "ThisIsMyCapsDelimitedString" ...to this string: "This Is My Caps Delimited String" Fewest lines of code in VB.net is preferred but C# is also welcome. Cheers!
I made this a while ago. It matches each component of a CamelCase name. ``` /([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g ``` For example: ``` "SimpleHTTPServer" => ["Simple", "HTTP", "Server"] "camelCase" => ["camel", "Case"] ``` To convert that to just insert spaces between the words: ``` Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ") ``` --- If you need to handle digits: ``` /([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g Regex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))","$1 ") ```
155,306
<p>I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345.</p> <p><code>scrollTop</code> sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, it's not possible to make textareas not line-wrap.</p>
[ { "answer_id": 155404, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": true, "text": "<p>You can stop wrapping with the wrap attribute. It is not part of HTML 4, but most browsers support it.<br />\nYou can compute the height of a line by dividing the height of the area by its number of rows.</p>\n<pre><code>&lt;script type=&quot;text/javascript&quot; language=&quot;JavaScript&quot;&gt;\nfunction Jump(line)\n{\n var ta = document.getElementById(&quot;TextArea&quot;);\n var lineHeight = ta.clientHeight / ta.rows;\n var jump = (line - 1) * lineHeight;\n ta.scrollTop = jump;\n}\n&lt;/script&gt;\n\n&lt;textarea name=&quot;TextArea&quot; id=&quot;TextArea&quot; \n rows=&quot;40&quot; cols=&quot;80&quot; title=&quot;Paste text here&quot;\n wrap=&quot;off&quot;&gt;&lt;/textarea&gt;\n&lt;input type=&quot;button&quot; onclick=&quot;Jump(98)&quot; title=&quot;Go!&quot; value=&quot;Jump&quot;/&gt;\n</code></pre>\n<p>Tested OK in FF3 and IE6.</p>\n" }, { "answer_id": 14199739, "author": "tetkin", "author_id": 1456378, "author_profile": "https://Stackoverflow.com/users/1456378", "pm_score": 2, "selected": false, "text": "<p>If you use .scrollHeight instead of .clientHeight, it will work properly for textareas that are shown with a limited height and a scrollbar:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"JavaScript\"&gt;\nfunction Jump(line)\n{\n var ta = document.getElementById(\"TextArea\");\n var lineHeight = ta.scrollHeight / ta.rows;\n var jump = (line - 1) * lineHeight;\n ta.scrollTop = jump;\n}\n&lt;/script&gt;\n\n&lt;textarea name=\"TextArea\" id=\"TextArea\" \n rows=\"40\" cols=\"80\" title=\"Paste text here\"\n wrap=\"off\"&gt;&lt;/textarea&gt;\n&lt;input type=\"button\" onclick=\"Jump(98)\" title=\"Go!\" value=\"Jump\"/&gt;\n</code></pre>\n" }, { "answer_id": 49033334, "author": "Darren Shewry", "author_id": 142714, "author_profile": "https://Stackoverflow.com/users/142714", "pm_score": 0, "selected": false, "text": "<p>Something to consider when referring to the accepted answer: you may not have specified the <code>rows</code> attribute in your <code>textarea</code> e.g. instead, you may have set the height of the <code>textarea</code> using CSS.</p>\n\n<p>Therefore referring to <code>ta.rows</code> will not work as per above (it's 2 by default), so instead you could get the <code>line-height</code> of your <code>textarea</code> via <code>currentStyle</code> / <code>getComputedStyle</code> or even jQuery's <code>.css()</code>, and do something like the following:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function jump(line) {\n var ta = document.getElementById(\"TextArea\");\n var jump = line * parseInt(getStyle(ta, 'line-height'), 10);\n ta.scrollTop = jump;\n}\n\nfunction getStyle(el, styleProp) {\n if (el.currentStyle) {\n var y = el.currentStyle[styleProp];\n } else if (window.getComputedStyle) {\n var y = document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);\n }\n return y;\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345. `scrollTop` sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, it's not possible to make textareas not line-wrap.
You can stop wrapping with the wrap attribute. It is not part of HTML 4, but most browsers support it. You can compute the height of a line by dividing the height of the area by its number of rows. ``` <script type="text/javascript" language="JavaScript"> function Jump(line) { var ta = document.getElementById("TextArea"); var lineHeight = ta.clientHeight / ta.rows; var jump = (line - 1) * lineHeight; ta.scrollTop = jump; } </script> <textarea name="TextArea" id="TextArea" rows="40" cols="80" title="Paste text here" wrap="off"></textarea> <input type="button" onclick="Jump(98)" title="Go!" value="Jump"/> ``` Tested OK in FF3 and IE6.
155,308
<p>I'm trying to get a PHP site working in IIS on Windows Server with MySQL.</p> <p>I'm getting this error…</p> <p>Fatal error: Call to undefined function mysql_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363</p> <hr /> <p>Update…</p> <p>This link outlines the steps I followed to install PHP on my server:<br /> <a href="https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341">How do I get PHP and MySQL working on IIS 7.0 ?</a><br /> (note especially steps 6 and 8 regarting php.ini and php_mysql.dll).</p> <p>Only two lines in the phpinfo report reference SQL:</p> <pre><code>&lt;?php phpinfo(); ?&gt; </code></pre> <blockquote> <p>Configure Command:<br /> cscript /nologo configure.js &quot;--enable-snapshot-build&quot; &quot;--enable-mysqlnd&quot;</p> <p>sql.safe_mode:<br /> Local Value Off, Master Value Off</p> </blockquote> <p><a href="http://img79.imageshack.us/img79/2373/configurecommandmw8.gif" rel="nofollow noreferrer">PHP Configure Command http://img79.imageshack.us/img79/2373/configurecommandmw8.gif</a></p> <p><a href="http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif" rel="nofollow noreferrer">PHP sql.safe_mode http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif</a></p> <hr /> <p>Update…</p> <p>I found the solution: <a href="https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746">How do I install MySQL modules within PHP?</a></p>
[ { "answer_id": 155316, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 2, "selected": false, "text": "<p>Check out phpinfo to see if the mysql functions are compiled with your PHP</p>\n\n<pre><code>&lt;?php\n phpinfo();\n?&gt;\n</code></pre>\n\n<p>Since in some versions of php, its not default with the install.</p>\n\n<p><b>Edit for the Update:</b></p>\n\n<p>You should have a full MySQL category in your phpinfo();</p>\n\n<p>See this for example: <a href=\"https://secure18.easycgi.com/phpinfo.php\" rel=\"nofollow noreferrer\">https://secure18.easycgi.com/phpinfo.php</a> (googled example)</p>\n" }, { "answer_id": 155318, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 1, "selected": false, "text": "<p>It sounds like the version of PHP you are using has not been compiled with MySQL support, or has not been enabled in the php.ini.</p>\n" }, { "answer_id": 157912, "author": "James Marshall", "author_id": 1025, "author_profile": "https://Stackoverflow.com/users/1025", "pm_score": 1, "selected": false, "text": "<p>Looks like you haven't got the MySQL PHP extensions installed! You shouldn't have to do any configuration other than installing the correct modules (and shouldn't be doing <em>anything</em> with ADODB).</p>\n\n<p>PHP comes in 2 versions as well - a CGI version and an ISAPI module. You're best using the ISAPI version with ISS and adding all the trimmings...</p>\n" }, { "answer_id": 443553, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 2, "selected": true, "text": "<p>I found the solution: <a href=\"https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746\">How do I install MySQL modules within PHP?</a></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'm trying to get a PHP site working in IIS on Windows Server with MySQL. I'm getting this error… Fatal error: Call to undefined function mysql\_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363 --- Update… This link outlines the steps I followed to install PHP on my server: [How do I get PHP and MySQL working on IIS 7.0 ?](https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341) (note especially steps 6 and 8 regarting php.ini and php\_mysql.dll). Only two lines in the phpinfo report reference SQL: ``` <?php phpinfo(); ?> ``` > > Configure Command: > > cscript /nologo configure.js "--enable-snapshot-build" "--enable-mysqlnd" > > > sql.safe\_mode: > > Local Value Off, Master Value Off > > > [PHP Configure Command http://img79.imageshack.us/img79/2373/configurecommandmw8.gif](http://img79.imageshack.us/img79/2373/configurecommandmw8.gif) [PHP sql.safe\_mode http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif](http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif) --- Update… I found the solution: [How do I install MySQL modules within PHP?](https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746)
I found the solution: [How do I install MySQL modules within PHP?](https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746)
155,311
<p>I would like invoke a function call in a one shot manner. What's the best way to do this in Boost / C++?</p> <p>I would like to pass it two parameters and do not need a result.</p>
[ { "answer_id": 155339, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 0, "selected": false, "text": "<p>Perhaps you want to emit a signal?</p>\n\n<p>I really liked Qt's signals and slots functionality, and I know Boost has signals/slots as well. I've never used signals/slots in Boost, though.</p>\n" }, { "answer_id": 155420, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 2, "selected": false, "text": "<p>Well you can spin up a thread and then never join it again. Something like:</p>\n\n<pre><code>boost::thread some_thread(&amp;SomeFunction, param1, param2);\n</code></pre>\n\n<p>Once the some_thread variable goes out of scope, the thread of execution will be detached and will not be able to be joined again. It's a waste to spin up a thread unless the processing time of this function is significant though.</p>\n" }, { "answer_id": 155434, "author": "David Smith", "author_id": 17201, "author_profile": "https://Stackoverflow.com/users/17201", "pm_score": 2, "selected": false, "text": "<p>I haven't used boost::thread in awhile but I see a quick example on the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/thread/thread_management.html\" rel=\"nofollow noreferrer\">documentation page for the class</a>:</p>\n\n<pre><code>void find_the_question(int the_answer);\n\nboost::thread deep_thought_2(find_the_question,42);\n</code></pre>\n\n<p>I believe as soon as it finishes the function, the thread will exit. This may not be what you want in that once the thread goes out of scope, it will be destroyed. If that's not going to work, you probably need to create a long running thread pool and then pass your functors as boost::bind compositions.</p>\n" }, { "answer_id": 155843, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "<p>Depending on how often you are doing this, you might be best off creating a pool of threads, along with a work queue. Creating a thread can create a lot of overhead if you are trying to do it dozens of times a second. If you don't care about the return value, that makes it really easy. </p>\n\n<p>Spin up a thread or two (or ten); have a thread-safe queue of functors to call (bind the parameters to the function and put that on the queue); the threads wait on the queue for something to show up, the first thread to wake up gets to process the work. When a thread is done running a job, it waits on the queue again. </p>\n\n<p>Take a look at <a href=\"http://www.codeproject.com/KB/threads/ProducerConsumerModel.aspx\" rel=\"nofollow noreferrer\">this project</a> for an idea of one way to do it. </p>\n\n<p>Of course if you are only making asynchonous calls every couple of seconds to improve a UI's responsiveness, it'd be easier to just start up a new thread every time.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
I would like invoke a function call in a one shot manner. What's the best way to do this in Boost / C++? I would like to pass it two parameters and do not need a result.
Well you can spin up a thread and then never join it again. Something like: ``` boost::thread some_thread(&SomeFunction, param1, param2); ``` Once the some\_thread variable goes out of scope, the thread of execution will be detached and will not be able to be joined again. It's a waste to spin up a thread unless the processing time of this function is significant though.
155,314
<p>I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail.</p> <p>Something along these lines should work: </p> <pre><code>// filename examples: "test.avi", "test.dvr-ms" // position is from 0 to 100 percent (0.0 to 1.0) // returns a bitmap byte[] GetVideoThumbnail(string filename, float position) { } </code></pre> <p>Does anyone know how to do this in .Net 3.0? </p> <p>The correct solution will be the "best" implementation of this function. Bonus points for avoiding selection of blank frames. </p>
[ { "answer_id": 155320, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 3, "selected": false, "text": "<p>This project will do the trick for AVIs: <a href=\"http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx</a></p>\n\n<p>Anything other formats, you might look into directshow. There are a few projects that might help:<br>\n<a href=\"http://sourceforge.net/projects/directshownet/\" rel=\"noreferrer\">http://sourceforge.net/projects/directshownet/</a><br>\n<a href=\"http://code.google.com/p/slimdx/\" rel=\"noreferrer\">http://code.google.com/p/slimdx/</a></p>\n" }, { "answer_id": 219172, "author": "GuyWithDogs", "author_id": 9520, "author_profile": "https://Stackoverflow.com/users/9520", "pm_score": 0, "selected": false, "text": "<p>There are some libraries at <a href=\"http://www.mitov.com\" rel=\"nofollow noreferrer\">www.mitov.com</a> that may help. It's a generic wrapper for Directshow functionality, and I think one of the demos shows how to take a frame from a video file.</p>\n" }, { "answer_id": 418953, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 4, "selected": true, "text": "<p>I ended up rolling my own stand alone class (with the single method I described), the source can be <a href=\"https://gist.github.com/2823028\" rel=\"noreferrer\">viewed here</a>. <a href=\"http://www.mediabrowser.tv\" rel=\"noreferrer\">Media browser is</a> GPL but I am happy for the code I wrote for that file to be Public Domain. Keep in mind it uses interop from the <a href=\"http://sourceforge.net/projects/directshownet/\" rel=\"noreferrer\">directshow.net</a> project so you will have to clear that portion of the code with them. </p>\n\n<p>This class will not work for DVR-MS files, you need to inject a direct show filter for those.</p>\n" }, { "answer_id": 6852123, "author": "Ahmad Behjati", "author_id": 866395, "author_profile": "https://Stackoverflow.com/users/866395", "pm_score": 2, "selected": false, "text": "<p>1- Get latest version of ffmpeg.exe from : <a href=\"http://ffmpeg.arrozcru.org/builds/\" rel=\"nofollow\">http://ffmpeg.arrozcru.org/builds/</a></p>\n\n<p>2- Extract the file and copy ffmpeg.exe to your website</p>\n\n<p>3- Use this Code:</p>\n\n<pre><code>Process ffmpeg;\n\nstring video;\nstring thumb;\n\nvideo = Server.MapPath(\"first.avi\");\nthumb = Server.MapPath(\"frame.jpg\");\n\nffmpeg = new Process();\n\nffmpeg.StartInfo.Arguments = \" -i \"+video+\" -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg \"+thumb;\nffmpeg.StartInfo.FileName = Server.MapPath(\"ffmpeg.exe\");\nffmpeg.Start();\n</code></pre>\n" }, { "answer_id": 11706098, "author": "Maciej", "author_id": 77273, "author_profile": "https://Stackoverflow.com/users/77273", "pm_score": 0, "selected": false, "text": "<p>This is also worth to see:</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/13237/Extract-Frames-from-Video-Files\" rel=\"nofollow\">http://www.codeproject.com/Articles/13237/Extract-Frames-from-Video-Files</a></p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail. Something along these lines should work: ``` // filename examples: "test.avi", "test.dvr-ms" // position is from 0 to 100 percent (0.0 to 1.0) // returns a bitmap byte[] GetVideoThumbnail(string filename, float position) { } ``` Does anyone know how to do this in .Net 3.0? The correct solution will be the "best" implementation of this function. Bonus points for avoiding selection of blank frames.
I ended up rolling my own stand alone class (with the single method I described), the source can be [viewed here](https://gist.github.com/2823028). [Media browser is](http://www.mediabrowser.tv) GPL but I am happy for the code I wrote for that file to be Public Domain. Keep in mind it uses interop from the [directshow.net](http://sourceforge.net/projects/directshownet/) project so you will have to clear that portion of the code with them. This class will not work for DVR-MS files, you need to inject a direct show filter for those.
155,321
<p>I'm trying to build a mapping table to associate the IDs of new rows in a table with those that they're copied from. The OUTPUT INTO clause seems perfect for that, but it doesn't seem to behave according to the documentation. </p> <p>My code:</p> <pre><code>DECLARE @Missing TABLE (SrcContentID INT PRIMARY KEY ) INSERT INTO @Missing ( SrcContentID ) SELECT cshadow.ContentID FROM Private.Content AS cshadow LEFT JOIN Private.Content AS cglobal ON cshadow.Tag = cglobal.Tag WHERE cglobal.ContentID IS NULL PRINT 'Adding new content headers' DECLARE @Inserted TABLE (SrcContentID INT PRIMARY KEY, TgtContentID INT ) INSERT INTO Private.Content ( Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, OrgUnitID ) OUTPUT cglobal.ContentID, INSERTED.ContentID INTO @Inserted (SrcContentID, TgtContentID) SELECT Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, NULL FROM Private.Content AS cglobal INNER JOIN @Missing AS m ON cglobal.ContentID = m.SrcContentID </code></pre> <p>Results in the error message:</p> <pre><code>Msg 207, Level 16, State 1, Line 34 Invalid column name 'SrcContentID'. </code></pre> <p>(line 34 being the one with the OUTPUT INTO)</p> <p>Experimentation suggests that only rows that are actually present in the target of the INSERT can be selected in the OUTPUT INTO. But this contradicts the docs in the books online. The article on <strong>OUTPUT Clause</strong> has example E that describes a similar usage:</p> <blockquote> <p>The OUTPUT INTO clause returns values from the table being updated (WorkOrder) and also from the Product table. The Product table is used in the FROM clause to specify the rows to update.</p> </blockquote> <p>Has anyone worked with this feature?</p> <p>(In the meantime I've rewritten my code to do the job using a cursor loop, but that's ugly and I'm still curious)</p>
[ { "answer_id": 156352, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": true, "text": "<p>I've verified that the problem is that you can only use <code>INSERTED</code> columns. The documentation seems to indicate that you can use <code>from_table_name</code>, but I can't seem to get it to work (The multi-part identifier \"m.ContentID\" could not be bound.):</p>\n\n<pre><code>TRUNCATE TABLE main\n\nSELECT *\nFROM incoming\n\nSELECT *\nFROM main\n\nDECLARE @Missing TABLE (ContentID INT PRIMARY KEY)\nINSERT INTO @Missing(ContentID) \nSELECT incoming.ContentID\nFROM incoming\nLEFT JOIN main\n ON main.ContentID = incoming.ContentID\nWHERE main.ContentID IS NULL\n\nSELECT *\nFROM @Missing\n\nDECLARE @Inserted TABLE (ContentID INT PRIMARY KEY, [Content] varchar(50))\nINSERT INTO main(ContentID, [Content]) \nOUTPUT INSERTED.ContentID /* incoming doesn't work, m doesn't work */, INSERTED.[Content] INTO @Inserted (ContentID, [Content])\nSELECT incoming.ContentID, incoming.[Content] \nFROM incoming\nINNER JOIN @Missing AS m\n ON m.ContentID = incoming.ContentID\n\nSELECT *\nFROM @Inserted\n\nSELECT *\nFROM incoming\n\nSELECT *\nFROM main\n</code></pre>\n\n<p>Apparently the <code>from_table_name</code> prefix is only allowed on <code>DELETE</code> or <code>UPDATE</code> (or <code>MERGE</code> in 2008) - I'm not sure why:</p>\n\n<ul>\n<li><code>from_table_name</code></li>\n</ul>\n\n<p>Is a column prefix that specifies a table included in the <code>FROM</code> clause of a <code>DELETE</code> or <code>UPDATE</code> statement that is used to specify the rows to update or delete.</p>\n\n<p>If the table being modified is also specified in the <code>FROM</code> clause, any reference to columns in that table must be qualified with the <code>INSERTED</code> or <code>DELETED</code> prefix.</p>\n" }, { "answer_id": 659122, "author": "Roland Zwaga", "author_id": 79594, "author_profile": "https://Stackoverflow.com/users/79594", "pm_score": 3, "selected": false, "text": "<p>I'm running into EXACTLY the same problem as you are, I feel your pain...\nAs far as I've been able to find out there's no way to use the from_table_name prefix with an INSERT statement.\nI'm sure there's a viable technical reason for this, and I'd love to know exactly what it is.</p>\n\n<p>Ok, found it, here's a forum post on why it doesn't work:\n<a href=\"http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/c1fe0b9c-9305-4cb0-9237-9374ff4fc03e/\" rel=\"nofollow noreferrer\">MSDN forums</a></p>\n" }, { "answer_id": 662046, "author": "Roland Zwaga", "author_id": 79594, "author_profile": "https://Stackoverflow.com/users/79594", "pm_score": 0, "selected": false, "text": "<p>I think I found a solution to this problem, it sadly involves a temporary table, but at least it'll prevent the creation of a dreaded cursor :)\nWhat you need to do is add an extra column to the table you're duplicating records from and give it a 'uniqueidentifer' type.</p>\n\n<p>then declare a temporary table:</p>\n\n<pre><code>DECLARE @tmptable TABLE (uniqueid uniqueidentifier, original_id int, new_id int)\n</code></pre>\n\n<p>insert the the data into your temp table like this:</p>\n\n<pre><code>insert into @tmptable\n(uniqueid,original_id,new_id)\nselect NewId(),id,0 from OriginalTable\n</code></pre>\n\n<p>the go ahead and do the real insert into the original table:</p>\n\n<pre><code>insert into OriginalTable\n(uniqueid)\nselect uniqueid from @tmptable\n</code></pre>\n\n<p>Now to add the newly created identity values to your temp table:</p>\n\n<pre><code>update @tmptable\nset new_id = o.id\nfrom OriginalTable o inner join @tmptable tmp on tmp.uniqueid = o.uniqueid\n</code></pre>\n\n<p>Now you have a lookup table that holds the new id and original id in one record, for your using pleasure :)</p>\n\n<p>I hope this helps somebody...</p>\n" }, { "answer_id": 4192191, "author": "ArtOfCoding", "author_id": 272067, "author_profile": "https://Stackoverflow.com/users/272067", "pm_score": 0, "selected": false, "text": "<p>(MS) If the table being modified is also specified in the FROM clause, any reference to columns in that table must be qualified with the INSERTED or DELETED prefix.</p>\n\n<p>In your example, you can't use cglobal table in the OUTPUT unless it's INSERTED.column_name or DELETED.column_name:</p>\n\n<pre><code>INSERT INTO Private.Content \n (Tag) \n OUTPUT cglobal.ContentID, INSERTED.ContentID \n INTO @Inserted (SrcContentID, TgtContentID)\nSELECT Tag\n FROM Private.Content AS cglobal\n INNER JOIN @Missing AS m ON cglobal.ContentID = m.SrcContentID\n</code></pre>\n\n<p>What worked for me was a simple alias table, like this:</p>\n\n<pre><code>INSERT INTO con1 \n (Tag) \n OUTPUT **con2**.ContentID, INSERTED.ContentID \n INTO @Inserted (SrcContentID, TgtContentID)\nSELECT Tag\n FROM Private.Content con1\n **INNER JOIN Private.Content con2 ON con1.id=con2.id**\n INNER JOIN @Missing AS m ON con1.ContentID = m.SrcContentID\n</code></pre>\n" }, { "answer_id": 5423588, "author": "Simon D", "author_id": 161040, "author_profile": "https://Stackoverflow.com/users/161040", "pm_score": 4, "selected": false, "text": "<p>You can do this with a MERGE in Sql Server 2008. Example code below:</p>\n\n<pre><code>--drop table A\ncreate table A (a int primary key identity(1, 1))\ninsert into A default values\ninsert into A default values\n\ndelete from A where a&gt;=3\n\n-- insert two values into A and get the new primary keys\nMERGE a USING (SELECT a FROM A) AS B(a)\nON (1 = 0) -- ignore the values, NOT MATCHED will always be true\nWHEN NOT MATCHED THEN INSERT DEFAULT VALUES -- always insert here for this example\nOUTPUT $action, inserted.*, deleted.*, B.a; -- show the new primary key and source data\n</code></pre>\n\n<p>Result is</p>\n\n<pre><code>INSERT, 3, NULL, 1\nINSERT, 4, NULL, 2\n</code></pre>\n\n<p>i.e. for each row the new primary key (3, 4) and the old one (1, 2). Creating a table called e.g. #OUTPUT and adding \" INTO #OUTPUT;\" at the end of the OUTPUT clause would save the records.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10082/" ]
I'm trying to build a mapping table to associate the IDs of new rows in a table with those that they're copied from. The OUTPUT INTO clause seems perfect for that, but it doesn't seem to behave according to the documentation. My code: ``` DECLARE @Missing TABLE (SrcContentID INT PRIMARY KEY ) INSERT INTO @Missing ( SrcContentID ) SELECT cshadow.ContentID FROM Private.Content AS cshadow LEFT JOIN Private.Content AS cglobal ON cshadow.Tag = cglobal.Tag WHERE cglobal.ContentID IS NULL PRINT 'Adding new content headers' DECLARE @Inserted TABLE (SrcContentID INT PRIMARY KEY, TgtContentID INT ) INSERT INTO Private.Content ( Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, OrgUnitID ) OUTPUT cglobal.ContentID, INSERTED.ContentID INTO @Inserted (SrcContentID, TgtContentID) SELECT Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, NULL FROM Private.Content AS cglobal INNER JOIN @Missing AS m ON cglobal.ContentID = m.SrcContentID ``` Results in the error message: ``` Msg 207, Level 16, State 1, Line 34 Invalid column name 'SrcContentID'. ``` (line 34 being the one with the OUTPUT INTO) Experimentation suggests that only rows that are actually present in the target of the INSERT can be selected in the OUTPUT INTO. But this contradicts the docs in the books online. The article on **OUTPUT Clause** has example E that describes a similar usage: > > The OUTPUT INTO clause returns values > from the table being updated > (WorkOrder) and also from the Product > table. The Product table is used in > the FROM clause to specify the rows to > update. > > > Has anyone worked with this feature? (In the meantime I've rewritten my code to do the job using a cursor loop, but that's ugly and I'm still curious)
I've verified that the problem is that you can only use `INSERTED` columns. The documentation seems to indicate that you can use `from_table_name`, but I can't seem to get it to work (The multi-part identifier "m.ContentID" could not be bound.): ``` TRUNCATE TABLE main SELECT * FROM incoming SELECT * FROM main DECLARE @Missing TABLE (ContentID INT PRIMARY KEY) INSERT INTO @Missing(ContentID) SELECT incoming.ContentID FROM incoming LEFT JOIN main ON main.ContentID = incoming.ContentID WHERE main.ContentID IS NULL SELECT * FROM @Missing DECLARE @Inserted TABLE (ContentID INT PRIMARY KEY, [Content] varchar(50)) INSERT INTO main(ContentID, [Content]) OUTPUT INSERTED.ContentID /* incoming doesn't work, m doesn't work */, INSERTED.[Content] INTO @Inserted (ContentID, [Content]) SELECT incoming.ContentID, incoming.[Content] FROM incoming INNER JOIN @Missing AS m ON m.ContentID = incoming.ContentID SELECT * FROM @Inserted SELECT * FROM incoming SELECT * FROM main ``` Apparently the `from_table_name` prefix is only allowed on `DELETE` or `UPDATE` (or `MERGE` in 2008) - I'm not sure why: * `from_table_name` Is a column prefix that specifies a table included in the `FROM` clause of a `DELETE` or `UPDATE` statement that is used to specify the rows to update or delete. If the table being modified is also specified in the `FROM` clause, any reference to columns in that table must be qualified with the `INSERTED` or `DELETED` prefix.
155,334
<p>The application uses Oracle DataAccess ver. 1.1. , VS 2008, .Net Framework 3.5 w/SP1</p> <pre><code>OracleConnection connection = new OracleConnection(ConnectionStringLogon); connection.Open(); OracleParameter selectParam = new OracleParameter(":applicationName", OracleDbType.Varchar2, 256); selectParam.Value = applicationName; if (connection.State != ConnectionState.Open) connection.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = connection; cmd.CommandText = "Select ApplicationId from Applications where AppName = 'appName'"; cmd.CommandType = CommandType.Text; if (selectParam != null) { cmd.Parameters.Add(selectParam); } object lookupResult = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if (lookupResult != null) </code></pre> <p>The procedure fails on object lookupResult = cmd.ExecuteScalar(); with this error:</p> <p>Event Type: Error Event Source: App Log Event Category: None Event ID: 9961 Date: 9/30/2008 Time: 4:42:11 PM User: N/A Computer: Server15 Description: System.NullReferenceException: Object reference not set to an instance of an object. at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior) at Oracle.DataAccess.Client.OracleCommand.ExecuteReader() at Oracle.DataAccess.Client.OracleCommand.ExecuteScalar() at Membership.OracleMembershipProvider.GetApplicationId(String applicationName, Boolean createIfNeeded) in OracleMembershipProvider.cs:line 1626</p> <p>I've looked at this from every angle that I can conceive of... basically, no matter how I wrap it, the Execute fails.</p>
[ { "answer_id": 155335, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>The closest I can think of is doing something similar with <a href=\"http://www.shunra.com/vedesktop.aspx\" rel=\"nofollow noreferrer\">VEDekstop</a> from Shunra..</p>\n\n<p><a href=\"http://sqlblog.com/blogs/john_paul_cook/archive/2008/04/13/simulating-high-latency-and-low-bandwidth-for-database-connectivity-testing.aspx\" rel=\"nofollow noreferrer\">Simulating High Latency and Low Bandwidth in Testing of Database Applications</a> </p>\n\n<p><em>Shunra VE Desktop Standard is a Windows-based client software solution that simulates a wide area network link so that you can test applications under a variety of current and potential network conditions – directly from your desktop.</em> </p>\n" }, { "answer_id": 155343, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>if you're using apache you may want to take a look at <a href=\"http://httpd.apache.org/docs/2.0/programs/ab.html\" rel=\"noreferrer\">apache ab</a></p>\n" }, { "answer_id": 155720, "author": "Matthew Smith", "author_id": 20889, "author_profile": "https://Stackoverflow.com/users/20889", "pm_score": 1, "selected": false, "text": "<p>I wrote a php script awhile back which used CURL to run a sequence of page requests against my server which represented a typical use scenario. I had it output the times that it took for the server to respond to each of the requests. I then had another script which spawned a bunch of these test case scripts simultaneously for a sustained period and correlated the results into a file which I could then look at in a spreadsheet to see average times. This way I could simulate the number of users hitting the site that I wanted. The limitations are that you need to run the test script on a different server to the web server and that the client machine can become too loaded to give meaningful results past a certain point. I've since left the job otherwise I would paste the scripts here.</p>\n" }, { "answer_id": 155885, "author": "Kalpesh Patel", "author_id": 23003, "author_profile": "https://Stackoverflow.com/users/23003", "pm_score": 0, "selected": false, "text": "<p>We use Loadrunner to do bandwidth and traffic simulation in our App. Loadrunner is can start agents on various machines and you can simulate one machine as running on dialup modem v/s another on DSL v/s another on Cable internet.\nWe also use Loadrunner to simulate various kinds of traffic conditions from 10 user run to 500 user run. We can also insert think times in the script and simulate a real user executing the http request. The best part is that it comes with a recording studio where it will plug in with Internet explorer and you can record the whole scenario/Usecase that can be as simple as hitting one page to a full blown 50-60 page script or more.</p>\n" }, { "answer_id": 159344, "author": "paranoio", "author_id": 11124, "author_profile": "https://Stackoverflow.com/users/11124", "pm_score": 0, "selected": false, "text": "<p>i found this little java program that works great : <a href=\"http://www.dallaway.com/sloppy/\" rel=\"nofollow noreferrer\">sloppy</a></p>\n\n<p>yet not a proffesional solution but it works for simple tests, i guess it uses java streams and buffers to slow down the connection .</p>\n" }, { "answer_id": 236177, "author": "Sargun Dhillon", "author_id": 10432, "author_profile": "https://Stackoverflow.com/users/10432", "pm_score": 0, "selected": false, "text": "<p>Have you looked at Tsung? It's a great utility for seeing if your website will scale in event of attack, I mean massive popularity. We use it for our web frontend, and our internal systems too. </p>\n" }, { "answer_id": 236186, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 1, "selected": false, "text": "<p>If you are running a Linux box as your server, Linux box as your client, or have the capability to put (perhaps a VM) a Linux router between your client and server, you can use NetEm.</p>\n\n<p><a href=\"http://www.linuxfoundation.org/en/Net:Netem\" rel=\"nofollow noreferrer\">NetEm</a> is a Linux TC (Traffic Control) discipline which can delay (i.e. add latency) packets leaving a host. Although it's tricky to set up clever rules (e.g. add latency to some traffic, not to others), it's easy to add a simple \"delay everything leaving the interface by 50ms\" type rules and some recipes are provided.</p>\n\n<p>By sticking a Linux VM between your client and server, you can simulate as much latency as you like. And you can turn it on and off dynamically. Linux has other TC disciplines which can be combined with NetEm to restrict bandwidth (but the script to set this up can be somewhat complicated). NetEm can also randomly drop packets.</p>\n\n<p>I use it and it works a treat :)</p>\n" }, { "answer_id": 342563, "author": "picardo", "author_id": 32816, "author_profile": "https://Stackoverflow.com/users/32816", "pm_score": 0, "selected": false, "text": "<p>If you're interested in performing your tests out of your browser, there is also <a href=\"http://www.uselessapplications.com/en/Application/FirefoxThrottle.aspx\" rel=\"nofollow noreferrer\">a really great Firefox plug-in</a>. </p>\n" }, { "answer_id": 401200, "author": "rupello", "author_id": 635, "author_profile": "https://Stackoverflow.com/users/635", "pm_score": 2, "selected": false, "text": "<p>There are two approaches to shape network traffic to simulate a network link:</p>\n\n<ol>\n<li>Run some software on the client or server that sits somewhere in the networking stack and shapes the traffic between the app and the network interface</li>\n<li>Run the traffic shaping software on a dedicated machine with 2 network interfaces through which your traffic is routed</li>\n</ol>\n\n<p>(2) is a better solution if you don't want to install software on the client or server (and possibly impact performance), but requires more hardware fiddling. </p>\n\n<p>Some other features you might want to think about are what shaping parameters can be simulated. Most do delay and packet loss, some do jitter and bandwidth limiting as well. Some solutions can selectively filter traffic (for instance by port number, TCP or UDP etc).</p>\n\n<p>Here is a list of some of the systems I've found:</p>\n\n<p><strong>Open Source or Freeware</strong></p>\n\n<p><a href=\"http://info.iet.unipi.it/~luigi/ip_dummynet/\" rel=\"nofollow noreferrer\">DummyNet</a> is an open source BSD Unix-based for dedicated devices. It is not clear if the software is being actively maintained</p>\n\n<p><a href=\"http://snad.ncsl.nist.gov/nistnet/\" rel=\"nofollow noreferrer\">NistNet</a> is an open source Linux-based system for dedicated devices. The software has not been actively maintained for several years.</p>\n\n<p><strong>Commercial</strong></p>\n\n<p><a href=\"http://www.apposite-tech.com/\" rel=\"nofollow noreferrer\">Apposite Technoligies</a> sell dedicated hardware solutions for simulating WAN links, with a Web based GUI for configuring the settings and collecting traffic measurements</p>\n\n<p><a href=\"http://www.ecdata.com/compprof.htm\" rel=\"nofollow noreferrer\">East Coast DataCom</a> sell hardware dedicated simulators for simulating routers and modems</p>\n\n<p><a href=\"http://www.itrinegy.com/\" rel=\"nofollow noreferrer\">Itrinegy</a> offer both dedicated device solutions, and solutions for running on clients or servers.</p>\n\n<p><a href=\"http://www.networkfx.com/\" rel=\"nofollow noreferrer\">Network FX</a> offer several dedicated device products for simulating network impairments between the client &amp; server</p>\n\n<p><a href=\"http://www.netlimiter.com/\" rel=\"nofollow noreferrer\">NetLimiter</a> is a client side system that allows throttling of individual applications, and includes a firewall.</p>\n\n<p><a href=\"http://www.shunra.com/\" rel=\"nofollow noreferrer\">Shunra Software</a> offer a range of products, from high end enterprise WAN simulation and testing, to a simple client-resident emulator.</p>\n" }, { "answer_id": 401219, "author": "sammich", "author_id": 50276, "author_profile": "https://Stackoverflow.com/users/50276", "pm_score": 1, "selected": false, "text": "<p>As other people have mentioned, <a href=\"http://httpd.apache.org/docs/2.0/programs/ab.html\" rel=\"nofollow noreferrer\">Apache's ab</a> (comes with Apache, so you probably have it already) is good.</p>\n\n<p>Other good options are:</p>\n\n<ul>\n<li>HP's <a href=\"http://en.wikipedia.org/wiki/LoadRunner\" rel=\"nofollow noreferrer\">LoadRunner</a> Apache</li>\n<li>Jakarta's <a href=\"http://jakarta.apache.org/jmeter/\" rel=\"nofollow noreferrer\">JMeter</a></li>\n<li><a href=\"http://tsung.erlang-projects.org/\" rel=\"nofollow noreferrer\">Tsung</a> (if you want to get your erlang on)</li>\n</ul>\n\n<p>I personally like ab and JMeter the best.</p>\n" }, { "answer_id": 615894, "author": "devXen", "author_id": 50021, "author_profile": "https://Stackoverflow.com/users/50021", "pm_score": 1, "selected": false, "text": "<p>Web Application Stress Tool (WAST) from Microsoft is what you need.</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=e2c0585a-062a-439e-a67d-75a89aa36495&amp;displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=e2c0585a-062a-439e-a67d-75a89aa36495&amp;displaylang=en</a></p>\n" }, { "answer_id": 3359508, "author": "Assembler", "author_id": 5503, "author_profile": "https://Stackoverflow.com/users/5503", "pm_score": 1, "selected": false, "text": "<p>I haven't used it for years (lack of need, not because I'd found anything else), but <a href=\"http://www.xat.com/wo/index.html\" rel=\"nofollow noreferrer\">xat webspeed</a> would be the first thing I would point toward</p>\n" }, { "answer_id": 5868110, "author": "Maksim", "author_id": 735939, "author_profile": "https://Stackoverflow.com/users/735939", "pm_score": 0, "selected": false, "text": "<p>Do not forget about Wanulator (http://www.wanulator.de/).\nThe name Wanulator comes from \"WAN\" and \"simulator. This pretty much describes what the software does: It simulates different Internet conditions such as delay or packet loss. Furthermore it simulates user access line speeds e.g. modem, ISDN or ADSL.\nWanulator is currently packaged as a Linux boot CD based on SLAX. This will give you a full out of the box experience. You can turn any PC into a test-system within a blink - just by booting the Wanulator CD. The package already includes useful client SW such as web-browser and network sniffer (Wireshark). Nevertheless if the PC has 2 network interfaces the system can run as an intermediate system between your server and your client - as a switch - without any configuration hassles.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The application uses Oracle DataAccess ver. 1.1. , VS 2008, .Net Framework 3.5 w/SP1 ``` OracleConnection connection = new OracleConnection(ConnectionStringLogon); connection.Open(); OracleParameter selectParam = new OracleParameter(":applicationName", OracleDbType.Varchar2, 256); selectParam.Value = applicationName; if (connection.State != ConnectionState.Open) connection.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = connection; cmd.CommandText = "Select ApplicationId from Applications where AppName = 'appName'"; cmd.CommandType = CommandType.Text; if (selectParam != null) { cmd.Parameters.Add(selectParam); } object lookupResult = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if (lookupResult != null) ``` The procedure fails on object lookupResult = cmd.ExecuteScalar(); with this error: Event Type: Error Event Source: App Log Event Category: None Event ID: 9961 Date: 9/30/2008 Time: 4:42:11 PM User: N/A Computer: Server15 Description: System.NullReferenceException: Object reference not set to an instance of an object. at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior) at Oracle.DataAccess.Client.OracleCommand.ExecuteReader() at Oracle.DataAccess.Client.OracleCommand.ExecuteScalar() at Membership.OracleMembershipProvider.GetApplicationId(String applicationName, Boolean createIfNeeded) in OracleMembershipProvider.cs:line 1626 I've looked at this from every angle that I can conceive of... basically, no matter how I wrap it, the Execute fails.
if you're using apache you may want to take a look at [apache ab](http://httpd.apache.org/docs/2.0/programs/ab.html)
155,371
<p>I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back.</p> <p>I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe.</p> <p>Submitting the form results in HTTP that looks like: </p> <pre><code>Content-Type: multipart/form-data;boundary=&lt;boundary string&gt; Content-Length: &lt;length&gt; --&lt;boundary string&gt; Content-Disposition: form-data, name="&lt;input element name&gt;" &lt;input element value&gt; --&lt;boundary string&gt; Content-Disposition: form-data, name=&lt;input element name&gt;"; filename="&lt;input element value&gt;" Content-Type: application/octet-stream &lt;element body&gt; </code></pre> <p>How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream?</p>
[ { "answer_id": 155429, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 0, "selected": false, "text": "<p>I don't see why iframe (an invisible one) implies XHTML and not ANY content. If you use an iframe you can set the onreadystatechange event and wait for 'complete'. Next you could use frame.window.document.innerHTML (please someone correct me) to get the string result.</p>\n\n<pre><code>var lFrame = document.getElementById('myframe');\nlFrame.onreadystatechange = function()\n{\n if (lFrame.readyState == 'complete')\n {\n // your frame is done, get the content...\n }\n};\n</code></pre>\n" }, { "answer_id": 155430, "author": "TonyB", "author_id": 3543, "author_profile": "https://Stackoverflow.com/users/3543", "pm_score": 3, "selected": false, "text": "<p>There isn't any way to access a file input field inside javascript so there isn't a javascript only solution for ajax file uploads.</p>\n\n<p>There are workaround like <a href=\"http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html\" rel=\"nofollow noreferrer\">using an iframe</a>. </p>\n\n<p>The other option would be to use something like <a href=\"http://www.swfupload.org/\" rel=\"nofollow noreferrer\">SWFUpload</a> or <a href=\"http://ajaxian.com/archives/youtube-uploader-now-using-gears-and-what-people-missed-in-gears-04\" rel=\"nofollow noreferrer\">Google Gears</a></p>\n" }, { "answer_id": 155441, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "<p>You will need to POST to an IFrame to get this to work, simply add a target attribute to your form, where you specify the IFrame ID. Something like this:</p>\n\n<pre>\n<code>\n&lt;form method=\"post\" target=\"myiframe\" action=\"handler.php\">\n...\n&lt;/form>\n&lt;iframe id=\"myiframe\" style=\"display:none\" />\n</code>\n</pre>\n" }, { "answer_id": 170789, "author": "Komang", "author_id": 19463, "author_profile": "https://Stackoverflow.com/users/19463", "pm_score": 0, "selected": false, "text": "<p>i am confuse about the onload event that you specified, it is on the page or on iframe?, \nthe first answer is correct theres no way to do this using purely xmlhttprequest, if what you want to acheive is triggering some method once the response exist on iframe, simply check if it has content already or not using DOM scripting, then fire the method.</p>\n\n<p>to attach onload event to the iframe</p>\n\n<pre><code>if(window.attachEvent){\n document.getElementById(iframe).attachEvent('onload', some_method);\n}else{\n document.getElementById(iframe).addEventListener('load', some_method, false);\n} \n</code></pre>\n" }, { "answer_id": 4240940, "author": "Alex Polo", "author_id": 514852, "author_profile": "https://Stackoverflow.com/users/514852", "pm_score": 6, "selected": true, "text": "<p>You can construct the 'multipart/form-data' request yourself (read more about it at <a href=\"http://www.faqs.org/rfcs/rfc2388.html\" rel=\"noreferrer\">http://www.faqs.org/rfcs/rfc2388.html</a>) and then use the <code>send</code> method (ie. xhr.send(your-multipart-form-data)). Similarly, but easier, in Firefox 4+ (also in Chrome 5+ and Safari 5+) you can use the <a href=\"http://hacks.mozilla.org/2010/07/firefox-4-formdata-and-the-new-file-url-object/\" rel=\"noreferrer\">FormData</a> interface that helps to construct such requests. The <code>send</code> method is good for text content but if you want to send binary data such as images, you can do it with the help of the <code>sendAsBinary</code> method that has been around starting with Firefox 3.0. For details on how to send files via <code>XMLHttpRequest</code>, please refer to <a href=\"http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html\" rel=\"noreferrer\">http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html</a>.</p>\n" }, { "answer_id": 6523168, "author": "Aldekein", "author_id": 162118, "author_profile": "https://Stackoverflow.com/users/162118", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Content-Disposition: form-data, name</p>\n</blockquote>\n\n<p>You should use semicolon, like this: Content-Disposition: form-data; name</p>\n" }, { "answer_id": 48043063, "author": "Romuald Brunet", "author_id": 286182, "author_profile": "https://Stackoverflow.com/users/286182", "pm_score": 0, "selected": false, "text": "<p>Here is an up to date way using FormData (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects\" rel=\"nofollow noreferrer\">full doc @MDN</a>)</p>\n\n<p>Script:</p>\n\n<pre><code>var form = document.querySelector('#myForm');\nform.addEventListener(\"submit\", function(e) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"POST\", this.action);\n xhr.addEventListener(\"load\", function(e) {\n // Your callback\n });\n\n xhr.send(new FormData(this));\n\n e.preventDefault();\n});\n</code></pre>\n\n<p>(from this basic form)</p>\n\n<pre><code>&lt;form id=\"myForm\" action=\"...\" method=\"POST\" enctype=\"multipart/form-data\"&gt;\n &lt;input type=\"file\" name=\"file0\"&gt;\n &lt;input type=\"text\" name=\"some-text\"&gt;\n ...\n&lt;/form&gt;\n</code></pre>\n\n<p>Thanks again to Alex Polo for his answer</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14405/" ]
I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back. I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe. Submitting the form results in HTTP that looks like: ``` Content-Type: multipart/form-data;boundary=<boundary string> Content-Length: <length> --<boundary string> Content-Disposition: form-data, name="<input element name>" <input element value> --<boundary string> Content-Disposition: form-data, name=<input element name>"; filename="<input element value>" Content-Type: application/octet-stream <element body> ``` How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream?
You can construct the 'multipart/form-data' request yourself (read more about it at <http://www.faqs.org/rfcs/rfc2388.html>) and then use the `send` method (ie. xhr.send(your-multipart-form-data)). Similarly, but easier, in Firefox 4+ (also in Chrome 5+ and Safari 5+) you can use the [FormData](http://hacks.mozilla.org/2010/07/firefox-4-formdata-and-the-new-file-url-object/) interface that helps to construct such requests. The `send` method is good for text content but if you want to send binary data such as images, you can do it with the help of the `sendAsBinary` method that has been around starting with Firefox 3.0. For details on how to send files via `XMLHttpRequest`, please refer to <http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html>.
155,375
<p>I'm working with a datagrid and adapter that correspond with an MSAccess table through a stored query (named "UpdatePaid", 3 paramaters as shown below) like so:</p> <pre><code> OleDbCommand odc = new OleDbCommand("UpdatePaid", connection); OleDbParameter param; odc.CommandType = CommandType.StoredProcedure; param = odc.Parameters.Add("v_iid", OleDbType.Double); param.SourceColumn = "I"; param.SourceVersion = DataRowVersion.Original; param = odc.Parameters.Add("v_pd", OleDbType.Boolean); param.SourceColumn = "Paid"; param.SourceVersion = DataRowVersion.Current; param = odc.Parameters.Add("v_Projected", OleDbType.Currency); param.SourceColumn = "ProjectedCost"; param.SourceVersion = DataRowVersion.Current; odc.Prepare(); myAdapter.UpdateCommand = odc; ... myAdapter.Update(); </code></pre> <p>It works fine...but the really weird thing is that it <em>didn't</em> until I put in the <strong>odc.Prepare()</strong> call.<br><br>My question is thus: Do I need to do that all the time when working with OleDb stored procs/queries? Why? I also have another project coming up where I'll have to do the same thing with a SqlDbCommand... do I have to do it with those, too? </p>
[ { "answer_id": 155561, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 0, "selected": false, "text": "<p>I don't use it with SqlDbCommand. It seems as a bug to me that it's <em>required</em>. It should only be <em>nice to have</em> if you're going to call a procedure multiple times in a row. Maybe I'm wrong and there's a note in documentation about providers that love this call too much.</p>\n" }, { "answer_id": 155571, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 0, "selected": false, "text": "<p>Are you using the JET OLEDB Provider? or MSDASQL + JET ODBC?</p>\n\n<p>You should not need to call <code>Prepare()</code>, but I believe that's driver/provider dependent.</p>\n\n<p>You definitely don't need to use <code>Prepare()</code> for <code>System.Data.SqlClient</code>.</p>\n" }, { "answer_id": 156242, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 3, "selected": true, "text": "<p>This is called, oddly enough, a prepared statement, and they're actually really nice. Basically what happens is you either create or get a sql statement (insert, delete, update) and instead of passing actual values, you pass \"?\" as a place holder. This is all well and good, except what we want is our values to get passed in instead of the \"?\". </p>\n\n<p>So we prepare the statement so instead of \"?\", we pass in parameters as you have above that are going to be the values that go in in place of the place holders.</p>\n\n<p>Preparing parses the string to find where parameters can replace the question marks so all you have to do is enter the parameter data and execute the command.</p>\n\n<p>Within oleDB, stored queries are prepared statements, so a prepare is required. I've not used stored queries with SqlDB, so I'd have to defer to the 2 answers previous.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13776/" ]
I'm working with a datagrid and adapter that correspond with an MSAccess table through a stored query (named "UpdatePaid", 3 paramaters as shown below) like so: ``` OleDbCommand odc = new OleDbCommand("UpdatePaid", connection); OleDbParameter param; odc.CommandType = CommandType.StoredProcedure; param = odc.Parameters.Add("v_iid", OleDbType.Double); param.SourceColumn = "I"; param.SourceVersion = DataRowVersion.Original; param = odc.Parameters.Add("v_pd", OleDbType.Boolean); param.SourceColumn = "Paid"; param.SourceVersion = DataRowVersion.Current; param = odc.Parameters.Add("v_Projected", OleDbType.Currency); param.SourceColumn = "ProjectedCost"; param.SourceVersion = DataRowVersion.Current; odc.Prepare(); myAdapter.UpdateCommand = odc; ... myAdapter.Update(); ``` It works fine...but the really weird thing is that it *didn't* until I put in the **odc.Prepare()** call. My question is thus: Do I need to do that all the time when working with OleDb stored procs/queries? Why? I also have another project coming up where I'll have to do the same thing with a SqlDbCommand... do I have to do it with those, too?
This is called, oddly enough, a prepared statement, and they're actually really nice. Basically what happens is you either create or get a sql statement (insert, delete, update) and instead of passing actual values, you pass "?" as a place holder. This is all well and good, except what we want is our values to get passed in instead of the "?". So we prepare the statement so instead of "?", we pass in parameters as you have above that are going to be the values that go in in place of the place holders. Preparing parses the string to find where parameters can replace the question marks so all you have to do is enter the parameter data and execute the command. Within oleDB, stored queries are prepared statements, so a prepare is required. I've not used stored queries with SqlDB, so I'd have to defer to the 2 answers previous.
155,388
<p>Suppose that I have interface MyInterface and 2 classes A, B which implement MyInterface.<br> I declared 2 objects: <code>MyInterface a = new A()</code> , and <code>MyInterface b = new B()</code>.<br> When I try to pass to a function - function <code>doSomething(A a){}</code> I am getting an error.</p> <p>This is my code:</p> <pre><code>public interface MyInterface {} public class A implements MyInterface{} public class B implements MyInterface{} public class Tester { public static void main(String[] args){ MyInterface a = new A(); MyInterface b = new B(); test(b); } public static void test(A a){ System.out.println("A"); } public static void test(B b){ System.out.println("B"); } } </code></pre> <p>My problem is that I am getting from some component interface which can be all sorts of classes and I need to write function for each class.<br> So one way is to get interface and to check which type is it. (instance of A)</p> <p>I would like to know how others deal with this problem??</p> <p>Thx</p>
[ { "answer_id": 155411, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 2, "selected": false, "text": "<p>I'm unclear on what you're actually asking, but the problem is that you don't have a method that takes a parameter of type MyInterface. I don't know what the exact syntax is in Java, but you could do something like if (b is B) { test(b as B) } but I wouldn't. If you need it to be generic, then use the MyInterface type as the variable type, otherwise use B as the variable type. You're defeating the purpose of using the interface.</p>\n" }, { "answer_id": 155414, "author": "marcj", "author_id": 23940, "author_profile": "https://Stackoverflow.com/users/23940", "pm_score": 3, "selected": false, "text": "<p>Can you not just have a method on the interface which each class implements? Or do you not have control of the interface? </p>\n\n<p>This would provide both polymorphism and avoid the need to define any external methods. I believe this is the intention of an interface, it allows a client to treat all classes implementing it in a non type specific manner.</p>\n\n<p>If you cannot add to the interface then you would be best introducing a second interface with the appropriate method. If you cannot edit either the interface or the classes then you need a method which has the interface as a parameter and then check for the concrete class. However this should be a last resort and rather subverts the use of the interface and ties the method to all the implementations.</p>\n" }, { "answer_id": 155417, "author": "perimosocordiae", "author_id": 10601, "author_profile": "https://Stackoverflow.com/users/10601", "pm_score": 0, "selected": false, "text": "<p>I usually use an abstract class to get around this problem, like so:\n\n<blockquote>\n <p><code>public abstract class Parent {}</code><br>\n <code>public class A extends Parent {...}</code><br>\n <code>public class B extends Parent {...}</code></p>\n</blockquote>\n\n<p>That allows you to pass Parent objects to functions that take A or B.</p>\n" }, { "answer_id": 155418, "author": "Goran", "author_id": 23164, "author_profile": "https://Stackoverflow.com/users/23164", "pm_score": 1, "selected": false, "text": "<p>I think visitor <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">design pattern</a> will help you out here. The basic idea is to have your classes (A and B) call the appropriate method themselves instead of you trying to decide which method to call. Being a C# guy I hope my Java works:</p>\n\n<pre><code>public interface Visitable { \n void accept(Tester tester) \n}\n\npublic interface MyInterface implements Visitable { \n}\n\npublic class A implements MyInterface{\n public void accept(Tester tester){\n tester.test(this);\n }\n}\n\npublic class B implements MyInterface{\n public void accept(Tester tester){\n tester.test(this);\n }\n}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n a.accept(this);\n b.accept(this);\n }\n\n public void test(A a){\n System.out.println(\"A\");\n }\n\n public void test(B b){\n System.out.println(\"B\");\n }\n\n}\n</code></pre>\n" }, { "answer_id": 155428, "author": "parkerfath", "author_id": 6027, "author_profile": "https://Stackoverflow.com/users/6027", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if I fully understand the issue, but it seems like one way might be to move the test() methods into the child classes:</p>\n\n<pre><code>public interface MyInterface { \n public void test();\n}\n\npublic class A implements MyInterface{\n public void test() {\n System.out.println(\"A\");\n }\n}\n\npublic class B implements MyInterface{\n public void test() {\n System.out.println(\"B\");\n }\n}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n b.test();\n }\n}\n</code></pre>\n\n<p>You could similarly use a toString() method and print the result of that. I can't quite tell from the question, though, if your requirements make this impossible.</p>\n" }, { "answer_id": 155439, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 2, "selected": false, "text": "<p>It sounds like you are after something like this:</p>\n\n<pre><code>public static void test(MyInterface obj){\n if(obj instanceof A) {\n A tmp = (A)obj;\n } else if(obj instanceof B) {\n B tmp = (B)obj;\n } else {\n //handle error condition\n }\n}\n</code></pre>\n\n<p>But please note this is very bad form and indicates something has gone seriously wrong in your design. If you don't have control of the interface then, as suggested by marcj, adding a second interface might be the way to go. Note you can do this whilst preserving binary compatibility.</p>\n" }, { "answer_id": 155455, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 0, "selected": false, "text": "<p>You have 3 options:</p>\n\n<ol>\n<li>Visitor pattern; you'll need to be able to change the MyInterface type to include a method <code>visit(Visitor)</code> where the <code>Visitor</code> class contains lots of methods for visiting each subclass.</li>\n<li>Use <code>if-else</code> inside your method <code>test(MyInterface)</code> to check between them</li>\n<li>Use chaining. That is, declare handlers <code>ATester</code>, <code>BTester</code> etc, all of which implement the interface <code>ITester</code> which has the method <code>test(MyInterface)</code>. Then in the <code>ATester</code>, check that the type is equal to A before doing stuff. Then your main Tester class can have a chain of these testers and pass each <code>MyInterface</code> instance down the chain, until it reaches an <code>ITester</code> which can handle it. This is basically turning the <code>if-else</code> block from 2 into separate classes.</li>\n</ol>\n\n<p>Personally I would go for 2 in most situations. Java lacks true object-orientation. Deal with it! Coming up with various ways around it usually just makes for difficult-to-follow code.</p>\n" }, { "answer_id": 156266, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 0, "selected": false, "text": "<p>Sounds like you need either a) to leverage polymorphism by putting method on MyInterface and implementing in A and B or b) some combination of Composite and Visitor design pattern. I'd start with a) and head towards b) when things get unwieldy.</p>\n\n<p>My extensive thoughts on Visitor:</p>\n\n<p><a href=\"http://tech.puredanger.com/2007/07/16/visitor/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2007/07/16/visitor/</a></p>\n" }, { "answer_id": 11116219, "author": "harika", "author_id": 1468679, "author_profile": "https://Stackoverflow.com/users/1468679", "pm_score": 1, "selected": false, "text": "<p>Use only one public class/interface in one .java file, otherwise it'll throw error. And call the object with the object name.. You declared two methos in Teater class only, then what the purpose of declaring class A,B.</p>\n" }, { "answer_id": 16544865, "author": "AllTooSir", "author_id": 1163607, "author_profile": "https://Stackoverflow.com/users/1163607", "pm_score": 0, "selected": false, "text": "<pre><code>public interface MyInterface {}\n\npublic class A implements MyInterface{}\n\npublic class B implements MyInterface{}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n test(b); // this is wrong\n }\n\n public static void test(A a){\n System.out.println(\"A\");\n }\n\n public static void test(B b){\n System.out.println(\"B\");\n }\n\n}\n</code></pre>\n\n<p>You are trying to pass an object referenced by <code>MyInterface</code> reference variable to a method defined with an argument with its sub type like <code>test(B b)</code>. Compiler complains here because the <code>MyInterface</code> reference variable can reference any object which is a sub type of <code>MyInterface</code>, but not necessarily an object of <code>B</code>.There can be runtime errors if this is allowed in Java. Take an example which will make the concept clearer for you. I have modified your code for class <code>B</code> and added a method.</p>\n\n<pre><code>public class B implements MyInterface {\n public void onlyBCanInvokeThis() {}\n\n}\n</code></pre>\n\n<p>Now just alter the <code>test(B b)</code> method like below :</p>\n\n<pre><code>public static void test(B b){\n b.onlyBCanInvokeThis();\n System.out.println(\"B\");\n}\n</code></pre>\n\n<p>This code will blow up at runtime if allowed by compiler:</p>\n\n<pre><code> MyInterface a = new A();\n // since a is of type A. invoking onlyBCanInvokeThis()\n // inside test() method on a will throw exception.\n test(a); \n</code></pre>\n\n<p>To prevent this, compiler disallows such method invocation techniques with super class reference.</p>\n\n<hr>\n\n<p>I'm not sure what are you trying to achieve but it seems like you want to achieve runtime polymorphism. To achieve that you need to declare a method in your <code>MyInterface</code> and implement it in each of the subclass. This way the call to the method will be resolved at run time based on the object type and not on the reference type.</p>\n\n<pre><code>public interface MyInterface { \n public void test();\n}\n\npublic class A implements MyInterface{\n public void test() {\n System.out.println(\"A\");\n }\n}\n\npublic class B implements MyInterface{\n public void test() {\n System.out.println(\"B\");\n }\n}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n b.test(); // calls B's implementation of test()\n }\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23968/" ]
Suppose that I have interface MyInterface and 2 classes A, B which implement MyInterface. I declared 2 objects: `MyInterface a = new A()` , and `MyInterface b = new B()`. When I try to pass to a function - function `doSomething(A a){}` I am getting an error. This is my code: ``` public interface MyInterface {} public class A implements MyInterface{} public class B implements MyInterface{} public class Tester { public static void main(String[] args){ MyInterface a = new A(); MyInterface b = new B(); test(b); } public static void test(A a){ System.out.println("A"); } public static void test(B b){ System.out.println("B"); } } ``` My problem is that I am getting from some component interface which can be all sorts of classes and I need to write function for each class. So one way is to get interface and to check which type is it. (instance of A) I would like to know how others deal with this problem?? Thx
Can you not just have a method on the interface which each class implements? Or do you not have control of the interface? This would provide both polymorphism and avoid the need to define any external methods. I believe this is the intention of an interface, it allows a client to treat all classes implementing it in a non type specific manner. If you cannot add to the interface then you would be best introducing a second interface with the appropriate method. If you cannot edit either the interface or the classes then you need a method which has the interface as a parameter and then check for the concrete class. However this should be a last resort and rather subverts the use of the interface and ties the method to all the implementations.
155,391
<p>What is the difference between a BitmapFrame and BitmapImage in WPF? Where would you use each (ie. why would you use a BitmapFrame rather than a BitmapImage?)</p>
[ { "answer_id": 155433, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 5, "selected": true, "text": "<p>You should stick to using the abstract class <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx\" rel=\"noreferrer\">BitmapSource</a> if you need to get at the bits, or even <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx\" rel=\"noreferrer\">ImageSource</a> if you just want to draw it.</p>\n\n<p>The implementation BitmapFrame is just the object oriented nature of the implementation showing through. You shouldn't really have any need to distinguish between the implementations. BitmapFrames may contain a little extra information (metadata), but usually nothing but an imaging app would care about.</p>\n\n<p>You'll notice these other classes that inherit from BitmapSource:</p>\n\n<ul>\n<li>BitmapFrame</li>\n<li>BitmapImage</li>\n<li>CachedBitmap</li>\n<li>ColorConvertedBitmap</li>\n<li>CroppedBitmap</li>\n<li>FormatConvertedBitmap</li>\n<li>RenderTargetBitmap</li>\n<li>TransformedBitmap</li>\n<li>WriteableBitmap</li>\n</ul>\n\n<p>You can get a BitmapSource from a URI by constructing a BitmapImage object:</p>\n\n<pre><code>Uri uri = ...;\nBitmapSource bmp = new BitmapImage(uri);\nConsole.WriteLine(\"{0}x{1}\", bmp.PixelWIdth, bmp.PixelHeight);\n</code></pre>\n\n<p>The BitmapSource could also come from a decoder. In this case you are indirectly using BitmapFrames.</p>\n\n<pre><code>Uri uri = ...;\nBitmapDecoder dec = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.Default);\nBitmapSource bmp = dec.Frames[0];\nConsole.WriteLine(\"{0}x{1}\", bmp.PixelWIdth, bmp.PixelHeight);\n</code></pre>\n" }, { "answer_id": 155478, "author": "ligaz", "author_id": 6409, "author_profile": "https://Stackoverflow.com/users/6409", "pm_score": 1, "selected": false, "text": "<p>BitmapFrame is a low level primitive for image manipulation. It is usually used when you want to encode/decode some image from one format to another.</p>\n\n<p>BitmapImage is more high level abstraction that has some neat data-binding properties (UriSource, etc).</p>\n\n<p>If you are just displaying images and want some fine tuning BitmapImage is what you need.</p>\n\n<p>If you are doing low level image manipulation then you will need BitmapFrame.</p>\n" }, { "answer_id": 24946309, "author": "stritch000", "author_id": 436717, "author_profile": "https://Stackoverflow.com/users/436717", "pm_score": 2, "selected": false, "text": "<p>The accepted answer is incomplete (not to suggest that my answer is complete either) and my addition may help someone somewhere.</p>\n\n<p>The reason (albeit the <em>only</em> reason) I use a BitmapFrame is when I access the individual frames of a multiple-framed TIFF image using the <code>TiffBitmapDecoder</code> class. For example,</p>\n\n<pre><code>TiffBitmapDecoder decoder = new TiffBitmapDecoder(\n new Uri(filename), \n BitmapCreateOptions.None, \n BitmapCacheOption.None);\n\nfor (int frameIndex = 0; frameIndex &lt; decoder.Frames.Count; frameIndex++)\n{\n BitmapFrame frame = decoder.Frames[frameIndex];\n // Do something with the frame\n // (it inherits from BitmapSource, so the options are wide open)\n}\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
What is the difference between a BitmapFrame and BitmapImage in WPF? Where would you use each (ie. why would you use a BitmapFrame rather than a BitmapImage?)
You should stick to using the abstract class [BitmapSource](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx) if you need to get at the bits, or even [ImageSource](http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx) if you just want to draw it. The implementation BitmapFrame is just the object oriented nature of the implementation showing through. You shouldn't really have any need to distinguish between the implementations. BitmapFrames may contain a little extra information (metadata), but usually nothing but an imaging app would care about. You'll notice these other classes that inherit from BitmapSource: * BitmapFrame * BitmapImage * CachedBitmap * ColorConvertedBitmap * CroppedBitmap * FormatConvertedBitmap * RenderTargetBitmap * TransformedBitmap * WriteableBitmap You can get a BitmapSource from a URI by constructing a BitmapImage object: ``` Uri uri = ...; BitmapSource bmp = new BitmapImage(uri); Console.WriteLine("{0}x{1}", bmp.PixelWIdth, bmp.PixelHeight); ``` The BitmapSource could also come from a decoder. In this case you are indirectly using BitmapFrames. ``` Uri uri = ...; BitmapDecoder dec = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapSource bmp = dec.Frames[0]; Console.WriteLine("{0}x{1}", bmp.PixelWIdth, bmp.PixelHeight); ```
155,427
<p>I have a form element that I want to address via javascript, but it doesn't like the syntax.</p> <pre><code>&lt;form name="mycache"&gt; &lt;input type="hidden" name="cache[m][2]"&gt; &lt;!-- ... --&gt; &lt;/form&gt; </code></pre> <p>I want to be able to say:</p> <pre><code>document.mycache.cache[m][2] </code></pre> <p>but obviously I need to indicate that <code>cache[m][2]</code> is the whole name, and not an array reference to <code>cache</code>. Can it be done?</p>
[ { "answer_id": 155437, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 3, "selected": true, "text": "<p>UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.</p>\n\n<p>Here's some code that proves it:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n\n&lt;form id=\"form1\"&gt;\n\n&lt;input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/&gt;\n\n&lt;input type='button' value='Test' onclick='showtest();'/&gt;\n\n&lt;script type=\"text/javascript\"&gt;\nfunction showtest() {\n var value = document.getElementById(\"field[m][2]\").value;\n alert(value);\n}\n&lt;/script&gt;\n\n&lt;/form&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Update: You can also use the following to get the value from the form element:</p>\n\n<pre><code>var value = document.forms.form1[\"field[m][2]\"].value;\n</code></pre>\n" }, { "answer_id": 155438, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Is it possible to add an id reference to the form element and use document.getElementById?</p>\n" }, { "answer_id": 155446, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "<p>Use <code>document.getElementsByName(\"input_name\")</code> instead. Cross platform too. Win.</p>\n" }, { "answer_id": 156153, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 1, "selected": false, "text": "<p>-- and in the old days (in HTML3.2/4.01 transitional/XHTML1.0 transitional DOM-binding) you could use:</p>\n\n<pre><code>form.elements[\"cache[m][2]\"]\n</code></pre>\n\n<p>-- but the elements-stuff is, as Chris Pietschmann showed, not necessary as these binding-schemes also allow direct access (though I personally would prefer the extra readability !-)</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14253/" ]
I have a form element that I want to address via javascript, but it doesn't like the syntax. ``` <form name="mycache"> <input type="hidden" name="cache[m][2]"> <!-- ... --> </form> ``` I want to be able to say: ``` document.mycache.cache[m][2] ``` but obviously I need to indicate that `cache[m][2]` is the whole name, and not an array reference to `cache`. Can it be done?
UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute. Here's some code that proves it: ``` <html> <body> <form id="form1"> <input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/> <input type='button' value='Test' onclick='showtest();'/> <script type="text/javascript"> function showtest() { var value = document.getElementById("field[m][2]").value; alert(value); } </script> </form> </body> </html> ``` Update: You can also use the following to get the value from the form element: ``` var value = document.forms.form1["field[m][2]"].value; ```
155,435
<p>In JavaScript, you can do this:</p> <pre><code>var a = null; var b = "I'm a value"; var c = null; var result = a || b || c; </code></pre> <p>And 'result' will get the value of 'b' because JavaScript short-circuits the 'or' operator.</p> <p>I want a one-line idiom to do this in ColdFusion and the best I can come up with is:</p> <pre><code>&lt;cfif LEN(c) GT 0&gt;&lt;cfset result=c&gt;&lt;/cfif&gt; &lt;cfif LEN(b) GT 0&gt;&lt;cfset result=b&gt;&lt;/cfif&gt; &lt;cfif LEN(a) GT 0&gt;&lt;cfset result=a&gt;&lt;/cfif&gt; </code></pre> <p>Can anyone do any better than this?</p>
[ { "answer_id": 155529, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 4, "selected": true, "text": "<p>ColdFusion doesn't have nulls.</p>\n\n<p>Your example is basing the choice on which item is an empty string.</p>\n\n<p>If that is what you're after, and all your other values are simple values, you can do this:</p>\n\n<pre><code>&lt;cfset result = ListFirst( \"#a#,#b#,#c#\" )/&gt;\n</code></pre>\n\n<p>(Which works because the standard list functions ignore empty elements.)</p>\n" }, { "answer_id": 155550, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<p>Note: other CFML engines do support nulls.</p>\n\n<p>If we really are dealing with nulls (and not empty strings), here is a function that will work for Railo and OpenBlueDragon:</p>\n\n<pre><code>&lt;cffunction name=\"FirstNotNull\" returntype=\"any\" output=\"false\"&gt;\n &lt;cfset var i = 0/&gt;\n &lt;cfloop index=\"i\" from=\"1\" to=\"#ArrayLen(Arguments)#\"&gt;\n &lt;cfif NOT isNull(Arguments[i]) &gt;\n &lt;cfreturn Arguments[i] /&gt;\n &lt;/cfif&gt;\n &lt;/cfloop&gt;\n&lt;/cffunction&gt;\n</code></pre>\n\n<p>Then to use the function is as simple as:</p>\n\n<pre><code>&lt;cfset result = FirstNotNull( a , b , c ) /&gt;\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13958/" ]
In JavaScript, you can do this: ``` var a = null; var b = "I'm a value"; var c = null; var result = a || b || c; ``` And 'result' will get the value of 'b' because JavaScript short-circuits the 'or' operator. I want a one-line idiom to do this in ColdFusion and the best I can come up with is: ``` <cfif LEN(c) GT 0><cfset result=c></cfif> <cfif LEN(b) GT 0><cfset result=b></cfif> <cfif LEN(a) GT 0><cfset result=a></cfif> ``` Can anyone do any better than this?
ColdFusion doesn't have nulls. Your example is basing the choice on which item is an empty string. If that is what you're after, and all your other values are simple values, you can do this: ``` <cfset result = ListFirst( "#a#,#b#,#c#" )/> ``` (Which works because the standard list functions ignore empty elements.)
155,449
<p>Right now I have the following in my <code>.vimrc</code>:</p> <pre><code>au BufWritePost *.c,*.cpp,*.h !ctags -R </code></pre> <p>There are a few problems with this:</p> <ol> <li>It's slow -- regenerates tags for files that haven't changed since the last tag generation.</li> <li>I have to push the enter button <em>again</em> after writing the file because of an inevitable "press Enter or type command to continue".</li> </ol> <p>When you combine these two issues I end up pushing the additional enter too soon (before <code>ctags -R</code> has finished), then see the annoying error message, and have to push enter again.</p> <p>I know it doesn't sound like a big deal, but with the amount of file writes I do on a given day it tends to get really annoying. There's gotta be a better way to do it!</p>
[ { "answer_id": 155477, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 2, "selected": false, "text": "<p>How about having ctags scheduled to run via crontab? If your project tree is fairly stable in it's structure, that should be doable?</p>\n" }, { "answer_id": 155497, "author": "tonylo", "author_id": 4071, "author_profile": "https://Stackoverflow.com/users/4071", "pm_score": 2, "selected": false, "text": "<p>Perhaps use the append argument to ctags as demonstrated by:</p>\n\n<p><a href=\"http://vim.wikia.com/wiki/Autocmd_to_update_ctags_file\" rel=\"nofollow noreferrer\">http://vim.wikia.com/wiki/Autocmd_to_update_ctags_file</a></p>\n\n<p>I can't really vouch for this as I generally use source insight for code browsing, but use vim as an editor... go figure.</p>\n" }, { "answer_id": 155506, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>To suppress the \"press enter\" prompt, use <a href=\"http://vim.wikia.com/wiki/Avoiding_the_%22Hit_ENTER_to_continue%22_prompts\" rel=\"nofollow noreferrer\">:silent</a>.</p>\n" }, { "answer_id": 155515, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 7, "selected": true, "text": "<p><code>au BufWritePost *.c,*.cpp,*.h silent! !ctags -R &amp;</code></p>\n\n<p>The downside is that you won't have a useful tags file until it completes. As long as you're on a *nix system it should be ok to do multiple writes before the previous ctags has completed, but you should test that. On a Windows system it won't put it in the background and it'll complain that the file is locked until the first ctags finishes (which shouldn't cause problems in vim, but you'll end up with a slightly outdated tags file).</p>\n\n<p>Note, you could use the <code>--append</code> option as tonylo suggests, but then you'll have to disable <code>tagbsearch</code> which could mean that tag searches take a lot longer, depending on the size of your tag file.</p>\n" }, { "answer_id": 156781, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 1, "selected": false, "text": "<p>The <code>--append</code> option is indeed the way to go. Used with a <code>grep -v</code>, we can update only one <em>tagged</em> file. For instance, here is a excerpt of an <a href=\"https://github.com/LucHermitte/lh-tags\" rel=\"nofollow noreferrer\">unpolished plugin</a> that addresses this issue. (NB: It will require an \"external\" <a href=\"https://github.com/LucHermitte/lh-vim-lib\" rel=\"nofollow noreferrer\">library plugin</a>)</p>\n\n<pre><code>\" Options {{{1\nlet g:tags_options_cpp = '--c++-kinds=+p --fields=+imaS --extra=+q'\n\nfunction! s:CtagsExecutable()\n let tags_executable = lh#option#Get('tags_executable', s:tags_executable, 'bg')\n return tags_executable\nendfunction\n\nfunction! s:CtagsOptions()\n let ctags_options = lh#option#Get('tags_options_'.&amp;ft, '')\n let ctags_options .= ' '.lh#option#Get('tags_options', '', 'wbg')\n return ctags_options\nendfunction\n\nfunction! s:CtagsDirname()\n let ctags_dirname = lh#option#Get('tags_dirname', '', 'b').'/'\n return ctags_dirname\nendfunction\n\nfunction! s:CtagsFilename()\n let ctags_filename = lh#option#Get('tags_filename', 'tags', 'bg')\n return ctags_filename\nendfunction\n\nfunction! s:CtagsCmdLine(ctags_pathname)\n let cmd_line = s:CtagsExecutable().' '.s:CtagsOptions().' -f '.a:ctags_pathname\n return cmd_line\nendfunction\n\n\n\" ######################################################################\n\" Tag generating functions {{{1\n\" ======================================================================\n\" Interface {{{2\n\" ======================================================================\n\" Mappings {{{3\n\" inoremap &lt;expr&gt; ; &lt;sid&gt;Run('UpdateTags_for_ModifiedFile',';')\n\nnnoremap &lt;silent&gt; &lt;Plug&gt;CTagsUpdateCurrent :call &lt;sid&gt;UpdateCurrent()&lt;cr&gt;\nif !hasmapto('&lt;Plug&gt;CTagsUpdateCurrent', 'n')\n nmap &lt;silent&gt; &lt;c-x&gt;tc &lt;Plug&gt;CTagsUpdateCurrent\nendif\n\nnnoremap &lt;silent&gt; &lt;Plug&gt;CTagsUpdateAll :call &lt;sid&gt;UpdateAll()&lt;cr&gt;\nif !hasmapto('&lt;Plug&gt;CTagsUpdateAll', 'n')\n nmap &lt;silent&gt; &lt;c-x&gt;ta &lt;Plug&gt;CTagsUpdateAll\nendif\n\n\n\" ======================================================================\n\" Auto command for automatically tagging a file when saved {{{3\naugroup LH_TAGS\n au!\n autocmd BufWritePost,FileWritePost * if ! lh#option#Get('LHT_no_auto', 0) | call s:Run('UpdateTags_for_SavedFile') | endif\naug END\n\n\" ======================================================================\n\" Internal functions {{{2\n\" ======================================================================\n\" generate tags on-the-fly {{{3\nfunction! UpdateTags_for_ModifiedFile(ctags_pathname)\n let source_name = expand('%')\n let temp_name = tempname()\n let temp_tags = tempname()\n\n \" 1- purge old references to the source name\n if filereadable(a:ctags_pathname)\n \" it exists =&gt; must be changed\n call system('grep -v \" '.source_name.' \" '.a:ctags_pathname.' &gt; '.temp_tags.\n \\ ' &amp;&amp; mv -f '.temp_tags.' '.a:ctags_pathname)\n endif\n\n \" 2- save the unsaved contents of the current file\n call writefile(getline(1, '$'), temp_name, 'b')\n\n \" 3- call ctags, and replace references to the temporary source file to the\n \" real source file\n let cmd_line = s:CtagsCmdLine(a:ctags_pathname).' '.source_name.' --append'\n let cmd_line .= ' &amp;&amp; sed \"s#\\t'.temp_name.'\\t#\\t'.source_name.'\\t#\" &gt; '.temp_tags\n let cmd_line .= ' &amp;&amp; mv -f '.temp_tags.' '.a:ctags_pathname\n call system(cmd_line)\n call delete(temp_name)\n\n return ';'\nendfunction\n\n\" ======================================================================\n\" generate tags for all files {{{3\nfunction! s:UpdateTags_for_All(ctags_pathname)\n call delete(a:ctags_pathname)\n let cmd_line = 'cd '.s:CtagsDirname()\n \" todo =&gt; use project directory\n \"\n let cmd_line .= ' &amp;&amp; '.s:CtagsCmdLine(a:ctags_pathname).' -R'\n echo cmd_line\n call system(cmd_line)\nendfunction\n\n\" ======================================================================\n\" generate tags for the current saved file {{{3\nfunction! s:UpdateTags_for_SavedFile(ctags_pathname)\n let source_name = expand('%')\n let temp_tags = tempname()\n\n if filereadable(a:ctags_pathname)\n \" it exists =&gt; must be changed\n call system('grep -v \" '.source_name.' \" '.a:ctags_pathname.' &gt; '.temp_tags.' &amp;&amp; mv -f '.temp_tags.' '.a:ctags_pathname)\n endif\n let cmd_line = 'cd '.s:CtagsDirname()\n let cmd_line .= ' &amp;&amp; ' . s:CtagsCmdLine(a:ctags_pathname).' --append '.source_name\n \" echo cmd_line\n call system(cmd_line)\nendfunction\n\n\" ======================================================================\n\" (public) Run a tag generating function {{{3\nfunction! LHTagsRun(tag_function)\n call s:Run(a:tag_function)\nendfunction\n\n\" ======================================================================\n\" (private) Run a tag generating function {{{3\n\" See this function as a /template method/.\nfunction! s:Run(tag_function)\n try\n let ctags_dirname = s:CtagsDirname()\n if strlen(ctags_dirname)==1\n throw \"tags-error: empty dirname\"\n endif\n let ctags_filename = s:CtagsFilename()\n let ctags_pathname = ctags_dirname.ctags_filename\n if !filewritable(ctags_dirname) &amp;&amp; !filewritable(ctags_pathname)\n throw \"tags-error: \".ctags_pathname.\" cannot be modified\"\n endif\n\n let Fn = function(\"s:\".a:tag_function)\n call Fn(ctags_pathname)\n catch /tags-error:/\n \" call lh#common#ErrorMsg(v:exception)\n return 0\n finally\n endtry\n\n echo ctags_pathname . ' updated.'\n return 1\nendfunction\n\nfunction! s:Irun(tag_function, res)\n call s:Run(a:tag_function)\n return a:res\nendfunction\n\n\" ======================================================================\n\" Main function for updating all tags {{{3\nfunction! s:UpdateAll()\n let done = s:Run('UpdateTags_for_All')\nendfunction\n\n\" Main function for updating the tags from one file {{{3\n\" @note the file may be saved or \"modified\".\nfunction! s:UpdateCurrent()\n if &amp;modified\n let done = s:Run('UpdateTags_for_ModifiedFile')\n else\n let done = s:Run('UpdateTags_for_SavedFile')\n endif\nendfunction\n</code></pre>\n\n<p>This code defines:</p>\n\n<ul>\n<li><code>^Xta</code> to force the update of the tags base for all the files in the current project ;</li>\n<li><code>^Xtc</code> to force the update of the tags base for the current (unsaved) file ;</li>\n<li>an autocommand that updates the tags base every time a file is saved ;\nand it supports and many options to disable the automatic update where we don't want it, to tune ctags calls depending on filetypes, ...\nIt is not just a tip, but a small excerpt of a plugin.</li>\n</ul>\n\n<p>HTH,</p>\n" }, { "answer_id": 164404, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 4, "selected": false, "text": "<p><b>Edit</b>: A solution very much along the lines of the following has been posted as <strong>the <a href=\"http://www.vim.org/scripts/script.php?script_id=1343\" rel=\"noreferrer\">AutoTag</a> vim script</strong>. Note that the script <strong>needs a vim with Python support</strong>, however.</p>\n\n<p>My solution shells out to awk instead, so it should work on many more systems.</p>\n\n<hr>\n\n<pre><code>au FileType {c,cpp} au BufWritePost &lt;buffer&gt; silent ! [ -e tags ] &amp;&amp;\n \\ ( awk -F'\\t' '$2\\!=\"%:gs/'/'\\''/\"{print}' tags ; ctags -f- '%:gs/'/'\\''/' )\n \\ | sort -t$'\\t' -k1,1 -o tags.new &amp;&amp; mv tags.new tags\n</code></pre>\n\n<p>Note that you can only write it this way in a script, otherwise it has to go on a single line.</p>\n\n<p>There’s lot going on in there:</p>\n\n<ol>\n<li><p>This auto-command triggers when a file has been detected to be C or C++, and adds in turn a buffer-local auto-command that is triggered by the <code>BufWritePost</code> event.</p></li>\n<li><p>It uses the <code>%</code> placeholder which is replaced by the buffer’s filename at execution time, together with the <code>:gs</code> modifier used to shell-quote the filename (by turning any embedded single-quotes into quote-escape-quote-quote).</p></li>\n<li><p>That way it runs a shell command that checks if a <code>tags</code> file exists, in which case its content is printed except for the lines that refer to the just-saved file, meanwhile <code>ctags</code> is invoked on just the just-saved file, and the result is then <code>sort</code>ed and put back into place.</p></li>\n</ol>\n\n<p>Caveat implementor: this assumes everything is in the same directory and that that is also the buffer-local current directory. I have not given any thought to path mangling.</p>\n" }, { "answer_id": 4310892, "author": "code933k", "author_id": 194556, "author_profile": "https://Stackoverflow.com/users/194556", "pm_score": 3, "selected": false, "text": "<p>I've noticed this is an old thread, however...\nUse <strong>incron</strong> in *nix like environments supporting inotify. It will always launch commands whenever files in a directory change. i.e.,</p>\n\n<pre><code>/home/me/Code/c/that_program IN_DELETE,IN_CLOSE_WRITE ctags --sort=yes *.c\n</code></pre>\n\n<p>That's it.</p>\n" }, { "answer_id": 4962216, "author": "Marcus", "author_id": 9574, "author_profile": "https://Stackoverflow.com/users/9574", "pm_score": 1, "selected": false, "text": "<p>There is a vim plugin called <a href=\"http://www.vim.org/scripts/script.php?script_id=1343\" rel=\"nofollow\">AutoTag</a> for this that works really well.</p>\n\n<p>If you have taglist installed it will also update that for you.</p>\n" }, { "answer_id": 5441535, "author": "dimonomid", "author_id": 677890, "author_profile": "https://Stackoverflow.com/users/677890", "pm_score": 1, "selected": false, "text": "<p>In my opninion, plugin Indexer is better.</p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=3221\" rel=\"nofollow\">http://www.vim.org/scripts/script.php?script_id=3221</a></p>\n\n<p>It can be: </p>\n\n<p>1) an add-on for project.tar.gz</p>\n\n<p>2) an independent plugin</p>\n\n<ul>\n<li>background tags generation (you have not wait while ctags works)</li>\n<li>multiple projects supported</li>\n</ul>\n" }, { "answer_id": 7269205, "author": "rand_acs", "author_id": 143219, "author_profile": "https://Stackoverflow.com/users/143219", "pm_score": 2, "selected": false, "text": "<p>On OSX this command will not work out of the box, at least not for me.</p>\n\n<pre><code>au BufWritePost *.c,*.cpp,*.h silent! !ctags -R &amp;\n</code></pre>\n\n<p>I found a <a href=\"http://gmarik.info/blog/2010/10/08/ctags-on-OSX\" rel=\"nofollow\">post</a>, which explains how to get the standard ctags version that contains the -R option. This alone did not work for me. I had to add /usr/local/bin to the PATH variable in .bash_profile in order to pick up the bin where Homebrew installs programs.</p>\n" }, { "answer_id": 7909594, "author": "Greg Jandl", "author_id": 87141, "author_profile": "https://Stackoverflow.com/users/87141", "pm_score": 0, "selected": false, "text": "<p>Auto Tag is a vim plugin that updates existing tag files on save.</p>\n\n<p>I've been using it for years without problems, with the exception that it enforces a maximum size on the tags files. Unless you have a really large set of code all indexed in the same tags file, you shouldn't hit that limit, though.</p>\n\n<p>Note that Auto Tag requires Python support in vim.</p>\n" }, { "answer_id": 8866174, "author": "xolox", "author_id": 788200, "author_profile": "https://Stackoverflow.com/users/788200", "pm_score": 4, "selected": false, "text": "<p>I wrote <a href=\"http://www.vim.org/scripts/script.php?script_id=3114\" rel=\"nofollow\">easytags.vim</a> to do just this: automatically update and highlight tags. The plug-in can be configured to update just the file being edited or all files in the directory of the file being edited (recursively). It can use a global tags file, file type specific tags files and project specific tags files.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
Right now I have the following in my `.vimrc`: ``` au BufWritePost *.c,*.cpp,*.h !ctags -R ``` There are a few problems with this: 1. It's slow -- regenerates tags for files that haven't changed since the last tag generation. 2. I have to push the enter button *again* after writing the file because of an inevitable "press Enter or type command to continue". When you combine these two issues I end up pushing the additional enter too soon (before `ctags -R` has finished), then see the annoying error message, and have to push enter again. I know it doesn't sound like a big deal, but with the amount of file writes I do on a given day it tends to get really annoying. There's gotta be a better way to do it!
`au BufWritePost *.c,*.cpp,*.h silent! !ctags -R &` The downside is that you won't have a useful tags file until it completes. As long as you're on a \*nix system it should be ok to do multiple writes before the previous ctags has completed, but you should test that. On a Windows system it won't put it in the background and it'll complain that the file is locked until the first ctags finishes (which shouldn't cause problems in vim, but you'll end up with a slightly outdated tags file). Note, you could use the `--append` option as tonylo suggests, but then you'll have to disable `tagbsearch` which could mean that tag searches take a lot longer, depending on the size of your tag file.
155,458
<p>I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.</p> <p>Here is the code :</p> <pre><code> if (region != null) { .... } </code></pre> <p>This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... <strong>why and how?</strong></p> <p><strong>Update</strong></p> <p>Someone point out that the object was == and != overloaded:</p> <pre><code> public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 &amp;&amp; r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id); } </code></pre>
[ { "answer_id": 155464, "author": "skb", "author_id": 14101, "author_profile": "https://Stackoverflow.com/users/14101", "pm_score": 2, "selected": false, "text": "<p>This can sometimes happen when you have multiple threads working with the same data. If this is the case, you can use a lock to prevent them from messing with eachother.</p>\n" }, { "answer_id": 155467, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": true, "text": "<p>Is the == and/or != operator overloaded for the region object's class?</p>\n\n<p>Now that you've posted the code for the overloads:</p>\n\n<p>The overloads should probably look like the following (code taken from postings made by <a href=\"https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155488\">Jon Skeet</a> and <a href=\"https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155508\">Philip Rieck</a>):</p>\n\n<pre><code>public static bool operator ==(Region r1, Region r2)\n{\n if (object.ReferenceEquals( r1, r2)) {\n // handles if both are null as well as object identity\n return true;\n }\n\n if ((object)r1 == null || (object)r2 == null)\n {\n return false;\n } \n\n return (r1.Cmr.CompareTo(r2.Cmr) == 0 &amp;&amp; r1.Id == r2.Id);\n}\n\npublic static bool operator !=(Region r1, Region r2)\n{\n return !(r1 == r2);\n}\n</code></pre>\n" }, { "answer_id": 155488, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>Those operator overloads are broken.</p>\n\n<p>Firstly, it makes life a lot easier if != is implemented by just calling == and inverting the result.</p>\n\n<p>Secondly, before the nullity checks in == there should be:</p>\n\n<pre><code>if (object.ReferenceEquals(r1, r2))\n{\n return true;\n}\n</code></pre>\n" }, { "answer_id": 155489, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 0, "selected": false, "text": "<p>So is it that these checks here are not right:</p>\n\n<pre><code>public static bool operator !=(Region r1, Region r2)\n{\n if (object.ReferenceEquals(r1, null))\n {\n return false;\n }\n if (object.ReferenceEquals(r2, null))\n {\n return false;\n }\n...\n</code></pre>\n" }, { "answer_id": 155508, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 3, "selected": false, "text": "<p>Both of the overloads are incorrect</p>\n\n<pre><code> public static bool operator ==(Region r1, Region r2)\n {\n if (object.ReferenceEquals(r1, null))\n {\n return false;\n }\n if (object.ReferenceEquals(r2, null))\n {\n return false;\n }\n\n return (r1.Cmr.CompareTo(r2.Cmr) == 0 &amp;&amp; r1.Id == r2.Id);\n }\n</code></pre>\n\n<p>if r1 And r2 are null, the first test (<em>object.ReferenceEquals(r1, null)</em>) will return false, even though r2 is also null.</p>\n\n<p>try</p>\n\n<pre><code>//ifs expanded a bit for readability\n public static bool operator ==(Region r1, Region r2)\n {\n if( (object)r1 == null &amp;&amp; (object)r2 == null)\n {\n return true;\n }\n if( (object)r1 == null || (object)r2 == null)\n {\n return false;\n } \n //btw - a quick shortcut here is also object.ReferenceEquals(r1, r2)\n\n return (r1.Cmr.CompareTo(r2.Cmr) == 0 &amp;&amp; r1.Id == r2.Id);\n }\n</code></pre>\n" }, { "answer_id": 159129, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 0, "selected": false, "text": "<p>There's another possibility that you need to click the refresh icon next to the parameter that you're watching. VS try to keep up with the performance while not evaluating every statement/parameter. Take a look to make sure, before you start making changes to places that's non relevant.</p>\n" }, { "answer_id": 735710, "author": "Triynko", "author_id": 88409, "author_profile": "https://Stackoverflow.com/users/88409", "pm_score": 2, "selected": false, "text": "<p>For equality comparison of a type \"T\", overload these methods:</p>\n\n<pre><code>int GetHashCode() //Overrides Object.GetHashCode\nbool Equals(object other) //Overrides Object.Equals; would correspond to IEquatable, if such an interface existed\nbool Equals(T other) //Implements IEquatable&lt;T&gt;; do this for each T you want to compare to\nstatic bool operator ==(T x, T y)\nstatic bool operator !=(T x, T y)\n</code></pre>\n\n<p><strong>Your type-specific comparison code should be done in one place</strong>: the type-safe <code>IEquatable&lt;T&gt;</code> interface method <code>Equals(T other)</code>.\nIf you're comparing to another type (T2), implement <code>IEquatable&lt;T2&gt;</code> as well, and put the field comparison code for that type in Equals(T2 other).</p>\n\n<p>All overloaded methods and operators should forward the equality comparison task to the main type-safe Equals(T other) instance method, such that an clean dependency hierarchy is maintained and stricter guarantees are introduced at each level to eliminate redundancy and unessential complexity.</p>\n\n<pre><code>bool Equals(object other)\n{\n if (other is T) //replicate this for each IEquatable&lt;T2&gt;, IEquatable&lt;T3&gt;, etc. you may implement\n return Equals( (T)other) ); //forward to IEquatable&lt;T&gt; implementation\n return false; //other is null or cannot be compared to this instance; therefore it is not equal\n}\n\nbool Equals(T other)\n{\n if ((object)other == null) //cast to object for reference equality comparison, or use object.ReferenceEquals\n return false;\n //if ((object)other == this) //possible performance boost, ONLY if object instance is frequently compared to itself! otherwise it's just an extra useless check\n //return true;\n return field1.Equals( other.field1 ) &amp;&amp;\n field2.Equals( other.field2 ); //compare type fields to determine equality\n}\n\npublic static bool operator ==( T x, T y )\n{\n if ((object)x != null) //cast to object for reference equality comparison, or use object.ReferenceEquals\n return x.Equals( y ); //forward to type-safe Equals on non-null instance x\n if ((object)y != null)\n return false; //x was null, y is not null\n return true; //both null\n}\n\npublic static bool operator !=( T x, T y )\n{\n if ((object)x != null)\n return !x.Equals( y ); //forward to type-safe Equals on non-null instance x\n if ((object)y != null)\n return true; //x was null, y is not null\n return false; //both null\n}\n</code></pre>\n\n<p><strong>Discussion:</strong></p>\n\n<p>The preceding implementation centralizes the type-specific (i.e. field equality) comparison to the end of the <code>IEquatable&lt;T&gt;</code> implementation for the type.\nThe <code>==</code> and <code>!=</code> operators have a parallel but opposite implementation. I prefer this over having one reference the other, such that there is an extra method call for the dependent one. If the <code>!=</code> operator is simply going to call the <code>==</code> operator, rather than offer an equally performing operator, then you may as well just use <code>!(obj1 == obj2)</code> and avoid the extra method call.\nThe comparison-to-self is left out from the equals operator and the <code>IEquatable&lt;T&gt;</code> implementations, because it can introduce 1. unnecessary overhead in some cases, and/or 2. inconsistent performance depending on how often an instance is compared to itself vs other instances.</p>\n\n<p>An alternative I don't like, but should mention, is to reverse this setup, centralizing the type-specific equality code in the equality operator instead and have the Equals methods depend on that. One could then use the shortcut of <code>ReferenceEquals(obj1,obj2)</code> to check for reference equality and null equality simultaneously as Philip mentioned in an earlier post, but that idea is misleading. It seems like you're killing two birds with one stone, but your actually creating more work -- after determining the objects are neither both null nor the same instance, you will then, in addition, STILL have to on to check whether each instance is null. In my implementation, you check for any single instance being null exactly once. By the time the Equals instance method is called, it's already ruled out that the first object being compared is null, so all that's left to do is check whether the other is null. So after at most two comparisons, we jump directly into the field checking, no matter which method we use (<code>Equals(object),Equals(T),==,!=</code>). Also, as I mentioned, if you really are comparing and object to itself the majority of the time, then you could add that check in the Equals method just before diving into the field comparisons. The point in adding it last is that you can still maintain the flow/dependency hierarchy without introducing a redundant/useless check at every level.</p>\n" }, { "answer_id": 13519359, "author": "fernando", "author_id": 1846008, "author_profile": "https://Stackoverflow.com/users/1846008", "pm_score": 0, "selected": false, "text": "<pre><code>bool comp;\nif (object.IsNullOrEmpty(r1))\n{\n comp = false;\n}\n\nif (object.IsNullOrEmpty(r2))\n{\n comp = false;\n}\nreturn comp;\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data. Here is the code : ``` if (region != null) { .... } ``` This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... **why and how?** **Update** Someone point out that the object was == and != overloaded: ``` public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id); } ```
Is the == and/or != operator overloaded for the region object's class? Now that you've posted the code for the overloads: The overloads should probably look like the following (code taken from postings made by [Jon Skeet](https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155488) and [Philip Rieck](https://stackoverflow.com/questions/155458/c-object-is-not-null-but-myobject-null-still-return-false#155508)): ``` public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals( r1, r2)) { // handles if both are null as well as object identity return true; } if ((object)r1 == null || (object)r2 == null) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { return !(r1 == r2); } ```
155,460
<p>I'm using LINQ to SQL and C#. I have two LINQ classes: User and Network. </p> <p>User has UserID (primary key) and NetworkID</p> <p>Network has NetworkID (primary key) and an AdminID (a UserID)</p> <p>The following code works fine:</p> <pre><code>user.Network.AdminID = 0; db.SubmitChanges(); </code></pre> <p>However, if I access the AdminID before making the change, the change never happens to the DB. So the following doesn't work:</p> <pre><code>if(user.Network.AdminID == user.UserID) { user.Network.AdminID = 0; db.SubmitChanges(); } </code></pre> <p>It is making it into the if statement and calling submit changes. For some reason, the changes to AdminID never make it to the DB. No error thrown, the change just never 'takes'.</p> <p>Any idea what could be causing this?</p> <p>Thanks.</p>
[ { "answer_id": 155641, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 3, "selected": true, "text": "<p>I just ran a quick test and it works fine for me. </p>\n\n<p>I hate to ask this, but are you sure the if statement ever returns true? It could be you're just not hitting the code which changes the value.</p>\n\n<p>Other than that we might need more info. What are the properties of that member? Have you traced into the set statement to ensure the value is getting set before calling SubmitChanges? Does the Linq entity have the new value after SubmitChanges? Or do both the database AND the Linq entity fail to take the new value?</p>\n\n<p>In short, that code should work... so something else somewhere is probably wrong.</p>\n" }, { "answer_id": 155658, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Here's the original <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3086400&amp;SiteID=1\" rel=\"nofollow noreferrer\">post</a>.</p>\n\n<hr>\n\n<p>Here's a setter generated by the LinqToSql designer.</p>\n\n<p>Code Snippet</p>\n\n<pre><code>{\n Contact previousValue = this._Contact.Entity;\n if (((previousValue != value)\n || (this._Contact.HasLoadedOrAssignedValue == false)))\n {\n this.SendPropertyChanging();\n if ((previousValue != null))\n {\n this._Contact.Entity = null;\n previousValue.ContactEvents.Remove(this);\n }\n this._Contact.Entity = value;\n if ((value != null))\n {\n value.ContactEvents.Add(this);\n this._ContactID = value.ID;\n }\n else\n {\n this._ContactID = default(int);\n }\n this.SendPropertyChanged(\"Contact\");\n }\n}\n</code></pre>\n\n<p>This line sets the child's property to the parent.</p>\n\n<pre><code>this._Contact.Entity = value;\n</code></pre>\n\n<p>This line adds the child to the parent's collection</p>\n\n<pre><code>value.ContactEvents.Add(this);\n</code></pre>\n\n<p>The <strong>setter</strong> for the ID does not have this second line.</p>\n\n<p>So, with the autogenerated entities...\nThis code produces an unexpected behavior:</p>\n\n<pre><code>myContactEvent.ContactID = myContact.ID;\n</code></pre>\n\n<p>This code is good:</p>\n\n<pre><code>myContactEvent.Contact = myContact;\n</code></pre>\n\n<p>This code is also good:</p>\n\n<pre><code>myContact.ContactEvents.Add(myContactEvent);\n</code></pre>\n" }, { "answer_id": 3339204, "author": "Alex Kazansky", "author_id": 196837, "author_profile": "https://Stackoverflow.com/users/196837", "pm_score": 0, "selected": false, "text": "<p>I had this issue. The reason was one dumb line of code:</p>\n\n<pre><code>DBDataContext db { get { return new DBDataContext(); } }\n</code></pre>\n\n<p>obviously it should be:</p>\n\n<pre><code>DBDataContext db = new DBDataContext();\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23971/" ]
I'm using LINQ to SQL and C#. I have two LINQ classes: User and Network. User has UserID (primary key) and NetworkID Network has NetworkID (primary key) and an AdminID (a UserID) The following code works fine: ``` user.Network.AdminID = 0; db.SubmitChanges(); ``` However, if I access the AdminID before making the change, the change never happens to the DB. So the following doesn't work: ``` if(user.Network.AdminID == user.UserID) { user.Network.AdminID = 0; db.SubmitChanges(); } ``` It is making it into the if statement and calling submit changes. For some reason, the changes to AdminID never make it to the DB. No error thrown, the change just never 'takes'. Any idea what could be causing this? Thanks.
I just ran a quick test and it works fine for me. I hate to ask this, but are you sure the if statement ever returns true? It could be you're just not hitting the code which changes the value. Other than that we might need more info. What are the properties of that member? Have you traced into the set statement to ensure the value is getting set before calling SubmitChanges? Does the Linq entity have the new value after SubmitChanges? Or do both the database AND the Linq entity fail to take the new value? In short, that code should work... so something else somewhere is probably wrong.
155,462
<p>In Ruby:</p> <pre><code>for i in A do # some code end </code></pre> <p>is the same as: </p> <pre><code>A.each do |i| # some code end </code></pre> <p><code>for</code> is not a kernel method:</p> <ul> <li>What exactly is "<code>for</code>" in ruby</li> <li>Is there a way to use other keywords to do similar things? </li> </ul> <p>Something like:</p> <pre><code> total = sum i in I {x[i]} </code></pre> <p>mapping to:</p> <pre><code> total = I.sum {|i] x[i]} </code></pre>
[ { "answer_id": 155513, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": false, "text": "<p><code>for</code> is just syntax sugar for the <code>each</code> method. This can be seen by running this code:</p>\n\n<pre><code>for i in 1 do\nend\n</code></pre>\n\n<p>This results in the error:</p>\n\n<pre><code>NoMethodError: undefined method `each' for 1:Fixnum\n</code></pre>\n" }, { "answer_id": 155531, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 3, "selected": false, "text": "<p>For is just syntactic sugar.</p>\n\n<p>From <a href=\"http://www.rubycentral.com/pickaxe/tut_expressions.html#UK\" rel=\"noreferrer\">the pickaxe</a>:</p>\n\n<blockquote>\n <p><strong>For ... In</strong></p>\n \n <p>Earlier we said that the only built-in Ruby looping primitives were while and until. What's this ``for'' thing, then? Well, for is almost a lump of syntactic sugar. When you write</p>\n\n<pre><code>for aSong in songList\n aSong.play\nend\n</code></pre>\n \n <p>Ruby translates it into something like:</p>\n\n<pre><code>songList.each do |aSong|\n aSong.play\nend\n</code></pre>\n \n <p>The only difference between the for loop and the each form is the scope of local variables that are defined in the body. This is discussed on page 87.</p>\n \n <p>You can use for to iterate over any object that responds to the method each, such as an Array or a Range.</p>\n\n<pre><code>for i in ['fee', 'fi', 'fo', 'fum']\n print i, \" \"\nend\nfor i in 1..3\n print i, \" \"\nend\nfor i in File.open(\"ordinal\").find_all { |l| l =~ /d$/}\n print i.chomp, \" \"\nend\n</code></pre>\n \n <p>produces:</p>\n\n<pre><code>fee fi fo fum 1 2 3 second third\n</code></pre>\n \n <p>As long as your class defines a sensible each method, you can use a for loop to traverse it.</p>\n\n<pre><code>class Periods\n def each\n yield \"Classical\"\n yield \"Jazz\"\n yield \"Rock\"\n end\nend\n\n\nperiods = Periods.new\nfor genre in periods\n print genre, \" \"\nend\n</code></pre>\n \n <p>produces:</p>\n\n<pre><code>Classical Jazz Rock\n</code></pre>\n</blockquote>\n\n<p>Ruby doesn't have other keywords for list comprehensions (like the sum example you made above). <code>for</code> isn't a terribly popular keyword, and the method syntax ( <code>arr.each {}</code> ) is generally preferred.</p>\n" }, { "answer_id": 155543, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 7, "selected": true, "text": "<p>It's almost syntax sugar. One difference is that, while <code>for</code> would use the scope of the code around it, <code>each</code> creates a separate scope within its block. Compare the following:</p>\n\n<pre><code>for i in (1..3)\n x = i\nend\np x # =&gt; 3\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>(1..3).each do |i|\n x = i\nend\np x # =&gt; undefined local variable or method `x' for main:Object\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14167/" ]
In Ruby: ``` for i in A do # some code end ``` is the same as: ``` A.each do |i| # some code end ``` `for` is not a kernel method: * What exactly is "`for`" in ruby * Is there a way to use other keywords to do similar things? Something like: ``` total = sum i in I {x[i]} ``` mapping to: ``` total = I.sum {|i] x[i]} ```
It's almost syntax sugar. One difference is that, while `for` would use the scope of the code around it, `each` creates a separate scope within its block. Compare the following: ``` for i in (1..3) x = i end p x # => 3 ``` versus ``` (1..3).each do |i| x = i end p x # => undefined local variable or method `x' for main:Object ```
155,504
<p>I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API?</p> <p>I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with.</p> <p><strong>EDIT</strong>: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to <strong>read</strong> attachments from <strong>received</strong> mail.</p> <p>Cheers, Don</p>
[ { "answer_id": 155523, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 0, "selected": false, "text": "<p>Thus far, I've only used the JavaMail APIs (and I've been reasonably happy with them for my purposes). If the full JavaMail package is too heavy for you, the underlying transport engine can be used without the top layers of the package. The lower you go in the SMTP, POP3 and IMAP stacks, the more you have to be prepared to do for yourself.</p>\n\n<p>On the bright side, you'll also be able to ignore the parts that aren't required for your application.</p>\n" }, { "answer_id": 158511, "author": "Steven M. Cherry", "author_id": 24193, "author_profile": "https://Stackoverflow.com/users/24193", "pm_score": 5, "selected": true, "text": "<p>Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading.</p>\n\n<p>The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths.</p>\n\n<p>Focus on the doEMailDownload method.</p>\n\n<pre><code>/**\n * Copyright (c) 2008 Steven M. Cherry\n * All rights reserved.\n */\npackage utils.scheduled;\n\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.sql.Timestamp;\nimport java.util.Properties;\nimport java.util.Vector;\n\nimport javax.mail.Address;\nimport javax.mail.Flags;\nimport javax.mail.Folder;\nimport javax.mail.Message;\nimport javax.mail.Multipart;\nimport javax.mail.Part;\nimport javax.mail.Session;\nimport javax.mail.Store;\nimport javax.mail.internet.MimeBodyPart;\n\nimport glob.ActionLogicImplementation;\nimport glob.IOConn;\nimport glob.log.Log;\nimport logic.utils.sql.Settings;\nimport logic.utils.sqldo.EMail;\nimport logic.utils.sqldo.EMailAttach;\n\n/**\n * This will connect to our incoming e-mail server and download any e-mails\n * that are found on the server. The e-mails will be stored for further processing\n * in our internal database. Attachments will be written out to separate files\n * and then referred to by the database entries. This is intended to be run by \n * the scheduler every minute or so.\n *\n * @author Steven M. Cherry\n */\npublic class DownloadEMail implements ActionLogicImplementation {\n\n protected String receiving_host;\n protected String receiving_user;\n protected String receiving_pass;\n protected String receiving_protocol;\n protected boolean receiving_secure;\n protected String receiving_attachments;\n\n /** This will run our logic */\n public void ExecuteRequest(IOConn ioc) throws Exception {\n Log.Trace(\"Enter\");\n\n Log.Debug(\"Executing DownloadEMail\");\n ioc.initializeResponseDocument(\"DownloadEMail\");\n\n // pick up our configuration from the server:\n receiving_host = Settings.getValue(ioc, \"server.email.receiving.host\");\n receiving_user = Settings.getValue(ioc, \"server.email.receiving.username\");\n receiving_pass = Settings.getValue(ioc, \"server.email.receiving.password\");\n receiving_protocol = Settings.getValue(ioc, \"server.email.receiving.protocol\");\n String tmp_secure = Settings.getValue(ioc, \"server.email.receiving.secure\");\n receiving_attachments = Settings.getValue(ioc, \"server.email.receiving.attachments\");\n\n // sanity check on the parameters:\n if(receiving_host == null || receiving_host.length() == 0){\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n return; // no host defined.\n }\n if(receiving_user == null || receiving_user.length() == 0){\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n return; // no user defined.\n }\n if(receiving_pass == null || receiving_pass.length() == 0){\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n return; // no pass defined.\n }\n if(receiving_protocol == null || receiving_protocol.length() == 0){\n Log.Debug(\"EMail receiving protocol not defined, defaulting to POP\");\n receiving_protocol = \"POP\";\n }\n if(tmp_secure == null || \n tmp_secure.length() == 0 ||\n tmp_secure.compareToIgnoreCase(\"false\") == 0 ||\n tmp_secure.compareToIgnoreCase(\"no\") == 0\n ){\n receiving_secure = false;\n } else {\n receiving_secure = true;\n }\n if(receiving_attachments == null || receiving_attachments.length() == 0){\n Log.Debug(\"EMail receiving attachments not defined, defaulting to ./email/attachments/\");\n receiving_attachments = \"./email/attachments/\";\n }\n\n // now do the real work.\n doEMailDownload(ioc);\n\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n }\n\n protected void doEMailDownload(IOConn ioc) throws Exception {\n // Create empty properties\n Properties props = new Properties();\n // Get the session\n Session session = Session.getInstance(props, null);\n\n // Get the store\n Store store = session.getStore(receiving_protocol);\n store.connect(receiving_host, receiving_user, receiving_pass);\n\n // Get folder\n Folder folder = store.getFolder(\"INBOX\");\n folder.open(Folder.READ_WRITE);\n\n try {\n\n // Get directory listing\n Message messages[] = folder.getMessages();\n\n for (int i=0; i &lt; messages.length; i++) {\n // get the details of the message:\n EMail email = new EMail();\n email.fromaddr = messages[i].getFrom()[0].toString();\n Address[] to = messages[i].getRecipients(Message.RecipientType.TO);\n email.toaddr = \"\";\n for(int j = 0; j &lt; to.length; j++){\n email.toaddr += to[j].toString() + \"; \";\n }\n Address[] cc;\n try {\n cc = messages[i].getRecipients(Message.RecipientType.CC);\n } catch (Exception e){\n Log.Warn(\"Exception retrieving CC addrs: %s\", e.getLocalizedMessage());\n cc = null;\n }\n email.cc = \"\";\n if(cc != null){\n for(int j = 0; j &lt; cc.length; j++){\n email.cc += cc[j].toString() + \"; \";\n }\n }\n email.subject = messages[i].getSubject();\n if(messages[i].getReceivedDate() != null){\n email.received_when = new Timestamp(messages[i].getReceivedDate().getTime());\n } else {\n email.received_when = new Timestamp( (new java.util.Date()).getTime());\n }\n\n\n email.body = \"\";\n Vector&lt;EMailAttach&gt; vema = new Vector&lt;EMailAttach&gt;();\n Object content = messages[i].getContent();\n if(content instanceof java.lang.String){\n email.body = (String)content;\n } else if(content instanceof Multipart){\n Multipart mp = (Multipart)content;\n\n for (int j=0; j &lt; mp.getCount(); j++) {\n Part part = mp.getBodyPart(j);\n\n String disposition = part.getDisposition();\n\n if (disposition == null) {\n // Check if plain\n MimeBodyPart mbp = (MimeBodyPart)part;\n if (mbp.isMimeType(\"text/plain\")) {\n Log.Debug(\"Mime type is plain\");\n email.body += (String)mbp.getContent();\n } else {\n Log.Debug(\"Mime type is not plain\");\n // Special non-attachment cases here of \n // image/gif, text/html, ...\n EMailAttach ema = new EMailAttach();\n ema.name = decodeName(part.getFileName());\n File savedir = new File(receiving_attachments);\n savedir.mkdirs();\n File savefile = File.createTempFile(\"emailattach\", \".atch\", savedir );\n ema.path = savefile.getAbsolutePath();\n ema.size = part.getSize();\n vema.add(ema);\n ema.size = saveFile(savefile, part);\n }\n } else if ((disposition != null) &amp;&amp; \n (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) \n ){\n // Check if plain\n MimeBodyPart mbp = (MimeBodyPart)part;\n if (mbp.isMimeType(\"text/plain\")) {\n Log.Debug(\"Mime type is plain\");\n email.body += (String)mbp.getContent();\n } else {\n Log.Debug(\"Save file (%s)\", part.getFileName() );\n EMailAttach ema = new EMailAttach();\n ema.name = decodeName(part.getFileName());\n File savedir = new File(receiving_attachments);\n savedir.mkdirs();\n File savefile = File.createTempFile(\"emailattach\", \".atch\", savedir );\n ema.path = savefile.getAbsolutePath();\n ema.size = part.getSize();\n vema.add(ema);\n ema.size = saveFile( savefile, part);\n }\n }\n }\n }\n\n // Insert everything into the database:\n logic.utils.sql.EMail.insertEMail(ioc, email);\n for(int j = 0; j &lt; vema.size(); j++){\n vema.get(j).emailid = email.id;\n logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) );\n }\n\n // commit this message and all of it's attachments\n ioc.getDBConnection().commit();\n\n // Finally delete the message from the server.\n messages[i].setFlag(Flags.Flag.DELETED, true);\n }\n\n // Close connection \n folder.close(true); // true tells the mail server to expunge deleted messages.\n store.close();\n } catch (Exception e){\n folder.close(true); // true tells the mail server to expunge deleted messages.\n store.close();\n throw e;\n }\n\n }\n\n protected int saveFile(File saveFile, Part part) throws Exception {\n\n BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );\n\n byte[] buff = new byte[2048];\n InputStream is = part.getInputStream();\n int ret = 0, count = 0;\n while( (ret = is.read(buff)) &gt; 0 ){\n bos.write(buff, 0, ret);\n count += ret;\n }\n bos.close();\n is.close();\n return count;\n }\n\n protected String decodeName( String name ) throws Exception {\n if(name == null || name.length() == 0){\n return \"unknown\";\n }\n String ret = java.net.URLDecoder.decode( name, \"UTF-8\" );\n\n // also check for a few other things in the string:\n ret = ret.replaceAll(\"=\\\\?utf-8\\\\?q\\\\?\", \"\");\n ret = ret.replaceAll(\"\\\\?=\", \"\");\n ret = ret.replaceAll(\"=20\", \" \");\n\n return ret;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 1490089, "author": "Maciej Kreft", "author_id": 180819, "author_profile": "https://Stackoverflow.com/users/180819", "pm_score": 2, "selected": false, "text": "<p>Here is an error:</p>\n\n<pre><code>else if ((disposition != null) &amp;&amp; (disposition.equals(Part.ATTACHMENT)\n || disposition.equals(Part.INLINE) ) \n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>else if ((disposition.equalsIgnoreCase(Part.ATTACHMENT)\n || disposition.equalsIgnoreCase(Part.INLINE))\n</code></pre>\n\n<p>Thanks @Stevenmcherry for your answer</p>\n" }, { "answer_id": 4528035, "author": "chad", "author_id": 344269, "author_profile": "https://Stackoverflow.com/users/344269", "pm_score": 4, "selected": false, "text": "<p>I worked Steven's example a little bit and removed the parts of the code specific to Steven. My code won't read the body of an email if it has attachments. That is fine for my case but you may want to refine it further for yours.</p>\n\n<pre><code>package utils;\n\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Properties;\n\nimport javax.mail.Address;\nimport javax.mail.Flags;\nimport javax.mail.Folder;\nimport javax.mail.Message;\nimport javax.mail.Multipart;\nimport javax.mail.Part;\nimport javax.mail.Session;\nimport javax.mail.Store;\nimport javax.mail.internet.MimeBodyPart;\n\npublic class IncomingMail {\n\n public static List&lt;Email&gt; downloadPop3(String host, String user, String pass, String downloadDir) throws Exception {\n\n List&lt;Email&gt; emails = new ArrayList&lt;Email&gt;();\n\n // Create empty properties\n Properties props = new Properties();\n\n // Get the session\n Session session = Session.getInstance(props, null);\n\n // Get the store\n Store store = session.getStore(\"pop3\");\n store.connect(host, user, pass);\n\n // Get folder\n Folder folder = store.getFolder(\"INBOX\");\n folder.open(Folder.READ_WRITE);\n\n try {\n // Get directory listing\n Message messages[] = folder.getMessages();\n for (int i = 0; i &lt; messages.length; i++) {\n\n Email email = new Email();\n\n // from \n email.from = messages[i].getFrom()[0].toString();\n\n // to list\n Address[] toArray = messages[i] .getRecipients(Message.RecipientType.TO);\n for (Address to : toArray) { email.to.add(to.toString()); }\n\n // cc list\n Address[] ccArray = null;\n try {\n ccArray = messages[i] .getRecipients(Message.RecipientType.CC);\n } catch (Exception e) { ccArray = null; }\n if (ccArray != null) {\n for (Address c : ccArray) {\n email.cc.add(c.toString());\n }\n }\n\n // subject\n email.subject = messages[i].getSubject();\n\n // received date\n if (messages[i].getReceivedDate() != null) {\n email.received = messages[i].getReceivedDate();\n } else {\n email.received = new Date();\n }\n\n // body and attachments\n email.body = \"\";\n Object content = messages[i].getContent();\n if (content instanceof java.lang.String) {\n\n email.body = (String) content;\n\n } else if (content instanceof Multipart) {\n\n Multipart mp = (Multipart) content;\n\n for (int j = 0; j &lt; mp.getCount(); j++) {\n\n Part part = mp.getBodyPart(j);\n String disposition = part.getDisposition();\n\n if (disposition == null) {\n\n MimeBodyPart mbp = (MimeBodyPart) part;\n if (mbp.isMimeType(\"text/plain\")) {\n // Plain\n email.body += (String) mbp.getContent();\n } \n\n } else if ((disposition != null) &amp;&amp; (disposition.equals(Part.ATTACHMENT) || disposition .equals(Part.INLINE))) {\n\n // Check if plain\n MimeBodyPart mbp = (MimeBodyPart) part;\n if (mbp.isMimeType(\"text/plain\")) {\n email.body += (String) mbp.getContent();\n } else {\n EmailAttachment attachment = new EmailAttachment();\n attachment.name = decodeName(part.getFileName());\n File savedir = new File(downloadDir);\n savedir.mkdirs();\n // File savefile = File.createTempFile( \"emailattach\", \".atch\", savedir);\n File savefile = new File(downloadDir,attachment.name);\n attachment.path = savefile.getAbsolutePath();\n attachment.size = saveFile(savefile, part);\n email.attachments.add(attachment);\n }\n }\n } // end of multipart for loop \n } // end messages for loop\n\n emails.add(email);\n\n // Finally delete the message from the server.\n messages[i].setFlag(Flags.Flag.DELETED, true);\n }\n\n // Close connection\n folder.close(true); // true tells the mail server to expunge deleted messages\n store.close();\n\n } catch (Exception e) {\n folder.close(true); // true tells the mail server to expunge deleted\n store.close();\n throw e;\n }\n\n return emails;\n }\n\n private static String decodeName(String name) throws Exception {\n if (name == null || name.length() == 0) {\n return \"unknown\";\n }\n String ret = java.net.URLDecoder.decode(name, \"UTF-8\");\n\n // also check for a few other things in the string:\n ret = ret.replaceAll(\"=\\\\?utf-8\\\\?q\\\\?\", \"\");\n ret = ret.replaceAll(\"\\\\?=\", \"\");\n ret = ret.replaceAll(\"=20\", \" \");\n\n return ret;\n }\n\n private static int saveFile(File saveFile, Part part) throws Exception {\n\n BufferedOutputStream bos = new BufferedOutputStream(\n new FileOutputStream(saveFile));\n\n byte[] buff = new byte[2048];\n InputStream is = part.getInputStream();\n int ret = 0, count = 0;\n while ((ret = is.read(buff)) &gt; 0) {\n bos.write(buff, 0, ret);\n count += ret;\n }\n bos.close();\n is.close();\n return count;\n }\n\n}\n</code></pre>\n\n<p>You also need these two helper classes</p>\n\n<pre><code>package utils;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\npublic class Email {\n\n public Date received;\n public String from;\n public List&lt;String&gt; to = new ArrayList&lt;String&gt;();\n public List&lt;String&gt; cc = new ArrayList&lt;String&gt;();\n public String subject;\n public String body;\n public List&lt;EmailAttachment&gt; attachments = new ArrayList&lt;EmailAttachment&gt;();\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>package utils;\n\npublic class EmailAttachment {\n\n public String name;\n public String path;\n public int size;\n}\n</code></pre>\n\n<p>I used this to test the above classes</p>\n\n<pre><code>package utils;\n\nimport java.util.List;\n\n\npublic class Test {\n\n public static void main(String[] args) {\n\n String host = \"some host\";\n String user = \"some user\";\n String pass = \"some pass\";\n String downloadDir = \"/Temp\";\n try {\n List&lt;Email&gt; emails = IncomingMail.downloadPop3(host, user, pass, downloadDir);\n for ( Email email : emails ) {\n System.out.println(email.from);\n System.out.println(email.subject);\n System.out.println(email.body);\n List&lt;EmailAttachment&gt; attachments = email.attachments;\n for ( EmailAttachment attachment : attachments ) {\n System.out.println(attachment.path+\" \"+attachment.name);\n }\n }\n } catch (Exception e) { e.printStackTrace(); }\n\n }\n\n}\n</code></pre>\n\n<p>More info can be found at <a href=\"http://java.sun.com/developer/onlineTraining/JavaMail/contents.html\" rel=\"noreferrer\">http://java.sun.com/developer/onlineTraining/JavaMail/contents.html</a></p>\n" }, { "answer_id": 19317643, "author": "Karthik Reddy", "author_id": 1929603, "author_profile": "https://Stackoverflow.com/users/1929603", "pm_score": -1, "selected": false, "text": "<pre><code>import java.io.IOException;\nimport java.io.InputStream;\n\nimport javax.mail.internet.MimeMessage;\nimport javax.servlet.http.HttpServletRequest;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.core.io.InputStreamSource;\nimport org.springframework.mail.javamail.JavaMailSender;\nimport org.springframework.mail.javamail.MimeMessageHelper;\nimport org.springframework.mail.javamail.MimeMessagePreparator;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.multipart.commons.CommonsMultipartFile;\n\n@Controller\n@RequestMapping(\"/sendEmail.do\")\npublic class SendEmailAttachController {\n @Autowired\n private JavaMailSender mailSender;\n\n @RequestMapping(method = RequestMethod.POST)\n public String sendEmail(HttpServletRequest request,\n final @RequestParam CommonsMultipartFile attachFile) {\n\n // Input here\n final String emailTo = request.getParameter(\"mailTo\");\n final String subject = request.getParameter(\"subject\");\n final String yourmailid = request.getParameter(\"yourmail\");\n final String message = request.getParameter(\"message\");\n\n // Logging\n System.out.println(\"emailTo: \" + emailTo);\n System.out.println(\"subject: \" + subject);\n System.out.println(\"Your mail id is: \"+yourmailid);\n System.out.println(\"message: \" + message);\n System.out.println(\"attachFile: \" + attachFile.getOriginalFilename());\n\n mailSender.send(new MimeMessagePreparator() {\n\n @Override\n public void prepare(MimeMessage mimeMessage) throws Exception {\n MimeMessageHelper messageHelper = new MimeMessageHelper(\n mimeMessage, true, \"UTF-8\");\n messageHelper.setTo(emailTo);\n messageHelper.setSubject(subject);\n messageHelper.setReplyTo(yourmailid);\n messageHelper.setText(message);\n\n // Attachment with mail\n String attachName = attachFile.getOriginalFilename();\n if (!attachFile.equals(\"\")) {\n\n messageHelper.addAttachment(attachName, new InputStreamSource() {\n\n @Override\n public InputStream getInputStream() throws IOException {\n return attachFile.getInputStream();\n }\n });\n }\n\n }\n\n });\n\n return \"Result\";\n }\n}\n</code></pre>\n" }, { "answer_id": 20467580, "author": "Faber", "author_id": 2584278, "author_profile": "https://Stackoverflow.com/users/2584278", "pm_score": 1, "selected": false, "text": "<p>I used Apache Commons Mail for this task:</p>\n\n<pre><code>import java.util.List;\nimport javax.activation.DataSource; \nimport javax.mail.internet.MimeMessage; \nimport org.apache.commons.mail.util.MimeMessageParser; \n\npublic List&lt;DataSource&gt; getAttachmentList(MimeMessage message) throws Exception {\n msgParser = new MimeMessageParser(message);\n msgParser.parse();\n return msgParser.getAttachmentList();\n}\n</code></pre>\n\n<p>From a <code>DataSource</code> object you can retrieve an <code>InputStream</code> (beside name and type) of the attachment (see API: <a href=\"http://docs.oracle.com/javase/6/docs/api/javax/activation/DataSource.html?is-external=true\" rel=\"nofollow\">http://docs.oracle.com/javase/6/docs/api/javax/activation/DataSource.html?is-external=true</a>).</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API? I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with. **EDIT**: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to **read** attachments from **received** mail. Cheers, Don
Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading. The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths. Focus on the doEMailDownload method. ``` /** * Copyright (c) 2008 Steven M. Cherry * All rights reserved. */ package utils.scheduled; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Timestamp; import java.util.Properties; import java.util.Vector; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeBodyPart; import glob.ActionLogicImplementation; import glob.IOConn; import glob.log.Log; import logic.utils.sql.Settings; import logic.utils.sqldo.EMail; import logic.utils.sqldo.EMailAttach; /** * This will connect to our incoming e-mail server and download any e-mails * that are found on the server. The e-mails will be stored for further processing * in our internal database. Attachments will be written out to separate files * and then referred to by the database entries. This is intended to be run by * the scheduler every minute or so. * * @author Steven M. Cherry */ public class DownloadEMail implements ActionLogicImplementation { protected String receiving_host; protected String receiving_user; protected String receiving_pass; protected String receiving_protocol; protected boolean receiving_secure; protected String receiving_attachments; /** This will run our logic */ public void ExecuteRequest(IOConn ioc) throws Exception { Log.Trace("Enter"); Log.Debug("Executing DownloadEMail"); ioc.initializeResponseDocument("DownloadEMail"); // pick up our configuration from the server: receiving_host = Settings.getValue(ioc, "server.email.receiving.host"); receiving_user = Settings.getValue(ioc, "server.email.receiving.username"); receiving_pass = Settings.getValue(ioc, "server.email.receiving.password"); receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol"); String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure"); receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments"); // sanity check on the parameters: if(receiving_host == null || receiving_host.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no host defined. } if(receiving_user == null || receiving_user.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no user defined. } if(receiving_pass == null || receiving_pass.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no pass defined. } if(receiving_protocol == null || receiving_protocol.length() == 0){ Log.Debug("EMail receiving protocol not defined, defaulting to POP"); receiving_protocol = "POP"; } if(tmp_secure == null || tmp_secure.length() == 0 || tmp_secure.compareToIgnoreCase("false") == 0 || tmp_secure.compareToIgnoreCase("no") == 0 ){ receiving_secure = false; } else { receiving_secure = true; } if(receiving_attachments == null || receiving_attachments.length() == 0){ Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/"); receiving_attachments = "./email/attachments/"; } // now do the real work. doEMailDownload(ioc); ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); } protected void doEMailDownload(IOConn ioc) throws Exception { // Create empty properties Properties props = new Properties(); // Get the session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(receiving_protocol); store.connect(receiving_host, receiving_user, receiving_pass); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); try { // Get directory listing Message messages[] = folder.getMessages(); for (int i=0; i < messages.length; i++) { // get the details of the message: EMail email = new EMail(); email.fromaddr = messages[i].getFrom()[0].toString(); Address[] to = messages[i].getRecipients(Message.RecipientType.TO); email.toaddr = ""; for(int j = 0; j < to.length; j++){ email.toaddr += to[j].toString() + "; "; } Address[] cc; try { cc = messages[i].getRecipients(Message.RecipientType.CC); } catch (Exception e){ Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage()); cc = null; } email.cc = ""; if(cc != null){ for(int j = 0; j < cc.length; j++){ email.cc += cc[j].toString() + "; "; } } email.subject = messages[i].getSubject(); if(messages[i].getReceivedDate() != null){ email.received_when = new Timestamp(messages[i].getReceivedDate().getTime()); } else { email.received_when = new Timestamp( (new java.util.Date()).getTime()); } email.body = ""; Vector<EMailAttach> vema = new Vector<EMailAttach>(); Object content = messages[i].getContent(); if(content instanceof java.lang.String){ email.body = (String)content; } else if(content instanceof Multipart){ Multipart mp = (Multipart)content; for (int j=0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { Log.Debug("Mime type is plain"); email.body += (String)mbp.getContent(); } else { Log.Debug("Mime type is not plain"); // Special non-attachment cases here of // image/gif, text/html, ... EMailAttach ema = new EMailAttach(); ema.name = decodeName(part.getFileName()); File savedir = new File(receiving_attachments); savedir.mkdirs(); File savefile = File.createTempFile("emailattach", ".atch", savedir ); ema.path = savefile.getAbsolutePath(); ema.size = part.getSize(); vema.add(ema); ema.size = saveFile(savefile, part); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) ){ // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { Log.Debug("Mime type is plain"); email.body += (String)mbp.getContent(); } else { Log.Debug("Save file (%s)", part.getFileName() ); EMailAttach ema = new EMailAttach(); ema.name = decodeName(part.getFileName()); File savedir = new File(receiving_attachments); savedir.mkdirs(); File savefile = File.createTempFile("emailattach", ".atch", savedir ); ema.path = savefile.getAbsolutePath(); ema.size = part.getSize(); vema.add(ema); ema.size = saveFile( savefile, part); } } } } // Insert everything into the database: logic.utils.sql.EMail.insertEMail(ioc, email); for(int j = 0; j < vema.size(); j++){ vema.get(j).emailid = email.id; logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) ); } // commit this message and all of it's attachments ioc.getDBConnection().commit(); // Finally delete the message from the server. messages[i].setFlag(Flags.Flag.DELETED, true); } // Close connection folder.close(true); // true tells the mail server to expunge deleted messages. store.close(); } catch (Exception e){ folder.close(true); // true tells the mail server to expunge deleted messages. store.close(); throw e; } } protected int saveFile(File saveFile, Part part) throws Exception { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) ); byte[] buff = new byte[2048]; InputStream is = part.getInputStream(); int ret = 0, count = 0; while( (ret = is.read(buff)) > 0 ){ bos.write(buff, 0, ret); count += ret; } bos.close(); is.close(); return count; } protected String decodeName( String name ) throws Exception { if(name == null || name.length() == 0){ return "unknown"; } String ret = java.net.URLDecoder.decode( name, "UTF-8" ); // also check for a few other things in the string: ret = ret.replaceAll("=\\?utf-8\\?q\\?", ""); ret = ret.replaceAll("\\?=", ""); ret = ret.replaceAll("=20", " "); return ret; } } ```
155,507
<p>How exactly can I create a new directory using Emacs? What commands do I use? (If possible, please provide an example)</p>
[ { "answer_id": 155510, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 9, "selected": true, "text": "<ul>\n<li><p>to create the directory <code>dir/to/create</code>, type:</p>\n\n<pre><code>M-x make-directory RET dir/to/create RET\n</code></pre></li>\n<li><p>to create directories <code>dir/parent1/node</code> and <code>dir/parent2/node</code>, type:</p>\n\n<pre><code>M-! mkdir -p dir/parent{1,2}/node RET\n</code></pre>\n\n<p>It assumes that Emacs's inferior shell is <code>bash</code>/<code>zsh</code> or other compatible shell.</p></li>\n<li><p>or in a <code>Dired</code> mode </p>\n\n<pre><code>+\n</code></pre>\n\n<p>It doesn't create nonexistent parent directories.</p>\n\n<p>Example:</p>\n\n<pre><code>C-x d *.py RET ; shows python source files in the CWD in `Dired` mode\n+ test RET ; create `test` directory in the CWD\n</code></pre>\n\n<p><code>CWD</code> stands for Current Working Directory.</p></li>\n<li><p>or just create a new file with non-existing parent directories using <code>C-x C-f</code> and type:</p>\n\n<pre><code>M-x make-directory RET RET\n</code></pre></li>\n</ul>\n\n<p>Emacs asks to create the parent directories automatically while saving a new file in recent Emacs versions. For older version, see <a href=\"https://stackoverflow.com/q/6830671/4279\">How to make Emacs create intermediate dirs - when saving a file?</a></p>\n" }, { "answer_id": 155519, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 6, "selected": false, "text": "<p><kbd>Ctrl</kbd>+<kbd>X</kbd> <kbd>D</kbd> (<code>C-x d</code>) to open a directory in \"dired\" mode, then <kbd>+</kbd> to create a directory.</p>\n" }, { "answer_id": 155616, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 3, "selected": false, "text": "<p>You can also run single shell commands using <code>M-!</code></p>\n\n<p>You're basically sending a string to the command line so you don't get any nice auto-completion but it's useful if you know how to perform an action through the command line but don't know an Emacs equivalent way.</p>\n\n<pre><code>M-! mkdir /path/to/new_dir\n</code></pre>\n" }, { "answer_id": 156001, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 3, "selected": false, "text": "<p>You can use <kbd>M-x</kbd> <code>make-directory</code> inside of any buffer, not necessarily a dired buffer. It is a lisp function you can use as well.</p>\n" }, { "answer_id": 7217039, "author": "etank", "author_id": 271884, "author_profile": "https://Stackoverflow.com/users/271884", "pm_score": 3, "selected": false, "text": "<p>I guess I did it the hard way earlier today. I did:</p>\n\n<pre><code>M-x shell-command\n</code></pre>\n\n<p>then</p>\n\n<pre><code>mkdir -p topdir/subdir\n</code></pre>\n" }, { "answer_id": 14114348, "author": "Brian Taylor", "author_id": 457547, "author_profile": "https://Stackoverflow.com/users/457547", "pm_score": 2, "selected": false, "text": "<p>I came across this question while searching for how to automatically create directories in Emacs. The best answer I found was in <a href=\"https://stackoverflow.com/questions/6830671/how-to-make-emacs-create-intermediate-dirs-when-saving-a-file\">another thread</a> from a few years later. The answer from <a href=\"https://stackoverflow.com/users/513266/victor-deryagin\">Victor Deryagin</a> was exactly what I was looking for. Adding that code to your .emacs will make Emacs prompt you to create the directory when you go to save the file.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
How exactly can I create a new directory using Emacs? What commands do I use? (If possible, please provide an example)
* to create the directory `dir/to/create`, type: ``` M-x make-directory RET dir/to/create RET ``` * to create directories `dir/parent1/node` and `dir/parent2/node`, type: ``` M-! mkdir -p dir/parent{1,2}/node RET ``` It assumes that Emacs's inferior shell is `bash`/`zsh` or other compatible shell. * or in a `Dired` mode ``` + ``` It doesn't create nonexistent parent directories. Example: ``` C-x d *.py RET ; shows python source files in the CWD in `Dired` mode + test RET ; create `test` directory in the CWD ``` `CWD` stands for Current Working Directory. * or just create a new file with non-existing parent directories using `C-x C-f` and type: ``` M-x make-directory RET RET ``` Emacs asks to create the parent directories automatically while saving a new file in recent Emacs versions. For older version, see [How to make Emacs create intermediate dirs - when saving a file?](https://stackoverflow.com/q/6830671/4279)
155,517
<p>Is it possible to cancel out of a long running process in VB6.0 without using DoEvents?</p> <p>For example:</p> <pre><code>for i = 1 to someVeryHighNumber ' Do some work here ' ... if cancel then exit for end if next Sub btnCancel_Click() cancel = true End Sub </code></pre> <p>I assume I need a "DoEvents" before the "if cancel then..." is there a better way? It's been awhile...</p>
[ { "answer_id": 155527, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 3, "selected": false, "text": "<p>Is the \"for\" loop running in the GUI thread? If so, yes, you'll need a DoEvents. You may want to use a separate Thread, in which case a DoEvents would not be required. You <a href=\"http://www.freevbcode.com/ShowCode.Asp?ID=1287\" rel=\"nofollow noreferrer\">can do this in VB6</a> (not simple).</p>\n" }, { "answer_id": 155539, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 3, "selected": false, "text": "<p>No, you have to use DoEvents otherwise all UI, keyboard and Timer events will stay waiting in the queue.</p>\n\n<p>The only thing you can do is calling DoEvents once for every 1000 iterations or such.</p>\n" }, { "answer_id": 155541, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p>You could start it on a separate thread, but in VB6 it's a royal pain. DoEvents should work. It's a hack, but then so is VB6 (10 year VB veteran talking here, so don't down-mod me).</p>\n" }, { "answer_id": 156158, "author": "Bob", "author_id": 24007, "author_profile": "https://Stackoverflow.com/users/24007", "pm_score": 2, "selected": false, "text": "<p>Divide up the long-running task into quanta. Such tasks are often driven by a simple loop, so slice it into 10, 100, 1000, etc. iterations. Use a Timer control and each time it fires do part of the task and save its state as you go. To start, set up initial state and enable the Timer. When complete, disable the Timer and process the results.</p>\n\n<p>You can \"tune\" this by changing how much work is done per quantum. In the Timer event handler you can check for \"cancel\" and stop early as required. You can make it all neater by bundling the workload and Timer into a UserControl with a Completed event.</p>\n" }, { "answer_id": 160893, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 6, "selected": true, "text": "<p>Nope, you got it right, you definitely want DoEvents in your loop.</p>\n\n<p>If you put the <code>DoEvents</code> in your main loop and find that slows down processing too much, try calling the Windows API function <code>GetQueueStatus</code> (which is much faster than DoEvents) to quickly determine if it's even necessary to call DoEvents. <code>GetQueueStatus</code> tells you if there are any events to process.</p>\n\n<pre><code>' at the top:\nDeclare Function GetQueueStatus Lib \"user32\" (ByVal qsFlags As Long) As Long\n\n' then call this instead of DoEvents:\nSub DoEventsIfNecessary()\n If GetQueueStatus(255) &lt;&gt; 0 Then DoEvents\nEnd Sub\n</code></pre>\n" }, { "answer_id": 206791, "author": "Shane Miskin", "author_id": 16415, "author_profile": "https://Stackoverflow.com/users/16415", "pm_score": 2, "selected": false, "text": "<p>This works well for me when I need it. It checks to see if the user has pressed the escape key to exit the loop.</p>\n\n<p>Note that it has a really big drawback: it will detect if the user hit the escape key on ANY application - not just yours. But it's a great trick in development when you want to give yourself a way to interrupt a long running loop, or a way to hold down the shift key to bypass a bit of code.</p>\n\n<pre><code>Option Explicit\n\nPrivate Declare Function GetAsyncKeyState Lib \"user32\" (ByVal nVirtKey As Long) As Integer\n\nPrivate Sub Command1_Click()\n Do\n Label1.Caption = Now()\n Label1.Refresh\n If WasKeyPressed(vbKeyEscape) Then Exit Do\n Loop\n\n Label1.Caption = \"Exited loop successfully\"\n\nEnd Sub\n\nFunction WasKeyPressed(ByVal plVirtualKey As Long) As Boolean\n If (GetAsyncKeyState(plVirtualKey) And &amp;H8000) Then WasKeyPressed = True\nEnd Function\n</code></pre>\n\n<p>Documentation for GetAsyncKeyState is here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms646301(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms646301(VS.85).aspx</a></p>\n" }, { "answer_id": 413935, "author": "MarkJ", "author_id": 15639, "author_profile": "https://Stackoverflow.com/users/15639", "pm_score": 2, "selected": false, "text": "<p><strong>EDIT</strong> it <a href=\"https://stackoverflow.com/questions/2785169/using-the-net-backgroundworker-from-vb6-fails-with-an-accessviolationexception\">turns out</a> the MSDN article is flawed and the technique <a href=\"https://stackoverflow.com/questions/2785169/using-the-net-backgroundworker-from-vb6-fails-with-an-accessviolationexception\"><strong>DOESN'T WORK</strong></a> :(</p>\n\n<p>Here's an article on using the <a href=\"http://msdn.microsoft.com/en-us/library/aa719109.aspx\" rel=\"nofollow noreferrer\">.NET BackgroundWorker</a> component to run the task on another thread from within VB6.</p>\n" }, { "answer_id": 1561574, "author": "MarkJ", "author_id": 15639, "author_profile": "https://Stackoverflow.com/users/15639", "pm_score": 2, "selected": false, "text": "<p>Here is a pretty standard scheme for asynchronous background processing in VB6. (For instance it's in Dan Appleman's <a href=\"http://www.amazon.co.uk/Applemans-Developing-ActiveX-Components-Visual/dp/1562765760\" rel=\"nofollow noreferrer\">book</a> and Microsoft's VB6 <a href=\"http://msdn.microsoft.com/en-us/library/aa445814(VS.60).aspx\" rel=\"nofollow noreferrer\">samples</a>.) You create a separate ActiveX EXE to do the work: that way the work is automatically on another thread, in a separate process (which means you don't have to worry about variables being trampled). </p>\n\n<ul>\n<li>The VB6 ActiveX EXE object should expose an event CheckQuitDoStuff(). This takes a ByRef Boolean called Quit. </li>\n<li>The client calls StartDoStuff in the ActiveX EXE object. This routine starts a Timer on a hidden form and <strong>immediately returns</strong>. This unblocks the calling thread. The Timer interval is very short so the Timer event fires quickly. </li>\n<li>The Timer event handler disables the Timer, and then calls back into the ActiveX object DoStuff method. This begins the lengthy processing. </li>\n<li>Periodically the DoStuff method raises the CheckQuitDoStuff event. The client's event handler checks the special flag and sets Quit True if it's necessary to abort. Then DoStuff aborts the calculation and returns early if Quit is True. </li>\n</ul>\n\n<p>This scheme means that the client doesn't actually need to be multi-threaded, since the calling thread doesn't block while \"DoStuff\" is happening. The tricky part is making sure that DoStuff raises the events at appropriate intervals - too long, and you can't quit when you want to: too short, and you are slowing down DoStuff unecessarily. Also, when DoStuff exits, it must unload the hidden form.</p>\n\n<p>If DoStuff does actually manage to get all the stuff done before being aborted, you can raise a different event to tell the client that the job is finished.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019/" ]
Is it possible to cancel out of a long running process in VB6.0 without using DoEvents? For example: ``` for i = 1 to someVeryHighNumber ' Do some work here ' ... if cancel then exit for end if next Sub btnCancel_Click() cancel = true End Sub ``` I assume I need a "DoEvents" before the "if cancel then..." is there a better way? It's been awhile...
Nope, you got it right, you definitely want DoEvents in your loop. If you put the `DoEvents` in your main loop and find that slows down processing too much, try calling the Windows API function `GetQueueStatus` (which is much faster than DoEvents) to quickly determine if it's even necessary to call DoEvents. `GetQueueStatus` tells you if there are any events to process. ``` ' at the top: Declare Function GetQueueStatus Lib "user32" (ByVal qsFlags As Long) As Long ' then call this instead of DoEvents: Sub DoEventsIfNecessary() If GetQueueStatus(255) <> 0 Then DoEvents End Sub ```
155,532
<p>Are there any good methods for getting ASP.NET 2.0 to validate under the XHTML 1.0 Strict (or Transitional) DTD? I'm interested to hear some ideas before I hack up the core of the HTTP response.</p> <p>One major problem is the form tag itself, this is the output I got from W3C when I tried to validate:</p> <pre><code>Line 13, Column 11: there is no attribute "name". &lt;form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript </code></pre> <p>That tag is very fundamental to ASP.NET, as you all know. Hmmmm.</p>
[ { "answer_id": 155553, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 2, "selected": false, "text": "<p>Its possible to change the output of ASP.NET controls using techniques like the <a href=\"http://www.asp.net/CssAdapters/\" rel=\"nofollow noreferrer\">CSS Adapters</a>. Although I wouldn't personally recommend you use these out of the box, it might give you some hints on a good solution.</p>\n\n<p>I generally avoid using the ASP.NET controls where ever possible, except ones that don't generate markup on their own such as the Repeater control. I would look into the ASP.NET MVC framework (what StackOverflow is built on) as this gives you 100% control over markup.</p>\n" }, { "answer_id": 155562, "author": "Gabriel Isenberg", "author_id": 1473493, "author_profile": "https://Stackoverflow.com/users/1473493", "pm_score": 2, "selected": false, "text": "<p>Have you considered the <a href=\"http://www.asp.net/mvc/\" rel=\"nofollow noreferrer\">ASP.NET MVC Framework</a>? It's likely to be a better bet if strict XHTML compliance is a requirement. You gain more control of your output, but you'll be treading unfamiliar territory if you're already comfortable with the traditional ASP.NET model.</p>\n" }, { "answer_id": 156533, "author": "Calroth", "author_id": 23358, "author_profile": "https://Stackoverflow.com/users/23358", "pm_score": 5, "selected": true, "text": "<p>ASP.NET 2.0 and above can indeed output Strict (or Transitional) XHTML. This will resolve your 'there is no attribute \"name\"' validation error, amongst other things. To set this up, update your Web.config file with something like:</p>\n\n<pre><code>&lt;system.web&gt;\n ... other configuration goes here ...\n &lt;xhtmlConformance mode=\"Strict\" /&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>For Transitional XHTML, use <code>mode=\"Transitional\"</code> instead.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ms178159.aspx\" rel=\"nofollow noreferrer\">How to: Configure XHTML Rendering in ASP.NET Web Sites</a> on MSDN.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12252/" ]
Are there any good methods for getting ASP.NET 2.0 to validate under the XHTML 1.0 Strict (or Transitional) DTD? I'm interested to hear some ideas before I hack up the core of the HTTP response. One major problem is the form tag itself, this is the output I got from W3C when I tried to validate: ``` Line 13, Column 11: there is no attribute "name". <form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript ``` That tag is very fundamental to ASP.NET, as you all know. Hmmmm.
ASP.NET 2.0 and above can indeed output Strict (or Transitional) XHTML. This will resolve your 'there is no attribute "name"' validation error, amongst other things. To set this up, update your Web.config file with something like: ``` <system.web> ... other configuration goes here ... <xhtmlConformance mode="Strict" /> </system.web> ``` For Transitional XHTML, use `mode="Transitional"` instead. See [How to: Configure XHTML Rendering in ASP.NET Web Sites](http://msdn.microsoft.com/en-us/library/ms178159.aspx) on MSDN.
155,540
<p>I'm writing a scheduler or sorts. It's basically a table with a list of exes (like "C:\a.exe") and a console app that looks at the records in the table every minute or so and runs the tasks that haven't been run yet.</p> <p>I run the tasks like this:</p> <pre><code>System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = someExe; // like "a.exe" p.Start(); </code></pre> <p>How can I tell if a particular task failed? For example what if a.exe throws an unhandled exception? I'd like the above code to know when this happens and update the tasks table with something like "the particular task failed" etc.</p> <p>How can I do this?</p> <p>I'm not using the Sql Agent or the Windows Scheduler because someone else told me not to. He has more "experience" so I'm basically just following orders. Feel free to suggest alternatives.</p>
[ { "answer_id": 155554, "author": "Kenny Mann", "author_id": 18217, "author_profile": "https://Stackoverflow.com/users/18217", "pm_score": 3, "selected": false, "text": "<p>I think you're looking for Process.ExitCode, assuming the process returns one.\nYou may need to use WaitForExit() though. There is also an ErrorDataReceived event which is triggered when an app sends to stderr.</p>\n" }, { "answer_id": 155563, "author": "Pete", "author_id": 76, "author_profile": "https://Stackoverflow.com/users/76", "pm_score": 2, "selected": false, "text": "<p>In addition to the ExitCode, you can also do something like this:</p>\n\n<pre><code>string output = p.StandardOutput.ReadToEnd();\n</code></pre>\n\n<p>That will capture everything that would have been written to a command window. Then you can parse that string for known patterns for displaying errors, depending on the app.</p>\n" }, { "answer_id": 155588, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": true, "text": "<p>You can catch the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx\" rel=\"noreferrer\">Win32Exception</a> to check if <a href=\"http://msdn.microsoft.com/en-us/library/e8zac0ca.aspx\" rel=\"noreferrer\">Process.Start()</a> failed due to the file not existing or execute access is denied.</p>\n\n<p>But you can not catch exceptions thrown by the processes that you create using this class. In the first place, the application might not be written in .NET so there might not be a concept of exception at all.</p>\n\n<p>What you can do is check on the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx\" rel=\"noreferrer\">ExitCode</a> of the application or read the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx\" rel=\"noreferrer\">StandardOutput</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx\" rel=\"noreferrer\">StandardError</a> streams to check whether error messages are being posted.</p>\n" }, { "answer_id": 157096, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 0, "selected": false, "text": "<p>To expand on what @jop said. You will also need to wait for the process to close. Thus:</p>\n\n<pre><code> p.Start();\n p.WaitForExit();\n int returnCode = p.ExitCode;\n</code></pre>\n\n<p>Non-zero codes are typically errors. Some application use negative ones are errors, and positive ones as status codes/warnings.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I'm writing a scheduler or sorts. It's basically a table with a list of exes (like "C:\a.exe") and a console app that looks at the records in the table every minute or so and runs the tasks that haven't been run yet. I run the tasks like this: ``` System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = someExe; // like "a.exe" p.Start(); ``` How can I tell if a particular task failed? For example what if a.exe throws an unhandled exception? I'd like the above code to know when this happens and update the tasks table with something like "the particular task failed" etc. How can I do this? I'm not using the Sql Agent or the Windows Scheduler because someone else told me not to. He has more "experience" so I'm basically just following orders. Feel free to suggest alternatives.
You can catch the [Win32Exception](http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx) to check if [Process.Start()](http://msdn.microsoft.com/en-us/library/e8zac0ca.aspx) failed due to the file not existing or execute access is denied. But you can not catch exceptions thrown by the processes that you create using this class. In the first place, the application might not be written in .NET so there might not be a concept of exception at all. What you can do is check on the [ExitCode](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx) of the application or read the [StandardOutput](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx) and [StandardError](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx) streams to check whether error messages are being posted.
155,544
<p>I need to create a unique ID for a given location, and the location's ID must be sequential. So its basically like a primary key, except that it is also tied to the locationID. So 3 different locations will all have ID's like 1,2,3,4,5,...,n</p> <p>What is the best way to do this? I also need a safe way of getting the nextID for a given location, I'm guessing I can just put a transaction on the stored procedure that gets the next ID?</p>
[ { "answer_id": 155557, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<p>You'll want to wrap both the code to find the next ID and the code to save the row in the same transaction. You don't want (pseudocode):</p>\n\n<pre><code>transaction {\n id = getId\n}\n\n... other processing\n\ntransaction {\n createRowWithNewId\n}\n</code></pre>\n\n<p>Because another object with that id could be saved during \"... other processing\"</p>\n" }, { "answer_id": 155592, "author": "David Smith", "author_id": 17201, "author_profile": "https://Stackoverflow.com/users/17201", "pm_score": 2, "selected": false, "text": "<p>One of the ways I've seen this done is by creating a table mapping the location to the next ID.</p>\n\n<pre><code>CREATE TABLE LocationID {\n Location varchar(32) PRIMARY KEY,\n NextID int DEFAULT(1)\n}\n</code></pre>\n\n<p>Inside your stored procedure you can do an update and grab the current value while also incrementing the value:</p>\n\n<pre><code>...\nUPDATE LocationID SET @nextID = NextID, NextID = NextID + 1 WHERE Location = @Location\n...\n</code></pre>\n\n<p>The above may not be very portable and you may end up getting the incremented value instead of the current one. You can adjust the default for the column as desired.</p>\n\n<p>Another thing to be cautious of is how often you'll be hitting this and if you're going to hit it from another stored procedure, or from application code. If it's from another stored procedure, then one at a time is probably fine. If you're going to hit it from application code, you might be better off grabbing a range of values and then doling them out to your application one by one and then grabbing another range. This could leave gaps in your sequence if the application goes down while it still has a half allocated block.</p>\n" }, { "answer_id": 44853081, "author": "S3S", "author_id": 6167855, "author_profile": "https://Stackoverflow.com/users/6167855", "pm_score": 0, "selected": false, "text": "<p>If this doesn't need to be persisted, you could always do this in your query versus storing it in the table itself.</p>\n\n<pre><code>select\n locationID\n ,row_number() over (partition by locationID order by (select null)) as LocationPK\nFrom\n YourTable\n</code></pre>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I need to create a unique ID for a given location, and the location's ID must be sequential. So its basically like a primary key, except that it is also tied to the locationID. So 3 different locations will all have ID's like 1,2,3,4,5,...,n What is the best way to do this? I also need a safe way of getting the nextID for a given location, I'm guessing I can just put a transaction on the stored procedure that gets the next ID?
One of the ways I've seen this done is by creating a table mapping the location to the next ID. ``` CREATE TABLE LocationID { Location varchar(32) PRIMARY KEY, NextID int DEFAULT(1) } ``` Inside your stored procedure you can do an update and grab the current value while also incrementing the value: ``` ... UPDATE LocationID SET @nextID = NextID, NextID = NextID + 1 WHERE Location = @Location ... ``` The above may not be very portable and you may end up getting the incremented value instead of the current one. You can adjust the default for the column as desired. Another thing to be cautious of is how often you'll be hitting this and if you're going to hit it from another stored procedure, or from application code. If it's from another stored procedure, then one at a time is probably fine. If you're going to hit it from application code, you might be better off grabbing a range of values and then doling them out to your application one by one and then grabbing another range. This could leave gaps in your sequence if the application goes down while it still has a half allocated block.
155,584
<p>I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly.</p> <p>The designer is including <a href="http://stlartworks.efficionconsulting.com/Portals/6/Skins/ArtWorks/img/ProgramsHeading.png" rel="noreferrer">a file like this</a> for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names.</p>
[ { "answer_id": 155595, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 3, "selected": false, "text": "<p>On the server-side you can do this easily enough without annoying search engines AFAIK.</p>\n\n<pre><code>// This server-side code example is in JavaScript because that's\n// what I know best.\nvar words = split(message, \" \");\nvar c = 1;\nfor(var i = 0; i &lt; words.length; i++) {\n print(\"&lt;span class=\\\"color\" + c + \"\\\"&gt;\" + words[i] + \"&lt;/span&gt; \");\n c = c + 1; if (c &gt; 3) c = 1;\n}\n</code></pre>\n\n<p>If you really want dead simple inline HTML code, write client-side Javascript to retrieve the message out of a given P or DIV or whatever based on its ID, split it, recode it as above, and replace the P or DIV's 'innerHTML' attribute.</p>\n" }, { "answer_id": 157458, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 3, "selected": false, "text": "<p>There’s definitely no solution using just CSS, as CSS selectors give you no access to individual letters (apart from <code>:first-letter</code>).</p>\n" }, { "answer_id": 163986, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I'd rather not have to manually generate an image for every page </p>\n</blockquote>\n\n<p>Then generate the image automatically.</p>\n\n<p>You don't specify which server-side technology you're using, but any good one will allow you to manipulate images (or at least call an external image utility)</p>\n\n<p>So the non-technical users would just need to do something like this:</p>\n\n<pre><code>&lt;img src=\"images/redblueyellow.cfm/programs.png\" alt=\"programs\"/&gt;\n</code></pre>\n\n<p>And the redblueyellow.cfm script would then either use an existing programs.png or generate a new image with the multiple colours as desired.</p>\n\n<p>I can provide sample CFML or pseudo-code to do this, if you'd like?</p>\n" }, { "answer_id": 164131, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 5, "selected": true, "text": "<p>Here is some JavaScript.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var message = \"The quick brown fox.\";\r\nvar colors = new Array(\"#ff0000\",\"#00ff00\",\"#0000ff\"); // red, green, blue\r\n\r\nfor (var i = 0; i &lt; message.length; i++){\r\n document.write(\"&lt;span style=\\\"color:\" + colors[(i % colors.length)] + \";\\\"&gt;\" + message[i] + \"&lt;/span&gt;\");\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4318/" ]
I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly. The designer is including [a file like this](http://stlartworks.efficionconsulting.com/Portals/6/Skins/ArtWorks/img/ProgramsHeading.png) for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names.
Here is some JavaScript. ```js var message = "The quick brown fox."; var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue for (var i = 0; i < message.length; i++){ document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>"); } ```
155,586
<p>We use the DesignSurface and all that good IDesignerHost goodness in our own designer. The designed forms are then persisted in our own bespoke format and all that works great. WE also want to export the forms to a text-based format (which we've done as it isn't that difficult).</p> <p>However, we also want to import that text back into a document for the designer which involves getting the designer code back into a CodeCompileUnit. Unfortunately, the Parse method is not implemented (for, no doubt, good reasons). Is there an alternative? We don't want to use anything that wouldn't exist on a standard .NET installation (like .NET libraries installed with Visual Studio).</p> <p>My current idea is to compile the imported text and then instantiate the form and copy its properties and controls over to the design surface object, and just capture the new CodeCompileUnit, but I was hoping there was a better way. Thanks.</p> <hr> <p>UPDATE: I though some might be interested in our progress. So far, not so good. A brief overview of what I've discovered is that the Parse method was not implemented because it was deemed too difficult, open source parsers exist that do the work but they're not complete and therefore aren't guaranteed to work in all cases (NRefactory is one of those from the SharpDevelop project, I believe), and the copying of controls across from an instance to the designer isn't working as yet. I believe this is because although the controls are getting added to the form instance that the designer surface wraps, the designer surface is not aware of their inclusion. Our next attempt is to mimic cut/paste to see if that solves it. Obviously, this is a huge nasty workaround, but we need it working so we'll take the hit and keep an eye out for alternatives.</p>
[ { "answer_id": 155595, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 3, "selected": false, "text": "<p>On the server-side you can do this easily enough without annoying search engines AFAIK.</p>\n\n<pre><code>// This server-side code example is in JavaScript because that's\n// what I know best.\nvar words = split(message, \" \");\nvar c = 1;\nfor(var i = 0; i &lt; words.length; i++) {\n print(\"&lt;span class=\\\"color\" + c + \"\\\"&gt;\" + words[i] + \"&lt;/span&gt; \");\n c = c + 1; if (c &gt; 3) c = 1;\n}\n</code></pre>\n\n<p>If you really want dead simple inline HTML code, write client-side Javascript to retrieve the message out of a given P or DIV or whatever based on its ID, split it, recode it as above, and replace the P or DIV's 'innerHTML' attribute.</p>\n" }, { "answer_id": 157458, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 3, "selected": false, "text": "<p>There’s definitely no solution using just CSS, as CSS selectors give you no access to individual letters (apart from <code>:first-letter</code>).</p>\n" }, { "answer_id": 163986, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I'd rather not have to manually generate an image for every page </p>\n</blockquote>\n\n<p>Then generate the image automatically.</p>\n\n<p>You don't specify which server-side technology you're using, but any good one will allow you to manipulate images (or at least call an external image utility)</p>\n\n<p>So the non-technical users would just need to do something like this:</p>\n\n<pre><code>&lt;img src=\"images/redblueyellow.cfm/programs.png\" alt=\"programs\"/&gt;\n</code></pre>\n\n<p>And the redblueyellow.cfm script would then either use an existing programs.png or generate a new image with the multiple colours as desired.</p>\n\n<p>I can provide sample CFML or pseudo-code to do this, if you'd like?</p>\n" }, { "answer_id": 164131, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 5, "selected": true, "text": "<p>Here is some JavaScript.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var message = \"The quick brown fox.\";\r\nvar colors = new Array(\"#ff0000\",\"#00ff00\",\"#0000ff\"); // red, green, blue\r\n\r\nfor (var i = 0; i &lt; message.length; i++){\r\n document.write(\"&lt;span style=\\\"color:\" + colors[(i % colors.length)] + \";\\\"&gt;\" + message[i] + \"&lt;/span&gt;\");\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23234/" ]
We use the DesignSurface and all that good IDesignerHost goodness in our own designer. The designed forms are then persisted in our own bespoke format and all that works great. WE also want to export the forms to a text-based format (which we've done as it isn't that difficult). However, we also want to import that text back into a document for the designer which involves getting the designer code back into a CodeCompileUnit. Unfortunately, the Parse method is not implemented (for, no doubt, good reasons). Is there an alternative? We don't want to use anything that wouldn't exist on a standard .NET installation (like .NET libraries installed with Visual Studio). My current idea is to compile the imported text and then instantiate the form and copy its properties and controls over to the design surface object, and just capture the new CodeCompileUnit, but I was hoping there was a better way. Thanks. --- UPDATE: I though some might be interested in our progress. So far, not so good. A brief overview of what I've discovered is that the Parse method was not implemented because it was deemed too difficult, open source parsers exist that do the work but they're not complete and therefore aren't guaranteed to work in all cases (NRefactory is one of those from the SharpDevelop project, I believe), and the copying of controls across from an instance to the designer isn't working as yet. I believe this is because although the controls are getting added to the form instance that the designer surface wraps, the designer surface is not aware of their inclusion. Our next attempt is to mimic cut/paste to see if that solves it. Obviously, this is a huge nasty workaround, but we need it working so we'll take the hit and keep an eye out for alternatives.
Here is some JavaScript. ```js var message = "The quick brown fox."; var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue for (var i = 0; i < message.length; i++){ document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>"); } ```
155,649
<p>What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: <code>xValues</code> and <code>yValues</code>. (I'm trying to get the coordinates so I can animate an object along a path.)</p> <p><strong>Here's what I have so far:</strong></p> <pre><code>circle: function(radius, steps, centerX, centerY){ var xValues = [centerX]; var yValues = [centerY]; for (var i = 1; i &lt; steps; i++) { xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2)); yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2)); } } </code></pre>
[ { "answer_id": 155653, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "<p>If you already have half a circle, just mirror the points to get the other half<br>\nmake sure you do this in the right order.</p>\n\n<p>more speficically, for the other half you simply replace the \"<code>+ sin(...)</code>\" with a \"<code>- sin(...)</code>\" </p>\n" }, { "answer_id": 155662, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "<p>You need to use a partial function to input the radians into cos and sin; therefore take the values you're getting for a quarter or half of the circle, and reflect them over the center points' axis to get your full circle.</p>\n\n<p>That said JavaScript's sin and cos aren't quite as picky, so you must have halved your radian or something; I'd write it as:</p>\n\n<pre><code>function circle(radius, steps, centerX, centerY){\n var xValues = [centerX];\n var yValues = [centerY];\n var table=\"&lt;tr&gt;&lt;th&gt;Step&lt;/th&gt;&lt;th&gt;X&lt;/th&gt;&lt;th&gt;Y&lt;/th&gt;&lt;/tr&gt;\";\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.fillStyle = \"red\"\n ctx.beginPath();\n for (var i = 0; i &lt;= steps; i++) {\n var radian = (2*Math.PI) * (i/steps);\n xValues[i+1] = centerX + radius * Math.cos(radian);\n yValues[i+1] = centerY + radius * Math.sin(radian);\n if(0==i){ctx.moveTo(xValues[i+1],yValues[i+1]);}else{ctx.lineTo(xValues[i+1],yValues[i+1]);}\n table += \"&lt;tr&gt;&lt;td&gt;\" + i + \"&lt;/td&gt;&lt;td&gt;\" + xValues[i+1] + \"&lt;/td&gt;&lt;td&gt;\" + yValues[i+1] + \"&lt;/td&gt;&lt;/tr&gt;\";\n }\n ctx.fill();\n return table;\n}\ndocument.body.innerHTML=\"&lt;canvas id=\\\"canvas\\\" width=\\\"300\\\" height=\\\"300\\\"&gt;&lt;/canvas&gt;&lt;table id=\\\"table\\\"/&gt;\";\ndocument.getElementById(\"table\").innerHTML+=circle(150,15,150,150);\n</code></pre>\n\n<p>I assumed that for whatever reason you wanted xValues[0] and yValues[0] to be centerX and centerY. I can't figure out why you'd want that, as they're values passed into the function already.</p>\n" }, { "answer_id": 155678, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 0, "selected": false, "text": "<p>I was able to solve it on my own by multiplying the number of steps by 2:</p>\n\n<pre><code>circle: function(radius, steps, centerX, centerY){\n var xValues = [centerX];\n var yValues = [centerY];\n for (var i = 1; i &lt; steps; i++) {\n xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps*2-Math.PI/2));\n yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps*2-Math.PI/2));\n }\n}\n</code></pre>\n" }, { "answer_id": 155680, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 6, "selected": true, "text": "<p>Your loop should be set up like this instead:</p>\n\n<pre><code>for (var i = 0; i &lt; steps; i++) {\n xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));\n yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));\n}\n</code></pre>\n\n<ul>\n<li>Start your loop at 0</li>\n<li>Step through the entire 2 * PI range, not just PI.</li>\n<li>You shouldn't have the <code>var xValues = [centerX]; var yValues = [centerY];</code> -- the center of the circle is not a part of it.</li>\n</ul>\n" }, { "answer_id": 155686, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 3, "selected": false, "text": "<p>Bresenham's algorithm is way faster. You hear of it in relation to drawing straight lines, but there's a form of the algorithm for circles.</p>\n\n<p>Whether you use that or continue with the trig calculations (which are blazingly fast these days) - you only need to draw 1/8th of the circle. By swapping x,y you can get another 1/8th, and then the negative of x, of y, and of both - swapped and unswapped - gives you points for all the rest of the circle. A speedup of 8x!</p>\n" }, { "answer_id": 155688, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Change:</p>\n\n<pre><code>Math.PI * i / steps\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>2*Math.PI * i / steps\n</code></pre>\n\n<p>A full circle is 2pi radians, and you are only going to pi radians.</p>\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: `xValues` and `yValues`. (I'm trying to get the coordinates so I can animate an object along a path.) **Here's what I have so far:** ``` circle: function(radius, steps, centerX, centerY){ var xValues = [centerX]; var yValues = [centerY]; for (var i = 1; i < steps; i++) { xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2)); yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2)); } } ```
Your loop should be set up like this instead: ``` for (var i = 0; i < steps; i++) { xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps)); yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps)); } ``` * Start your loop at 0 * Step through the entire 2 \* PI range, not just PI. * You shouldn't have the `var xValues = [centerX]; var yValues = [centerY];` -- the center of the circle is not a part of it.
155,669
<p>I have Flex based consumer <a href="http://www.rollingrazor.com" rel="nofollow noreferrer">website</a> where I would like to change various look and feel type settings based on random and other criteria, and then track these through to what results in the most sales. </p> <p>For instance I might completely switch out the homepage, show different things depending upon where people come from. I might show or hide certain features, or change certain text. The things i might change are as yet undefined and will likely become quite complicated.</p> <p>I want to design the most flexible database schema but it must be efficient and easy to search. Currently I have a 'SiteVisit' table which contains information about each distinct visitor.</p> <p>I want to find the right balance between a single table with columns for each setting, and a table containing just key value pairs.</p> <p>Any suggestions? </p>
[ { "answer_id": 627904, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 2, "selected": false, "text": "<p>Ok, this is very tricky. The reason for me to say that is because you are asking for two things:</p>\n\n<ul>\n<li>relaxed repository schema so that you can store various data and change what gets saved dynamically later</li>\n<li>fixed database schema so that you can query data effectively</li>\n</ul>\n\n<p>The solution will be a compromise. You have to understand that. </p>\n\n<p>Let's assume that you have User table:</p>\n\n<pre><code>+----------------\n| User\n+----------------\n| UserId (PK)\n| ...\n+----------------\n</code></pre>\n\n<p>1) XML blob approach\nYou can either save your data as a blog (big XML) into a table (actually a property bag) but querying (filtering) will be a nightmare.</p>\n\n<pre><code>+----------------\n| CustomProperty\n+----------------\n| PropId (PK)\n| UserId (FK)\n| Data of type memo/binary/...\n+----------------\n</code></pre>\n\n<p>Advantage is that you (business logic) own the schema. This is at the same time disadvantage of this solution. Another HUGE disadvantage is that querying/filtering will be EXTREMELY difficult and SLOW!</p>\n\n<p>2) Table per property\nAnother solution is to make a special table per property (homepage, etc.). This table would contain value per user (FK based realtionship to the User table).</p>\n\n<pre><code>+----------------\n| HomePage\n+----------------\n| HomePageId (PK)\n| UserId (FK)\n| Value of type string\n+----------------\n</code></pre>\n\n<p>Advantage of this approach is that you can very quickly see all the values for that property. Disadvantage is that you will have too many tables (one per custom property) and that you will join tables often during query operations.</p>\n\n<p>3) CustomProperty table\nIn this solution you have one table holding all custom properties. </p>\n\n<pre><code>+----------------\n| CustomPropertyEnum\n+----------------\n| PropertyId (PK)\n| Name of type string\n+----------------\n\n+----------------\n| CustomProperty\n+----------------\n| PropId (PK)\n| PropertyId (FK)\n| UserId (FK)\n| Value of type string\n+----------------\n</code></pre>\n\n<p>In this solution you store all custom properties in one table. You also have a special enum table that allows you to more efficiently query data. The disadvantage is that you will join tables often during query operations.</p>\n\n<p>Choose for yourself. I would decide between 2 and 3 depending on your workload (most probably 3 because it is easier).</p>\n" }, { "answer_id": 24899225, "author": "Liam", "author_id": 748766, "author_profile": "https://Stackoverflow.com/users/748766", "pm_score": 1, "selected": false, "text": "<p>This is a classic case for using a NoSQL database. It could be used to store various key value pairs with ease and without any predefined schema. </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
I have Flex based consumer [website](http://www.rollingrazor.com) where I would like to change various look and feel type settings based on random and other criteria, and then track these through to what results in the most sales. For instance I might completely switch out the homepage, show different things depending upon where people come from. I might show or hide certain features, or change certain text. The things i might change are as yet undefined and will likely become quite complicated. I want to design the most flexible database schema but it must be efficient and easy to search. Currently I have a 'SiteVisit' table which contains information about each distinct visitor. I want to find the right balance between a single table with columns for each setting, and a table containing just key value pairs. Any suggestions?
Ok, this is very tricky. The reason for me to say that is because you are asking for two things: * relaxed repository schema so that you can store various data and change what gets saved dynamically later * fixed database schema so that you can query data effectively The solution will be a compromise. You have to understand that. Let's assume that you have User table: ``` +---------------- | User +---------------- | UserId (PK) | ... +---------------- ``` 1) XML blob approach You can either save your data as a blog (big XML) into a table (actually a property bag) but querying (filtering) will be a nightmare. ``` +---------------- | CustomProperty +---------------- | PropId (PK) | UserId (FK) | Data of type memo/binary/... +---------------- ``` Advantage is that you (business logic) own the schema. This is at the same time disadvantage of this solution. Another HUGE disadvantage is that querying/filtering will be EXTREMELY difficult and SLOW! 2) Table per property Another solution is to make a special table per property (homepage, etc.). This table would contain value per user (FK based realtionship to the User table). ``` +---------------- | HomePage +---------------- | HomePageId (PK) | UserId (FK) | Value of type string +---------------- ``` Advantage of this approach is that you can very quickly see all the values for that property. Disadvantage is that you will have too many tables (one per custom property) and that you will join tables often during query operations. 3) CustomProperty table In this solution you have one table holding all custom properties. ``` +---------------- | CustomPropertyEnum +---------------- | PropertyId (PK) | Name of type string +---------------- +---------------- | CustomProperty +---------------- | PropId (PK) | PropertyId (FK) | UserId (FK) | Value of type string +---------------- ``` In this solution you store all custom properties in one table. You also have a special enum table that allows you to more efficiently query data. The disadvantage is that you will join tables often during query operations. Choose for yourself. I would decide between 2 and 3 depending on your workload (most probably 3 because it is easier).
155,681
<p>I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to &amp;nbsp and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks!</p>
[ { "answer_id": 155698, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 5, "selected": true, "text": "<p>You can cause the text inside the <code>pre</code> to wrap by using the following CSS</p>\n\n<pre><code>pre {\n white-space: pre-wrap; /* css-3 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n</code></pre>\n\n<p>Taken from <a href=\"http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html\" rel=\"noreferrer\">this site</a></p>\n\n<p>It's currently defined in CSS3 (which is not yet a finished standard) but most browsers seem to support it as per the comments.</p>\n" }, { "answer_id": 155707, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>You've got two competing requirements. You either want the content to fit within a certain area (ie: width: 300px), or you want to preserve the whitespace and newlines as the user entered them. You can't do both since one - by definition - interferes with the other.</p>\n\n<p>Since HTML isn't whitespace aware, your only options are changing multiple spaces to \"&amp;nbsp;\" and changing newlines to &lt;br />, using a &lt;pre&gt; tag, or specifying the css style \"white-space: pre\".</p>\n" }, { "answer_id": 155718, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>Regarding the problem with the div, you can always make it scroll, or adjust the font down (this is even possible dynamically based on length of longest line in your server-side code).</p>\n" }, { "answer_id": 187150, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 2, "selected": false, "text": "<p>You could just use PHP's <a href=\"http://uk3.php.net/nl2br\" rel=\"nofollow noreferrer\">nl2br function</a>.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23976/" ]
I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to &nbsp and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks!
You can cause the text inside the `pre` to wrap by using the following CSS ``` pre { white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } ``` Taken from [this site](http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html) It's currently defined in CSS3 (which is not yet a finished standard) but most browsers seem to support it as per the comments.
155,685
<p>I need to replace the contents of a node in an XElement hierarchy when the element name and all the attribute names and values match an input element. (If there is no match, the new element can be added.)</p> <p>For example, if my data looks like this:</p> <pre><code>&lt;root&gt; &lt;thing1 a1="a" a2="b"&gt;one&lt;/thing1&gt; &lt;thing2 a1="a" a2="a"&gt;two&lt;/thing2&gt; &lt;thing2 a1="a" a3="b"&gt;three&lt;/thing2&gt; &lt;thing2 a1="a"&gt;four&lt;/thing2&gt; &lt;thing2 a1="a" a2="b"&gt;five&lt;/thing2&gt; &lt;root&gt; </code></pre> <p>I want to find the last element when I call a method with this input:</p> <pre><code>&lt;thing2 a1="a" a2="b"&gt;new value&lt;/thing2&gt; </code></pre> <p>The method should have no hard-coded element or attribute names - it simply matches the input to the data.</p>
[ { "answer_id": 155728, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can do an XPathSelectElement with the path (don't quote me, been to the bar; will clean up in the morn) /root/thing2[@a1='a' and @a2='b'] and then take .LastOrDefault() (XPathSelectElement is an extension method in system.Linq.Xml).</p>\n\n<p>That will get you the node you wish to change. I'm not sure how you want to change it, however. The result you get is the actual XElement, so changing it will change the tree element.</p>\n" }, { "answer_id": 155787, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "<p>This will match any given element with exact tag name and attribute name/value pairs:</p>\n\n<pre><code>public static void ReplaceOrAdd(this XElement source, XElement node)\n{\n var q = from x in source.Elements()\n where x.Name == node.Name\n &amp;&amp; x.Attributes().All(a =&gt;node.Attributes().Any(b =&gt;a.Name==b.Name &amp;&amp; a.Value==b.Value))\n select x;\n\n var n = q.LastOrDefault();\n\n if (n == null) source.Add(node);\n else n.ReplaceWith(node); \n}\n\nvar root = XElement.Parse(data);\nvar newElem =XElement.Parse(\"&lt;thing2 a1=\\\"a\\\" a2=\\\"b\\\"&gt;new value&lt;/thing2&gt;\");\n\nroot.ReplaceOrAdd(newElem);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14842/" ]
I need to replace the contents of a node in an XElement hierarchy when the element name and all the attribute names and values match an input element. (If there is no match, the new element can be added.) For example, if my data looks like this: ``` <root> <thing1 a1="a" a2="b">one</thing1> <thing2 a1="a" a2="a">two</thing2> <thing2 a1="a" a3="b">three</thing2> <thing2 a1="a">four</thing2> <thing2 a1="a" a2="b">five</thing2> <root> ``` I want to find the last element when I call a method with this input: ``` <thing2 a1="a" a2="b">new value</thing2> ``` The method should have no hard-coded element or attribute names - it simply matches the input to the data.
This will match any given element with exact tag name and attribute name/value pairs: ``` public static void ReplaceOrAdd(this XElement source, XElement node) { var q = from x in source.Elements() where x.Name == node.Name && x.Attributes().All(a =>node.Attributes().Any(b =>a.Name==b.Name && a.Value==b.Value)) select x; var n = q.LastOrDefault(); if (n == null) source.Add(node); else n.ReplaceWith(node); } var root = XElement.Parse(data); var newElem =XElement.Parse("<thing2 a1=\"a\" a2=\"b\">new value</thing2>"); root.ReplaceOrAdd(newElem); ```
155,712
<p>Here's my problem - I have some code like this:</p> <pre><code>&lt;mx:Canvas width="300" height="300"&gt; &lt;mx:Button x="800" /&gt; &lt;/mx:Canvas&gt; </code></pre> <p>So the problem is that the Button inside the canvas has an x property way in excess of the Canvas's width - since it's a child of the Canvas, the Canvas masks it and creates some scrollbars for me to scroll over to the button.</p> <p>What I'd like is to display the button - 800 pixels to the left of the Canvas without the scrollbars while still leaving the button as a child of the Canvas. How do I do that?</p>
[ { "answer_id": 155817, "author": "Paul Mignard", "author_id": 3435, "author_profile": "https://Stackoverflow.com/users/3435", "pm_score": 4, "selected": true, "text": "<p>I figured it out - apparently the Container has a property called clipContent - here's the description from Adobe:</p>\n\n<p><em>Whether to apply a clip mask if the positions and/or sizes of this container's children extend outside the borders of this container. If false, the children of this container remain visible when they are moved or sized outside the borders of this container. If true, the children of this container are clipped.</em></p>\n\n<p><em>If clipContent is false, then scrolling is disabled for this container and scrollbars will not appear. If clipContent is true, then scrollbars will usually appear when the container's children extend outside the border of the container. For additional control over the appearance of scrollbars, see horizontalScrollPolicy and verticalScrollPolicy.\nThe default value is true.</em></p>\n\n<p>So basically - to show the button outside of the bounds of the container I need to do the following:</p>\n\n<pre><code>&lt;mx:Canvas width=\"300\" height=\"300\" clipContent=\"false\" &gt;\n &lt;mx:Button x=\"800\" /&gt;\n&lt;/mx:Canvas&gt;\n</code></pre>\n\n<p>That was easier than I thought it was going to be. :)</p>\n\n<p><a href=\"http://livedocs.adobe.com/flex/3/langref/mx/core/Container.html#clipContent\" rel=\"noreferrer\">Here's the official doc...</a></p>\n" }, { "answer_id": 175610, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You should be able to use the <strong>includeInLayout</strong> property also, which would allow you to apply it to each child component independently.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
Here's my problem - I have some code like this: ``` <mx:Canvas width="300" height="300"> <mx:Button x="800" /> </mx:Canvas> ``` So the problem is that the Button inside the canvas has an x property way in excess of the Canvas's width - since it's a child of the Canvas, the Canvas masks it and creates some scrollbars for me to scroll over to the button. What I'd like is to display the button - 800 pixels to the left of the Canvas without the scrollbars while still leaving the button as a child of the Canvas. How do I do that?
I figured it out - apparently the Container has a property called clipContent - here's the description from Adobe: *Whether to apply a clip mask if the positions and/or sizes of this container's children extend outside the borders of this container. If false, the children of this container remain visible when they are moved or sized outside the borders of this container. If true, the children of this container are clipped.* *If clipContent is false, then scrolling is disabled for this container and scrollbars will not appear. If clipContent is true, then scrollbars will usually appear when the container's children extend outside the border of the container. For additional control over the appearance of scrollbars, see horizontalScrollPolicy and verticalScrollPolicy. The default value is true.* So basically - to show the button outside of the bounds of the container I need to do the following: ``` <mx:Canvas width="300" height="300" clipContent="false" > <mx:Button x="800" /> </mx:Canvas> ``` That was easier than I thought it was going to be. :) [Here's the official doc...](http://livedocs.adobe.com/flex/3/langref/mx/core/Container.html#clipContent)
155,739
<p>I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.</p> <p>Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.</p>
[ { "answer_id": 155760, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": false, "text": "<p>In the .aspx page, you need a Javascript function to tell whether or not the form info is \"dirty\"</p>\n\n<pre><code>&lt;script language=\"javascript\"&gt;\n var isDirty = false;\n\n function setDirty() {\n isDirty = true;\n }\n\n function checkSave() {\n var sSave;\n if (isDirty == true) {\n sSave = window.confirm(\"You have some changes that have not been saved. Click OK to save now or CANCEL to continue without saving.\");\n if (sSave == true) {\n document.getElementById('__EVENTTARGET').value = 'btnSubmit';\n document.getElementById('__EVENTARGUMENT').value = 'Click'; \n window.document.formName.submit();\n } else {\n return true;\n }\n }\n }\n&lt;/script&gt;\n&lt;body class=\"StandardBody\" onunload=\"checkSave()\"&gt;\n</code></pre>\n\n<p>and in the codebehind, add the triggers to the input fields as well as resets on the submission/cancel buttons....</p>\n\n<pre><code>btnSubmit.Attributes.Add(\"onclick\", \"isDirty = 0;\");\nbtnCancel.Attributes.Add(\"onclick\", \"isDirty = 0;\");\ntxtName.Attributes.Add(\"onchange\", \"setDirty();\");\ntxtAddress.Attributes.Add(\"onchange\", \"setDirty();\");\n//etc..\n</code></pre>\n" }, { "answer_id": 155776, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://web.archive.org/web/20210728061434/https://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo3.htm\" rel=\"nofollow noreferrer\">One method</a>, using arrays to hold the variables so changes can be tracked.</p>\n\n<p>Here's a very simple method to <a href=\"http://gadgetopia.com/post/2507\" rel=\"nofollow noreferrer\">detect changes</a>, but the rest isn't as elegant.</p>\n\n<p>Another method which is fairly simple and small, from <a href=\"http://farfetched.blogspot.com/2005/03/warn-of-unsaved-changes-javascript.html\" rel=\"nofollow noreferrer\">Farfetched Blog</a>:</p>\n\n<pre><code>&lt;body onLoad=\"lookForChanges()\" onBeforeUnload=\"return warnOfUnsavedChanges()\"&gt;\n&lt;form&gt;\n&lt;select name=a multiple&gt;\n &lt;option value=1&gt;1\n &lt;option value=2&gt;2\n &lt;option value=3&gt;3\n&lt;/select&gt;\n&lt;input name=b value=123&gt;\n&lt;input type=submit&gt;\n&lt;/form&gt;\n\n&lt;script&gt;\nvar changed = 0;\nfunction recordChange() {\n changed = 1;\n}\nfunction recordChangeIfChangeKey(myevent) {\n if (myevent.which &amp;&amp; !myevent.ctrlKey &amp;&amp; !myevent.ctrlKey)\n recordChange(myevent);\n}\nfunction ignoreChange() {\n changed = 0;\n}\nfunction lookForChanges() {\n var origfunc;\n for (i = 0; i &lt; document.forms.length; i++) {\n for (j = 0; j &lt; document.forms[i].elements.length; j++) {\n var formField=document.forms[i].elements[j];\n var formFieldType=formField.type.toLowerCase();\n if (formFieldType == 'checkbox' || formFieldType == 'radio') {\n addHandler(formField, 'click', recordChange);\n } else if (formFieldType == 'text' || formFieldType == 'textarea') {\n if (formField.attachEvent) {\n addHandler(formField, 'keypress', recordChange);\n } else {\n addHandler(formField, 'keypress', recordChangeIfChangeKey);\n }\n } else if (formFieldType == 'select-multiple' || formFieldType == 'select-one') {\n addHandler(formField, 'change', recordChange);\n }\n }\n addHandler(document.forms[i], 'submit', ignoreChange);\n }\n}\nfunction warnOfUnsavedChanges() {\n if (changed) {\n if (\"event\" in window) //ie\n event.returnValue = 'You have unsaved changes on this page, which will be discarded if you leave now. Click \"Cancel\" in order to save them first.';\n else //netscape\n return false;\n }\n}\nfunction addHandler(target, eventName, handler) {\n if (target.attachEvent) {\n target.attachEvent('on'+eventName, handler);\n } else {\n target.addEventListener(eventName, handler, false);\n }\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 155812, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "<p>One piece of the puzzle:</p>\n\n<pre><code>/**\n * Determines if a form is dirty by comparing the current value of each element\n * with its default value.\n *\n * @param {Form} form the form to be checked.\n * @return {Boolean} &lt;code&gt;true&lt;/code&gt; if the form is dirty, &lt;code&gt;false&lt;/code&gt;\n * otherwise.\n */\nfunction formIsDirty(form) {\n for (var i = 0; i &lt; form.elements.length; i++) {\n var element = form.elements[i];\n var type = element.type;\n if (type == \"checkbox\" || type == \"radio\") {\n if (element.checked != element.defaultChecked) {\n return true;\n }\n }\n else if (type == \"hidden\" || type == \"password\" ||\n type == \"text\" || type == \"textarea\") {\n if (element.value != element.defaultValue) {\n return true;\n }\n }\n else if (type == \"select-one\" || type == \"select-multiple\") {\n for (var j = 0; j &lt; element.options.length; j++) {\n if (element.options[j].selected !=\n element.options[j].defaultSelected) {\n return true;\n }\n }\n }\n }\n return false;\n}\n</code></pre>\n\n<p><a href=\"http://developer.mozilla.org/en/DOM/window.onbeforeunload\" rel=\"noreferrer\">And another</a>:</p>\n\n<pre><code>window.onbeforeunload = function(e) {\n e = e || window.event; \n if (formIsDirty(document.forms[\"someForm\"])) {\n // For IE and Firefox\n if (e) {\n e.returnValue = \"You have unsaved changes.\";\n }\n // For Safari\n return \"You have unsaved changes.\";\n }\n};\n</code></pre>\n\n<p>Wrap it all up, and what do you get?</p>\n\n<pre><code>var confirmExitIfModified = (function() {\n function formIsDirty(form) {\n // ...as above\n }\n\n return function(form, message) {\n window.onbeforeunload = function(e) {\n e = e || window.event;\n if (formIsDirty(document.forms[form])) {\n // For IE and Firefox\n if (e) {\n e.returnValue = message;\n }\n // For Safari\n return message;\n }\n };\n };\n})();\n\nconfirmExitIfModified(\"someForm\", \"You have unsaved changes.\");\n</code></pre>\n\n<p>You'll probably also want to change the registration of the <code>beforeunload</code> event handler to use <code>LIBRARY_OF_CHOICE</code>'s event registration.</p>\n" }, { "answer_id": 155841, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 8, "selected": true, "text": "<p>Using jQuery:</p>\n\n<pre><code>var _isDirty = false;\n$(\"input[type='text']\").change(function(){\n _isDirty = true;\n});\n// replicate for other input types and selects\n</code></pre>\n\n<p>Combine with <code>onunload</code>/<code>onbeforeunload</code> methods as required.</p>\n\n<p>From the comments, the following references all input fields, without duplicating code:</p>\n\n<pre><code>$(':input').change(function () {\n</code></pre>\n\n<p>Using <code>$(\":input\")</code> refers to all input, textarea, select, and button elements.</p>\n" }, { "answer_id": 160273, "author": "tbreffni", "author_id": 637, "author_profile": "https://Stackoverflow.com/users/637", "pm_score": 3, "selected": false, "text": "<p>Thanks for the replies everyone. I ended up implementing a solution using JQuery and the <a href=\"http://code.google.com/p/protect-data/\" rel=\"noreferrer\">Protect-Data</a> plug-in. This allows me to automatically apply monitoring to all controls on a page.</p>\n\n<p>There are a few caveats however, especially when dealing with an ASP .Net application:</p>\n\n<ul>\n<li><p>When a user chooses the cancel option, the doPostBack function will throw a JavaScript error. I had to manually put a try-catch around the .submit call within doPostBack to suppress it.</p></li>\n<li><p>On some pages, a user could perform an action that performs a postback to the same page, but isn't a save. This results in any JavaScript logic resetting, so it thinks nothing has changed after the postback when something may have. I had to implement a hidden textbox that gets posted back with the page, and is used to hold a simple boolean value indicating whether the data is dirty. This gets persisted across postbacks.</p></li>\n<li><p>You may want some postbacks on the page to not trigger the dialog, such as a Save button. In this case, you can use JQuery to add an OnClick function which sets window.onbeforeunload to null.</p></li>\n</ul>\n\n<p>Hopefully this is helpful for anyone else who has to implement something similar.</p>\n" }, { "answer_id": 160493, "author": "mde", "author_id": 22440, "author_profile": "https://Stackoverflow.com/users/22440", "pm_score": 1, "selected": false, "text": "<p>This is exactly what the Fleegix.js plugin <code>fleegix.form.diff</code> (<a href=\"http://js.fleegix.org/plugins/form/diff\" rel=\"nofollow noreferrer\"><a href=\"http://js.fleegix.org/plugins/form/diff\" rel=\"nofollow noreferrer\">http://js.fleegix.org/plugins/form/diff</a></a>) was created for. Serialize the initial state of the form on load using <code>fleegix.form.toObject</code> (<a href=\"http://js.fleegix.org/ref#fleegix.form.toObject\" rel=\"nofollow noreferrer\"><a href=\"http://js.fleegix.org/ref#fleegix.form.toObject\" rel=\"nofollow noreferrer\">http://js.fleegix.org/ref#fleegix.form.toObject</a></a>) and save it in a variable, then compare with the current state using <code>fleegix.form.diff</code> on unload. Easy as pie.</p>\n" }, { "answer_id": 906026, "author": "reto", "author_id": 102200, "author_profile": "https://Stackoverflow.com/users/102200", "pm_score": 3, "selected": false, "text": "<p>The following solution works for prototype (tested in FF, IE 6 and Safari). It uses a generic form observer (which fires form:changed when any fields of the form have been modified), which you can use for other stuff as well.</p>\n\n<pre><code>/* use this function to announce changes from your own scripts/event handlers.\n * Example: onClick=\"makeDirty($(this).up('form'));\"\n */\nfunction makeDirty(form) {\n form.fire(\"form:changed\");\n}\n\nfunction handleChange(form, event) {\n makeDirty(form);\n}\n\n/* generic form observer, ensure that form:changed is being fired whenever\n * a field is being changed in that particular for\n */\nfunction setupFormChangeObserver(form) {\n var handler = handleChange.curry(form);\n\n form.getElements().each(function (element) {\n element.observe(\"change\", handler);\n });\n}\n\n/* installs a form protector to a form marked with class 'protectForm' */\nfunction setupProtectForm() {\n var form = $$(\"form.protectForm\").first();\n\n /* abort if no form */\n if (!form) return;\n\n setupFormChangeObserver(form);\n\n var dirty = false;\n form.observe(\"form:changed\", function(event) {\n dirty = true;\n });\n\n /* submitting the form makes the form clean again */\n form.observe(\"submit\", function(event) {\n dirty = false;\n });\n\n /* unfortunatly a propper event handler doesn't appear to work with IE and Safari */\n window.onbeforeunload = function(event) {\n if (dirty) {\n return \"There are unsaved changes, they will be lost if you leave now.\";\n }\n };\n}\n\ndocument.observe(\"dom:loaded\", setupProtectForm);\n</code></pre>\n" }, { "answer_id": 1744350, "author": "Colin Houghton", "author_id": 212333, "author_profile": "https://Stackoverflow.com/users/212333", "pm_score": 3, "selected": false, "text": "<p>The following uses the browser's onbeforeunload function and jquery to capture any onchange event. IT also looks for any submit or reset buttons to reset the flag indicating changes have occurred. </p>\n\n<pre><code>dataChanged = 0; // global variable flags unsaved changes \n\nfunction bindForChange(){ \n $('input,checkbox,textarea,radio,select').bind('change',function(event) { dataChanged = 1})\n $(':reset,:submit').bind('click',function(event) { dataChanged = 0 })\n}\n\n\nfunction askConfirm(){ \n if (dataChanged){ \n return \"You have some unsaved changes. Press OK to continue without saving.\" \n }\n}\n\nwindow.onbeforeunload = askConfirm;\nwindow.onload = bindForChange;\n</code></pre>\n" }, { "answer_id": 9272081, "author": "PeterX", "author_id": 845584, "author_profile": "https://Stackoverflow.com/users/845584", "pm_score": 2, "selected": false, "text": "<p>I expanded on Slace's suggestion above, to include most editable elements and also excluding certain elements (with a CSS style called \"srSearch\" here) from causing the dirty flag to be set.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n var _isDirty = false;\n $(document).ready(function () { \n\n // Set exclude CSS class on radio-button list elements\n $('table.srSearch input:radio').addClass(\"srSearch\");\n\n $(\"input[type='text'],input[type='radio'],select,textarea\").not(\".srSearch\").change(function () {\n _isDirty = true;\n });\n });\n\n $(window).bind('beforeunload', function () {\n if (_isDirty) {\n return 'You have unsaved changes.';\n }\n }); \n</code></pre>\n\n<p></p>\n" }, { "answer_id": 10389501, "author": "NightOwl888", "author_id": 181087, "author_profile": "https://Stackoverflow.com/users/181087", "pm_score": 2, "selected": false, "text": "<p>I recently contributed to an open source jQuery plugin called <a href=\"https://github.com/snikch/jquery.dirtyforms\" rel=\"nofollow\">dirtyForms</a>. </p>\n\n<p>The plugin is designed to work with dynamically added HTML, supports multiple forms, can support virtually any dialog framework, falls back to the browser beforeunload dialog, has a pluggable helper framework to support getting dirty status from custom editors (a tinyMCE plugin is included), works within iFrames, and the dirty status can be set or reset at will.</p>\n\n<p><a href=\"https://github.com/snikch/jquery.dirtyforms\" rel=\"nofollow\">https://github.com/snikch/jquery.dirtyforms</a></p>\n" }, { "answer_id": 19525717, "author": "skibulk", "author_id": 1017480, "author_profile": "https://Stackoverflow.com/users/1017480", "pm_score": 3, "selected": false, "text": "<p>Here's a javascript / jquery solution that is simple. It accounts for \"undos\" by the user, it is encapsulated within a function for ease of application, and it doesn't misfire on submit. Just call the function and pass the ID of your form.</p>\n\n<p>This function serializes the form once when the page is loaded, and again before the user leaves the page. If the two form states are different, the prompt is shown.</p>\n\n<p>Try it out: <a href=\"http://jsfiddle.net/skibulk/Ydt7Y/\" rel=\"noreferrer\">http://jsfiddle.net/skibulk/Ydt7Y/</a></p>\n\n<pre><code>function formUnloadPrompt(formSelector) {\n var formA = $(formSelector).serialize(), formB, formSubmit = false;\n\n // Detect Form Submit\n $(formSelector).submit( function(){\n formSubmit = true;\n });\n\n // Handle Form Unload \n window.onbeforeunload = function(){\n if (formSubmit) return;\n formB = $(formSelector).serialize();\n if (formA != formB) return \"Your changes have not been saved.\";\n };\n}\n\n$(function(){\n formUnloadPrompt('form');\n});\n</code></pre>\n" }, { "answer_id": 24624798, "author": "Ankit", "author_id": 2353426, "author_profile": "https://Stackoverflow.com/users/2353426", "pm_score": 2, "selected": false, "text": "<pre><code> var unsaved = false;\n $(\":input\").change(function () { \n unsaved = true;\n });\n\n function unloadPage() { \n if (unsaved) { \n alert(\"You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?\");\n }\n } \n</code></pre>\n\n<p>window.onbeforeunload = unloadPage;</p>\n" }, { "answer_id": 27482349, "author": "v.babak", "author_id": 2400627, "author_profile": "https://Stackoverflow.com/users/2400627", "pm_score": 2, "selected": false, "text": "<p>Detect form changes with using jQuery is very simple:</p>\n\n<pre><code>var formInitVal = $('#formId').serialize(); // detect form init value after form is displayed\n\n// check for form changes\nif ($('#formId').serialize() != formInitVal) {\n // show confirmation alert\n}\n</code></pre>\n" }, { "answer_id": 30374461, "author": "MhdSyrwan", "author_id": 923894, "author_profile": "https://Stackoverflow.com/users/923894", "pm_score": 3, "selected": false, "text": "<p>General Solution Supporting multiple forms in a given page (<strong>Just copy and paste in your project</strong>)</p>\n\n<pre><code>$(document).ready(function() {\n $('form :input').change(function() {\n $(this).closest('form').addClass('form-dirty');\n });\n\n $(window).bind('beforeunload', function() {\n if($('form:not(.ignore-changes).form-dirty').length &gt; 0) {\n return 'You have unsaved changes, are you sure you want to discard them?';\n }\n });\n\n $('form').bind('submit',function() {\n $(this).closest('form').removeClass('form-dirty');\n return true;\n });\n});\n</code></pre>\n\n<p>Note: This solution is combined from others' solutions to create a general integrated solution.</p>\n\n<p>Features:</p>\n\n<ul>\n<li>Just copy and paste into your app.</li>\n<li>Supports Multiple Forms.</li>\n<li>You can style or make actions dirty forms, since they've the class \"form-dirty\".</li>\n<li>You can exclude some forms by adding the class 'ignore-changes'.</li>\n</ul>\n" }, { "answer_id": 31238701, "author": "Krupall", "author_id": 2003093, "author_profile": "https://Stackoverflow.com/users/2003093", "pm_score": 0, "selected": false, "text": "<p>In IE document.ready will not work properly it will update the values of input.</p>\n\n<p>so we need to bind load event inside the document.ready function that will handle for IE browser also.</p>\n\n<p>below is the code you should put inside the document.ready function.</p>\n\n<pre><code> $(document).ready(function () {\n $(window).bind(\"load\", function () { \n $(\"input, select\").change(function () {});\n });\n});\n</code></pre>\n" }, { "answer_id": 64871468, "author": "darryn.ten", "author_id": 618172, "author_profile": "https://Stackoverflow.com/users/618172", "pm_score": 1, "selected": false, "text": "<p>A lot of outdated answers so here's something a little more modern.</p>\n<p>ES6</p>\n<pre><code>let dirty = false\ndocument.querySelectorAll('form').forEach(e =&gt; e.onchange = () =&gt; dirty = true)\n</code></pre>\n" }, { "answer_id": 73828635, "author": "dfcii", "author_id": 15461890, "author_profile": "https://Stackoverflow.com/users/15461890", "pm_score": 0, "selected": false, "text": "<p>I have found that this one works in Chrome with an exception... The messages being returned do not match those in the script:</p>\n<pre class=\"lang-js prettyprint-override\"><code>dataChanged = 0; // global variable flags unsaved changes\n\nfunction bindForChange() {\n $(&quot;input,checkbox,textarea,radio,select&quot;).bind(&quot;change&quot;, function (_event) {\n dataChanged = 1;\n });\n $(&quot;:reset,:submit&quot;).bind(&quot;click&quot;, function (_event) {\n dataChanged = 0;\n });\n}\n\nfunction askConfirm() {\n if (dataChanged) {\n var message =\n &quot;You have some unsaved changes. Press OK to continue without saving.&quot;;\n return message;\n }\n}\n\nwindow.onbeforeunload = askConfirm;\n\nwindow.onload = bindForChange;\n</code></pre>\n<p>The messages returned seem to be triggered by the specific type of action I'm performing. A RELOAD displays a question &quot;Reload Site?\nAnd a windows close returns a &quot;Leave Site?&quot; message.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637/" ]
I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls. Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.
Using jQuery: ``` var _isDirty = false; $("input[type='text']").change(function(){ _isDirty = true; }); // replicate for other input types and selects ``` Combine with `onunload`/`onbeforeunload` methods as required. From the comments, the following references all input fields, without duplicating code: ``` $(':input').change(function () { ``` Using `$(":input")` refers to all input, textarea, select, and button elements.
155,740
<p>I am working on an application that will sport a web-based point of sale interface.</p> <p>The point of sale PC (I am not sure as of now whether it will run on Linux or Windows) must have a fiscal printer attached to it, but like any web app, it is the server which processes all stuff. Both server and PoS machines are on the same LAN.</p> <p>I must send the sale data in real time, and via the fiscal printer which uses the serial port, so printing a PDF or even a web page is not an option.</p> <p>I've been told I could have a little app listening on web services on the client, which in turn talks to the printer instead of the server or the browser, but don't have a clue how to do it. Also, I'll most likely need to listen to any printer feedback (coupon number, for instance, which is generated by the printer) and hand it back to the server.</p> <p>Any ideas?</p>
[ { "answer_id": 155782, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "<p>I did something similar to this a couple of yrs. ago. But in my case the server and the PC where in the same lan. Is your PoS within the lan? If so, I'll explain it to you.</p>\n\n<p>In the mean time, if you have the \"little app\" covered you can take a look at the following:</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html</a></p>\n\n<p>The print service have a method to discover the printers registered within machine it is running on. So after you receive the message from the server on your app you just have to do something similar to the code shown in the link above:</p>\n\n<p>Taked from, <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html</a></p>\n\n<pre><code>DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;\nPrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();\naset.add(MediaSizeName.ISO_A4);\nPrintService[] pservices =\n PrintServiceLookup.lookupPrintServices(flavor, aset);\nif (pservices.length &gt; 0) {\n DocPrintJob pj = pservices[0].createPrintJob();\n // InputStreamDoc is an implementation of the Doc interface //\n Doc doc = new InputStreamDoc(\"test.ps\", flavor);\n try {\n pj.print(doc, aset);\n } catch (PrintException e) { \n }\n}\n</code></pre>\n" }, { "answer_id": 155849, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>That's why you have applets. But applets run in a security sandbox. However, if the right kind of privileges are given to the applet running in a webapp, it can open socket, write to files, write to serial port, etc.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22116/" ]
I am working on an application that will sport a web-based point of sale interface. The point of sale PC (I am not sure as of now whether it will run on Linux or Windows) must have a fiscal printer attached to it, but like any web app, it is the server which processes all stuff. Both server and PoS machines are on the same LAN. I must send the sale data in real time, and via the fiscal printer which uses the serial port, so printing a PDF or even a web page is not an option. I've been told I could have a little app listening on web services on the client, which in turn talks to the printer instead of the server or the browser, but don't have a clue how to do it. Also, I'll most likely need to listen to any printer feedback (coupon number, for instance, which is generated by the printer) and hand it back to the server. Any ideas?
I did something similar to this a couple of yrs. ago. But in my case the server and the PC where in the same lan. Is your PoS within the lan? If so, I'll explain it to you. In the mean time, if you have the "little app" covered you can take a look at the following: <http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html> The print service have a method to discover the printers registered within machine it is running on. So after you receive the message from the server on your app you just have to do something similar to the code shown in the link above: Taked from, <http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html> ``` DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet(); aset.add(MediaSizeName.ISO_A4); PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset); if (pservices.length > 0) { DocPrintJob pj = pservices[0].createPrintJob(); // InputStreamDoc is an implementation of the Doc interface // Doc doc = new InputStreamDoc("test.ps", flavor); try { pj.print(doc, aset); } catch (PrintException e) { } } ```
155,792
<p>I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.</p> <p>The basic idea is that this method will add certain things to a collection that will be used for validation.</p> <pre><code>public interface ITestInterface { //Specify stuff here. } private static void DoSomething&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; expression, params IMyInterface[] rule) { // Stuff is done here. } </code></pre> <p>The method is called as follows:</p> <pre><code>class TestClass { public int MyProperty { get; set; } } class OtherTestClass : ITestInterface { // Blah Blah Blah. } static void Main(string[] args) { DoSomething&lt;TestClass&gt;(t =&gt; t.MyProperty, new OtherTestClass()); } </code></pre> <p>I'm doing it this way because I'd like for the property names that are passed in to be strong typed.</p> <p>A couple of things I'm struggling with..</p> <ol> <li>Within DoSomething, I'd like to get a <code>PropertyInfo</code> type (from the body passed in) of T and add it to a collection along with rule[]. Currently, I'm thinking about using expression.Body and removing [propertyname] from &quot;Convert.([propertyname])&quot; and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way?</li> <li>Is this a specific pattern I'm using?</li> <li>Lastly, any suggestions or clarifications as to my misunderstanding of what I'm doing are appreciated and / or resources or good info on C# expression trees are appreciated as well.</li> </ol> <p>Thanks!</p> <p>Ian</p> <h1>Edit:</h1> <p>An example of what <code>expression.Body.ToString()</code> returns within the DoSomething method is a string that contains &quot;Convert(t.MyProperty)&quot; if called from the example above.</p> <p>I do need it to be strongly typed, so it will not compile if I change a property name.</p> <p>Thanks for the suggestions!</p>
[ { "answer_id": 155828, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "<p>Collecting PropertyInfo objects from Expression.Body seems similar to <a href=\"https://stackoverflow.com/questions/123088/possible-pitfalls-of-using-this-extension-method-based-shorthand#144982\">my solution</a> to another question. </p>\n" }, { "answer_id": 155845, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "<p>I appreciate what you are trying to do with the property here. I have run into this conundrum. It always feels weird to write:</p>\n\n<pre><code>DoSomething(\"MyProperty\", new OtherClass());\n</code></pre>\n\n<p>If the property ever changes name, or the text is mistyped in the call, then there will be a problem. What I have come to learn is that this is something you probably have to deal with via testing. Specifically, unit testing. I would write unit tests to enforce that the \"DoSomething\" calls work correctly.</p>\n\n<p>The other thing you might try is to decorate your properties with attributes, and then reflect against your class when it is constructed looking for properties with the attribute, and load rules.</p>\n\n<pre><code>[DoSomething(typeof(OtherClass), typeof(OtherClass2))]\npublic int MyProperty\n{\n get;\n set;\n}\n</code></pre>\n\n<p>In this case the constructor (perhaps in a base class?) would dynamically create an OtherClass object and a OtherClass2 object, and load them into a collection along with the name of the property. </p>\n" }, { "answer_id": 422132, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 2, "selected": false, "text": "<p>I rely heavily on expression trees to push a lot of what I want to do with my current application to compile-time, i.e. static type checking.</p>\n\n<p>I traverse expression trees to translate them into something else which \"makes sense\".</p>\n\n<p>One thing I've ended up doing a lot is that instead of URLs I rely on a MVC like approach where I declare lambda functions, and translates that... interpret, the compiler generated expression tree into an URL. When this URL is invoked, I do the opposite. This way, I have what I call compile-time checks for broken links and this works great with refactoring and overloads as well. I think it's cool to think about using expression trees in this way.</p>\n\n<p>You might wanna check out the visitor pattern, it's a pain to get started with because it doesn't make much sense in the beginning but it ties everything together and it's a very formal way to solve type checking in compiler construction. You could do the same, but instead of type checking emit what ever you need.</p>\n\n<p>Something which I'm currently pounding my head against is the ability to build a simple framework for translating (or actually I should say interpret) expression tress and emit JavaScript. The idea is that the compiler generated expression trees will translate into valid JavaScript which interfaces with some object model.</p>\n\n<p>What's exciting about this is the way the compiler is always able to tell me when I go wrong and sure the end result is just a bunch of strings but the important part is how these strings got created. They went through some verification and that means something.</p>\n\n<p>Once you get that going there is little you can't do with expression trees.</p>\n\n<p>While working with the System.Reflection.Emit stuff I found myself using expression trees to create a light-weight framework for dynamic compilation, which at compile time could basically say if my dynamically created assemblies would compile as well, and this worked seamlessly with reflection and static type checking. It took this further and further and ended up with something which in the end saved a lot of time and proved to be very agile and robust.</p>\n\n<p>So I love this kind of stuff, and this is what meta programming is all about, writing programs in your programs that do programs. I say keep it coming!</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10853/" ]
I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class. The basic idea is that this method will add certain things to a collection that will be used for validation. ``` public interface ITestInterface { //Specify stuff here. } private static void DoSomething<T>(Expression<Func<T, object>> expression, params IMyInterface[] rule) { // Stuff is done here. } ``` The method is called as follows: ``` class TestClass { public int MyProperty { get; set; } } class OtherTestClass : ITestInterface { // Blah Blah Blah. } static void Main(string[] args) { DoSomething<TestClass>(t => t.MyProperty, new OtherTestClass()); } ``` I'm doing it this way because I'd like for the property names that are passed in to be strong typed. A couple of things I'm struggling with.. 1. Within DoSomething, I'd like to get a `PropertyInfo` type (from the body passed in) of T and add it to a collection along with rule[]. Currently, I'm thinking about using expression.Body and removing [propertyname] from "Convert.([propertyname])" and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way? 2. Is this a specific pattern I'm using? 3. Lastly, any suggestions or clarifications as to my misunderstanding of what I'm doing are appreciated and / or resources or good info on C# expression trees are appreciated as well. Thanks! Ian Edit: ===== An example of what `expression.Body.ToString()` returns within the DoSomething method is a string that contains "Convert(t.MyProperty)" if called from the example above. I do need it to be strongly typed, so it will not compile if I change a property name. Thanks for the suggestions!
Collecting PropertyInfo objects from Expression.Body seems similar to [my solution](https://stackoverflow.com/questions/123088/possible-pitfalls-of-using-this-extension-method-based-shorthand#144982) to another question.
155,797
<p>ADO.NET has the notorious DataRow class which you cannot instantiate using new. This is a problem now that I find a need to mock it using Rhino Mocks. </p> <p>Does anyone have any ideas how I could get around this problem?</p>
[ { "answer_id": 155804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Any time I can't mock something (I prefer MoQ over Rhino, but that's beside the point) I have to code around it.</p>\n\n<p>The way I see it you only have two choices. Pay for a superior framework such as TypeMock that can mock ANY class, or code a wrapper around classes that weren't written to be mocked. </p>\n\n<p>Its a sad state of affairs in the framework. TDD wasn't a big concern back in the 1.1 days.</p>\n" }, { "answer_id": 155813, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 5, "selected": true, "text": "<p>I'm curious as to why you need to mock the DataRow. Sometimes you can get caught up doing mocking and forget that it can be just as prudent to use the real thing. If you are passing around data rows then you can simply instantiate one with a helper method and use that as a return value on your mock.</p>\n\n<pre><code>SetupResult.For(someMockClass.GetDataRow(input)).Return(GetReturnRow());\n\npublic DataRow GetReturnRow()\n{\n DataTable table = new DataTable(\"FakeTable\");\n DataRow row = table.NewRow();\n row.value1 = \"someValue\";\n row.value2 = 234;\n\n return row;\n}\n</code></pre>\n\n<p>If this is not the situation you are in then I am going to need some example code to be able to figure out what you are trying to do.</p>\n" }, { "answer_id": 920460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I also use <a href=\"http://www.typemock.com\" rel=\"nofollow noreferrer\">Typemock</a> Isolator for this, it can mock things that other mocking frameworks are unable to.</p>\n" }, { "answer_id": 69921036, "author": "Alison Rodrigues", "author_id": 14218167, "author_profile": "https://Stackoverflow.com/users/14218167", "pm_score": 0, "selected": false, "text": "<p>this works for me</p>\n<pre><code> private DataRow GetReturnRow()\n {\n DataTable table = new DataTable(&quot;FakeTable&quot;);\n table.Columns.Add(&quot;column_name&quot;);\n\n DataRow row = table.NewRow();\n row[&quot;column_name&quot;] = your_value;\n\n return row;\n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
ADO.NET has the notorious DataRow class which you cannot instantiate using new. This is a problem now that I find a need to mock it using Rhino Mocks. Does anyone have any ideas how I could get around this problem?
I'm curious as to why you need to mock the DataRow. Sometimes you can get caught up doing mocking and forget that it can be just as prudent to use the real thing. If you are passing around data rows then you can simply instantiate one with a helper method and use that as a return value on your mock. ``` SetupResult.For(someMockClass.GetDataRow(input)).Return(GetReturnRow()); public DataRow GetReturnRow() { DataTable table = new DataTable("FakeTable"); DataRow row = table.NewRow(); row.value1 = "someValue"; row.value2 = 234; return row; } ``` If this is not the situation you are in then I am going to need some example code to be able to figure out what you are trying to do.
155,848
<p>I need to create an access (mdb) database without using the ADOX interop assembly. </p> <p>How can this be done?</p>
[ { "answer_id": 155851, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 5, "selected": true, "text": "<p>Before I throw away this code, it might as well live on stackoverflow </p>\n\n<p>Something along these lines seems to do the trick: </p>\n\n<pre><code>if (!File.Exists(DB_FILENAME))\n{\n var cnnStr = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + DB_FILENAME;\n\n // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. \n var catType = Type.GetTypeFromProgID(\"ADOX.Catalog\");\n object o = Activator.CreateInstance(catType);\n catType.InvokeMember(\"Create\", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});\n\n OleDbConnection cnn = new OleDbConnection(cnnStr);\n cnn.Open();\n var cmd = cnn.CreateCommand();\n cmd.CommandText = \"CREATE TABLE VideoPosition (filename TEXT , pos LONG)\";\n cmd.ExecuteNonQuery();\n\n}\n</code></pre>\n\n<p>This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component. </p>\n" }, { "answer_id": 155880, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 0, "selected": false, "text": "<p>You don't need Jet(major headache) installed, if you use this connection string in .net 3.5 </p>\n\n<pre><code>Provider=Microsoft.ACE.OLEDB.12.0;Data\nSource=C:\\myFolder\\myAccess2007file.accdb;Persist\nSecurity Info=False;\n</code></pre>\n\n<p>This should work on access 2007 and below</p>\n" }, { "answer_id": 155955, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 0, "selected": false, "text": "<p>Interesting question -- I've never thought to create one on the fly like this. I've always included my baseline database as a resource in the project and made a copy when I needed a new one.</p>\n" }, { "answer_id": 156156, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 1, "selected": false, "text": "<p>I've done the same as Autsin, create an Access db then included it into my project as a managed resource. Once there, it is included in the compiled code and you can copy it to hard disk as many times as you want. Empty databases are relatively small too, so there isn't much overhead.</p>\n\n<p>The added bonus is the ability to set up the database if you know how it will be used or what tables will be added every time, you can reduce the amount of coding and slow database queries.</p>\n" }, { "answer_id": 17501983, "author": "Ian", "author_id": 2556032, "author_profile": "https://Stackoverflow.com/users/2556032", "pm_score": 0, "selected": false, "text": "<p>ACE <strong>is not</strong> in any framework (yet. ie not in 1, 2, 3.5, 4, 4.5)</p>\n\n<p>It's also not part of Windows Update.</p>\n\n<p>JET4 <strong>is</strong> in Framework2 and above.</p>\n\n<p>If you're working with Access/MDB files etc then do not assume ACE is present.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
I need to create an access (mdb) database without using the ADOX interop assembly. How can this be done?
Before I throw away this code, it might as well live on stackoverflow Something along these lines seems to do the trick: ``` if (!File.Exists(DB_FILENAME)) { var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME; // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. var catType = Type.GetTypeFromProgID("ADOX.Catalog"); object o = Activator.CreateInstance(catType); catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr}); OleDbConnection cnn = new OleDbConnection(cnnStr); cnn.Open(); var cmd = cnn.CreateCommand(); cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)"; cmd.ExecuteNonQuery(); } ``` This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component.
155,852
<p>I have created a non-visual component in C# which is designed as a placeholder for meta-data on a form.<br> The component has a property which is a collection of custom objects, this object is marked as Serializable and implements the GetObjectData for serilizing and public constuctor for deserilizing.<br></p> <p>In the resx file for the form it will generate binary data for storing the collection, however any time I make a change to the serialized class I get designer errors and need to delete the data manually out of the resx file and then recreate this data.</p> <p>I have tried changing the constuctor to have a try / catch block around each property in the class</p> <pre><code>try { _Name = info.GetString("Name"); } catch (SerializationException) { this._Name = string.Empty; } </code></pre> <p>but it still crashes. The last error I got was that I had to implement IConvertible.<br></p> <p>I would prefer to use xml serialization because I can at least see it, is this possible for use by the designer?<br></p> <p>Is there a way to make the serialization more stable and less resistant to changes?</p> <p>Edit:<br> More information...better description maybe<br> I have a class which inherits from Component, it has one property which is a collection of Rules. The RulesCollection seems to have to be marked as Serializable, otherwise it does not retain its members.<br> </p> <p>The Rules class is also a Component with the attribute DesignTimeVisible(false) to stop it showing in the component tray, this clas is not marked Serializable.<br></p> <p>Having the collection marked as Serializable generates binary data in the resx file (not ideal) and the IDE reports that the Rules class is not Serializable.<br></p> <p>I think this issue is getting beyond a simple question. So I will probably close it shortly.<br> If anyone has any links to something similar that would help a lot.</p>
[ { "answer_id": 155889, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 2, "selected": false, "text": "<p>You might want to try the alternate approach of getting everything to serialize as generated code. To do that is very easy. Just implement your non-visual class from <strong>Component</strong>. Then expose your collection as you already are but ensure each object placed into the collection is itself derived from <strong>Component</strong>. By doing that everything is code generated.</p>\n" }, { "answer_id": 160438, "author": "Jiminy", "author_id": 23355, "author_profile": "https://Stackoverflow.com/users/23355", "pm_score": 2, "selected": false, "text": "<p>Could you put more code up of the class that is having the serialization issue, maybe the constructor and the property to give reference to the variables you're using.</p>\n\n<p>Just a note:\nI've had a lot of issues with the visual designer and code generation, if I've got a property on a control then generally I put</p>\n\n<p>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] </p>\n\n<p>on the property and handle the initialization myself.</p>\n" }, { "answer_id": 199307, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 3, "selected": true, "text": "<p>I have since discovered where I was going wrong. </p>\n\n<p>The component I was implementing a custom collection (inherited from CollectionBase), I changed this to a List and added the DesignerSerializationVisibility(DesignerSerializationVisibility.Content) attribute to the List property, this list is also read-only. This would then produce code to generate all the components properties and all the entries in the List.</p>\n\n<p>The class stored in the list did not need any particuar attributes or need to be serializble.</p>\n\n<pre><code>private List&lt;Rule&gt; _Rules;\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic List&lt;Rule&gt; Rules\n{\n get { return _Rules; }\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
I have created a non-visual component in C# which is designed as a placeholder for meta-data on a form. The component has a property which is a collection of custom objects, this object is marked as Serializable and implements the GetObjectData for serilizing and public constuctor for deserilizing. In the resx file for the form it will generate binary data for storing the collection, however any time I make a change to the serialized class I get designer errors and need to delete the data manually out of the resx file and then recreate this data. I have tried changing the constuctor to have a try / catch block around each property in the class ``` try { _Name = info.GetString("Name"); } catch (SerializationException) { this._Name = string.Empty; } ``` but it still crashes. The last error I got was that I had to implement IConvertible. I would prefer to use xml serialization because I can at least see it, is this possible for use by the designer? Is there a way to make the serialization more stable and less resistant to changes? Edit: More information...better description maybe I have a class which inherits from Component, it has one property which is a collection of Rules. The RulesCollection seems to have to be marked as Serializable, otherwise it does not retain its members. The Rules class is also a Component with the attribute DesignTimeVisible(false) to stop it showing in the component tray, this clas is not marked Serializable. Having the collection marked as Serializable generates binary data in the resx file (not ideal) and the IDE reports that the Rules class is not Serializable. I think this issue is getting beyond a simple question. So I will probably close it shortly. If anyone has any links to something similar that would help a lot.
I have since discovered where I was going wrong. The component I was implementing a custom collection (inherited from CollectionBase), I changed this to a List and added the DesignerSerializationVisibility(DesignerSerializationVisibility.Content) attribute to the List property, this list is also read-only. This would then produce code to generate all the components properties and all the entries in the List. The class stored in the list did not need any particuar attributes or need to be serializble. ``` private List<Rule> _Rules; [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List<Rule> Rules { get { return _Rules; } } ```
155,864
<p>I have a controller with an action method as follows:</p> <pre><code>public class InventoryController : Controller { public ActionResult ViewStockNext(int firstItem) { // Do some stuff } } </code></pre> <p>And when I run it I get an error stating:</p> <blockquote> <p>The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type.</p> </blockquote> <p>I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method.</p> <p>I'm using this url syntax to call the action:</p> <pre><code>http://localhost:2316/Inventory/ViewStockNext/11 </code></pre> <p>Any ideas why I would get this error and what I need to do to fix it? </p> <p>I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs.</p>
[ { "answer_id": 155895, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 8, "selected": true, "text": "<p>Your routing needs to be set up along the lines of <code>{controller}/{action}/{firstItem}</code>. If you left the routing as the default <code>{controller}/{action}/{id}</code> in your <code>global.asax.cs</code> file, then you will need to pass in <code>id</code>.</p>\n\n<pre><code>routes.MapRoute(\n \"Inventory\",\n \"Inventory/{action}/{firstItem}\",\n new { controller = \"Inventory\", action = \"ListAll\", firstItem = \"\" }\n);\n</code></pre>\n\n<p>... or something close to that.</p>\n" }, { "answer_id": 155902, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 4, "selected": false, "text": "<p>To rephrase <a href=\"https://stackoverflow.com/questions/155864/aspnet-mvc-problem-passing-parameters-to-the-controller#155895\">Jarret Meyer's answer</a>, you need to change the parameter name to 'id' or add a route like this:</p>\n<pre><code>routes.MapRoute(\n &quot;ViewStockNext&quot;, // Route name\n &quot;Inventory/ViewStockNext/{firstItem}&quot;, // URL with parameters\n new { controller = &quot;Inventory&quot;, action = &quot;ViewStockNext&quot; } // Parameter defaults\n );\n</code></pre>\n<p>The reason is the default route only looks for actions with no parameter or a parameter called 'id'.</p>\n<p>Edit: Heh, nevermind Jarret added a route example after posting.</p>\n" }, { "answer_id": 355023, "author": "RAL", "author_id": 44844, "author_profile": "https://Stackoverflow.com/users/44844", "pm_score": 0, "selected": false, "text": "<p>Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...</p>\n\n<pre><code>public ActionResult ViewNextItem(string id)...\n</code></pre>\n" }, { "answer_id": 477963, "author": "Oskar Duveborn", "author_id": 49293, "author_profile": "https://Stackoverflow.com/users/49293", "pm_score": 3, "selected": false, "text": "<p><code>public ActionResult ViewNextItem(int? id)</code> makes the <code>id</code> integer a nullable type, no need for string&lt;->int conversions.</p>\n" }, { "answer_id": 1551423, "author": "Felix", "author_id": 184509, "author_profile": "https://Stackoverflow.com/users/184509", "pm_score": 1, "selected": false, "text": "<p>There is another way to accomplish that (described in more details in Stephen Walther's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0672329980\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Pager example</a></p>\n\n<p>Essentially, you create a link in the view:</p>\n\n<pre><code>Html.ActionLink(\"Next page\", \"Index\", routeData)\n</code></pre>\n\n<p>In routeData you can specify name/value pairs (e.g., routeData[\"page\"] = 5), and in the controller Index function corresponding parameters receive the value. That is,</p>\n\n<pre><code>public ViewResult Index(int? page)\n</code></pre>\n\n<p>will have <strong>page</strong> passed as 5. I have to admit, it's quite unusual that string (\"page\") automagically becomes a variable - but that's how MVC works in other languages as well...</p>\n" }, { "answer_id": 8363659, "author": "Bart Calixto", "author_id": 826568, "author_profile": "https://Stackoverflow.com/users/826568", "pm_score": 6, "selected": false, "text": "<p>you can change firstItem to id and it will work</p>\n\n<p>you can change the routing on global.asax (i do not recommed that)</p>\n\n<p>and, can't believe no one mentioned this, you can call :</p>\n\n<pre><code>http://localhost:2316/Inventory/ViewStockNext?firstItem=11\n</code></pre>\n\n<p>In a @Url.Action would be :</p>\n\n<pre><code>@Url.Action(\"ViewStockNext\", \"Inventory\", new {firstItem=11});\n</code></pre>\n\n<p>depending on the type of what you are doing, the last will be more suitable.\nAlso you should consider not doing ViewStockNext action and instead a ViewStock action with index. (my 2cents)</p>\n" }, { "answer_id": 8923030, "author": "Aristoteles", "author_id": 247949, "author_profile": "https://Stackoverflow.com/users/247949", "pm_score": 0, "selected": false, "text": "<p>The reason for the special treatment of \"id\" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:</p>\n\n<pre><code>routes.MapRoute (\"Default\", \"{controller}/{action}/{id}\", \n new { controller = \"Home\", action = \"Index\", id = \"\" });\n</code></pre>\n\n<p>Change it to:</p>\n\n<pre><code>routes.MapRoute (\"Default\", \"{controller}/{action}\", \n new { controller = \"Home\", action = \"Index\" });\n</code></pre>\n" }, { "answer_id": 12394449, "author": "Matthew Nichols", "author_id": 165031, "author_profile": "https://Stackoverflow.com/users/165031", "pm_score": 3, "selected": false, "text": "<p>Headspring created a nice library that allows you to add aliases to your parameters in attributes on the action. This looks like this:</p>\n\n<pre><code>[ParameterAlias(\"firstItem\", \"id\", Order = 3)]\npublic ActionResult ViewStockNext(int firstItem)\n{\n // Do some stuff\n}\n</code></pre>\n\n<p>With this you don't have to alter your routing just to handle a different parameter name. The library also supports applying it multiple times so you can map several parameter spellings (handy when refactoring without breaking your public interface). </p>\n\n<p>You can get it from <a href=\"http://nuget.org/packages/ActionParameterAlias\">Nuget</a> and read Jeffrey Palermo's article on it <a href=\"http://jeffreypalermo.com/blog/adding-an-alias-to-an-action-parameter-for-model-binding-in-asp-net-mvc/\">here</a></p>\n" }, { "answer_id": 32272225, "author": "Yar", "author_id": 2517730, "author_profile": "https://Stackoverflow.com/users/2517730", "pm_score": 4, "selected": false, "text": "<p>or do it with Route Attribute:</p>\n\n<pre><code>public class InventoryController : Controller\n{\n [Route(\"whatever/{firstItem}\")]\n public ActionResult ViewStockNext(int firstItem)\n {\n int yourNewVariable = firstItem;\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 43215223, "author": "Sasha Yakobchuk", "author_id": 4691615, "author_profile": "https://Stackoverflow.com/users/4691615", "pm_score": 3, "selected": false, "text": "<p>Using the ASP.NET Core Tag Helper feature:</p>\n\n<pre><code>&lt;a asp-controller=\"Home\" asp-action=\"SetLanguage\" asp-route-yourparam1=\"@item.Value\"&gt;@item.Text&lt;/a&gt;\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11908/" ]
I have a controller with an action method as follows: ``` public class InventoryController : Controller { public ActionResult ViewStockNext(int firstItem) { // Do some stuff } } ``` And when I run it I get an error stating: > > The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type. > > > I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method. I'm using this url syntax to call the action: ``` http://localhost:2316/Inventory/ViewStockNext/11 ``` Any ideas why I would get this error and what I need to do to fix it? I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs.
Your routing needs to be set up along the lines of `{controller}/{action}/{firstItem}`. If you left the routing as the default `{controller}/{action}/{id}` in your `global.asax.cs` file, then you will need to pass in `id`. ``` routes.MapRoute( "Inventory", "Inventory/{action}/{firstItem}", new { controller = "Inventory", action = "ListAll", firstItem = "" } ); ``` ... or something close to that.
155,869
<p>The Interwebs are no help on this one. We're encoding data in ColdFusion using <code>serializeJSON</code> and trying to decode it in PHP using <code>json_decode</code>. Most of the time, this is working fine, but in some cases, <code>json_decode</code> returns <code>NULL</code>. We've looked for the obvious culprits, but <code>serializeJSON</code> seems to be formatting things as expected. What else could be the problem?</p> <p>UPDATE: A couple of people (wisely) asked me to post the output that is causing the problem. I would, except we just discovered that the result set is all of our data (listing information for 2300+ rental properties for a total of 565,135 ASCII characters)! That could be a problem, though I didn't see anything in the PHP docs about a max size for the string. What would be the limiting factor there? RAM?</p> <p>UPDATE II: It looks like the problem was that a couple of our users had copied and pasted Microsoft Word text with "smart" quotes. Those pesky users...</p>
[ { "answer_id": 155914, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<p>can you replicate this issue reliably? and if so can you post sample data that returns null? i'm sure you know this, but for informational sake for others stumbling on this who may not, <a href=\"http://www.faqs.org/rfcs/rfc4627.html\" rel=\"nofollow noreferrer\">RFC 4627</a> describes JSON, and it's a common mistake to assume valid javascript is valid JSON. it's better to think of JSON as a subset of javascript.</p>\n\n<p>in response to the edit:</p>\n\n<p>i'd suggest checking to make sure your information is being populated in your PHP script (before it's being passed off to json_decode), and also validating that information (especially if you can reliably reproduce the error). you can try an <a href=\"http://www.jsonlint.com/\" rel=\"nofollow noreferrer\">online validator</a> for convenience. based on the very limited information it sounds like perhaps it's timing out and not grabbing all the data? is there a need for such a large dataset?</p>\n" }, { "answer_id": 155978, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "<p>You could try parsing it with another parser, and looking for an error -- I know Python's JSON parsers are very high quality. If you have Python installed it's easy enough to run the text through <a href=\"http://pypi.python.org/pypi/demjson\" rel=\"nofollow noreferrer\">demjson</a>'s syntax checker. If it's a very large dataset you can use my library <a href=\"http://pypi.python.org/pypi/jsonlib\" rel=\"nofollow noreferrer\">jsonlib</a> -- memory use will be higher than with demjson, but it will run faster because it's written in C.</p>\n" }, { "answer_id": 171521, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>You could try operating in UTF-8 and also letting PHP know that fact.</p>\n\n<p>I had an issue with PHP's <code>json_decode</code> not being able to decode a UTF-8 JSON string (with some \"weird\" characters other than the curly quotes that you have). My solution was to hint PHP that I was working in UTF-8 mode by inserting a Content-Type meta tag in the HTML page that was doing the submit to the PHP. That way the content type of the submitted data, which is the JSON string, would also be UTF-8:</p>\n\n<pre><code>&lt;meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/&gt;\n</code></pre>\n\n<p>After that, PHP's <code>json_decode</code> was able to properly decode the string.</p>\n" }, { "answer_id": 1184143, "author": "Stewart Robinson", "author_id": 47424, "author_profile": "https://Stackoverflow.com/users/47424", "pm_score": 1, "selected": false, "text": "<p>I had this exact problem and it turns out it was due to ColdFusion putting none printable characters into the JSON packets (these characters did actually exist in our data) but they can't go into JSON.</p>\n\n<p>Two questions on this site fixed this problem for me, although I went for the PHP solution rather than the ColdFusion solution as I felt it was the more elegant of the two.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1176904/php-how-to-remove-all-non-printable-characters-in-a-string\">PHP solution</a> </p>\n\n<p>Fix the string before you pass it to json_decode()</p>\n\n<pre><code>$string = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $string);\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1176940/how-to-get-around-serializejson-in-cf8-encoding-non-printable-characters\">ColdFusion solution</a></p>\n\n<p>Use the cleanXmlString() function in that SO question after using serializeJSON()</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
The Interwebs are no help on this one. We're encoding data in ColdFusion using `serializeJSON` and trying to decode it in PHP using `json_decode`. Most of the time, this is working fine, but in some cases, `json_decode` returns `NULL`. We've looked for the obvious culprits, but `serializeJSON` seems to be formatting things as expected. What else could be the problem? UPDATE: A couple of people (wisely) asked me to post the output that is causing the problem. I would, except we just discovered that the result set is all of our data (listing information for 2300+ rental properties for a total of 565,135 ASCII characters)! That could be a problem, though I didn't see anything in the PHP docs about a max size for the string. What would be the limiting factor there? RAM? UPDATE II: It looks like the problem was that a couple of our users had copied and pasted Microsoft Word text with "smart" quotes. Those pesky users...
You could try operating in UTF-8 and also letting PHP know that fact. I had an issue with PHP's `json_decode` not being able to decode a UTF-8 JSON string (with some "weird" characters other than the curly quotes that you have). My solution was to hint PHP that I was working in UTF-8 mode by inserting a Content-Type meta tag in the HTML page that was doing the submit to the PHP. That way the content type of the submitted data, which is the JSON string, would also be UTF-8: ``` <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> ``` After that, PHP's `json_decode` was able to properly decode the string.
155,891
<p>Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection. Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch. Any one have a handy trick for this conundrum?</p>
[ { "answer_id": 158948, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 2, "selected": false, "text": "<p>I don't believe that there is an easy way to rename a Verity collection. You can always use </p>\n\n<pre><code>&lt;cfcollection action=\"map\" ...&gt;\n</code></pre>\n\n<p>to assign an alias to an existing collection, provided you do not need to re-use the original name.</p>\n" }, { "answer_id": 214364, "author": "modius", "author_id": 10750, "author_profile": "https://Stackoverflow.com/users/10750", "pm_score": 1, "selected": false, "text": "<p>Looks like this is not possible. Deleting and re-creating the collection with the desired name appears to be the only approach available.</p>\n" }, { "answer_id": 571061, "author": "crb", "author_id": 51691, "author_profile": "https://Stackoverflow.com/users/51691", "pm_score": 2, "selected": true, "text": "<p>For the Verity part (without considering ColdFusion), it's easy enough to detach a collection, rename it, and reattach it again:</p>\n\n<pre><code>rcadmin&gt; indexdetach\nServer Alias:YourDocserver\nIndex Alias:CollectionName\nIndex Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c\nSave changes? [y|n]:y\n&lt;&lt;Return&gt;&gt; SUCCESS\n\nrcadmin&gt; collpurge\nCollection alias:CollectionName\nAdmin Alias:AdminServer\nSave changes? [y|n]:y\n&lt;&lt;Return&gt;&gt; SUCCESS\n\nrcadmin&gt; adminsignal\nAdmin Alias:AdminServer\nType of signal (Shutdown=2,WSRefresh=3,RestartAllServers=4):4\nSave changes? [y|n]:y\n&lt;&lt;Return&gt;&gt; SUCCESS\n</code></pre>\n\n<p>Now you can rename the collection directory, and re-attach. (If you are unsure of any of these values, check them with collget before you take it offline).</p>\n\n<pre><code>rcadmin&gt; collset\nAdmin Alias:AdminServer\nCollection Alias:NewCollectionName\nModify Type (Update=0, Insert=1):1\nPath:\nGateway[(o)dbc|(n)otes|(e)xchange|(d)ocumentum|(f)ilesys|(w)eb|o(t)her]:\nStyle Alias:\nDocument Access (Public=0,Secure=1,Anonymous=2):\nQuery Parser [(s)imple|(b)oolPlus|(f)reeText|(o)ldFreeText|O(l)dSimple|O(t)her]:\n\nDescription:\nMax. Search Time(msecs):\nSave changes? [y|n]:y\n\nrcadmin&gt; indexattach\nIndex Alias:NewCollectionName\nIndex Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c\nServer Alias:YourDocserver\nModify Type (Update=0, Insert=1):1\nIndex State (offline=0,hidden=1,online=2):2\nThreads (default=3):\nSave changes? [y|n]:y\n&lt;&lt;Return&gt;&gt; SUCCESS\n</code></pre>\n\n<p>It should now show up again in the 'hierarchyview'.</p>\n\n<p>You can also use the \"merge\" utility to copy content from one collection to another, with a new name.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750/" ]
Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection. Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch. Any one have a handy trick for this conundrum?
For the Verity part (without considering ColdFusion), it's easy enough to detach a collection, rename it, and reattach it again: ``` rcadmin> indexdetach Server Alias:YourDocserver Index Alias:CollectionName Index Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c Save changes? [y|n]:y <<Return>> SUCCESS rcadmin> collpurge Collection alias:CollectionName Admin Alias:AdminServer Save changes? [y|n]:y <<Return>> SUCCESS rcadmin> adminsignal Admin Alias:AdminServer Type of signal (Shutdown=2,WSRefresh=3,RestartAllServers=4):4 Save changes? [y|n]:y <<Return>> SUCCESS ``` Now you can rename the collection directory, and re-attach. (If you are unsure of any of these values, check them with collget before you take it offline). ``` rcadmin> collset Admin Alias:AdminServer Collection Alias:NewCollectionName Modify Type (Update=0, Insert=1):1 Path: Gateway[(o)dbc|(n)otes|(e)xchange|(d)ocumentum|(f)ilesys|(w)eb|o(t)her]: Style Alias: Document Access (Public=0,Secure=1,Anonymous=2): Query Parser [(s)imple|(b)oolPlus|(f)reeText|(o)ldFreeText|O(l)dSimple|O(t)her]: Description: Max. Search Time(msecs): Save changes? [y|n]:y rcadmin> indexattach Index Alias:NewCollectionName Index Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c Server Alias:YourDocserver Modify Type (Update=0, Insert=1):1 Index State (offline=0,hidden=1,online=2):2 Threads (default=3): Save changes? [y|n]:y <<Return>> SUCCESS ``` It should now show up again in the 'hierarchyview'. You can also use the "merge" utility to copy content from one collection to another, with a new name.
155,908
<p>I have defined tomcat:catalina:5.5.23 as a dependency to the cargo plugin, however I still get the following exception:</p> <pre><code>java.lang.ClassNotFoundException: org.apache.catalina.Connector at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:316) at org.codehaus.classworlds.RealmClassLoader.loadClassDirect(RealmClassLoader.java:195) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:255) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:274) at org.codehaus.classworlds.RealmClassLoader.loadClass(RealmClassLoader.java:214) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:374) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at org.codehaus.cargo.container.tomcat.internal.Tomcat5xEmbedded.preloadEmbedded(Tomcat5xEmbedded.java:232) </code></pre> <p>It looks like the RealmClassLoader is not finding the class, possibly due to java.security.AccessController.doPrivileged denying access. </p> <p>Has anyone got tomcat to run in embedded mode from within maven?</p>
[ { "answer_id": 169029, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 1, "selected": false, "text": "<p>Side note:\nYou can start jetty which is similar to tomcat. (Servlets will be available at <a href=\"http://localhost:8080/\" rel=\"nofollow noreferrer\">http://localhost:8080/</a> artefact-name)</p>\n\n<pre><code>mvn jetty6:run\n</code></pre>\n\n<p>You would have to add to your pom:</p>\n\n<pre><code>&lt;project&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt;\n &lt;artifactId&gt;maven-jetty6-plugin&lt;/artifactId&gt;\n &lt;configuration&gt;\n &lt;scanIntervalSeconds&gt;5&lt;/scanIntervalSeconds&gt;\n &lt;!--\n &lt;webXml&gt;${basedir}/WEB-INF/web.xml&lt;/webXml&gt;\n --&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n&lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 640436, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 0, "selected": false, "text": "<p>There is also a tomcat maven plugin:</p>\n\n<p><a href=\"http://mojo.codehaus.org/tomcat-maven-plugin/introduction.html\" rel=\"nofollow noreferrer\">http://mojo.codehaus.org/tomcat-maven-plugin/introduction.html</a></p>\n\n<pre><code>&lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;\n &lt;artifactId&gt;tomcat-maven-plugin&lt;/artifactId&gt;\n &lt;/plugin&gt;\n&lt;/plugins&gt;\n</code></pre>\n\n<p>On my machine this loads up tomcat 6. I'm not sure how to get it to work with tomcat 5.5</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
I have defined tomcat:catalina:5.5.23 as a dependency to the cargo plugin, however I still get the following exception: ``` java.lang.ClassNotFoundException: org.apache.catalina.Connector at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:316) at org.codehaus.classworlds.RealmClassLoader.loadClassDirect(RealmClassLoader.java:195) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:255) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:274) at org.codehaus.classworlds.RealmClassLoader.loadClass(RealmClassLoader.java:214) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:374) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at org.codehaus.cargo.container.tomcat.internal.Tomcat5xEmbedded.preloadEmbedded(Tomcat5xEmbedded.java:232) ``` It looks like the RealmClassLoader is not finding the class, possibly due to java.security.AccessController.doPrivileged denying access. Has anyone got tomcat to run in embedded mode from within maven?
Side note: You can start jetty which is similar to tomcat. (Servlets will be available at <http://localhost:8080/> artefact-name) ``` mvn jetty6:run ``` You would have to add to your pom: ``` <project> <build> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty6-plugin</artifactId> <configuration> <scanIntervalSeconds>5</scanIntervalSeconds> <!-- <webXml>${basedir}/WEB-INF/web.xml</webXml> --> </configuration> </plugin> </plugins> </build> </project> ```
155,911
<p>During software development, there may be bugs in the codebase which are known issues. These bugs will cause the regression/unit tests to fail, if the tests have been written well.</p> <p>There is constant debate in our teams about how failing tests should be managed:</p> <ol> <li><p>Comment out failing test cases with a REVISIT or TODO comment.</p> <ul> <li><strong>Advantage</strong>: We will always know when a <em>new</em> defect has been introduced, and not one we are already aware of.</li> <li><strong>Disadvantage</strong>: May forget to REVISIT the commented-out test case, meaning that the defect could slip through the cracks.</li> </ul></li> <li><p>Leave the test cases failing.</p> <ul> <li><strong>Advantage</strong>: Will not forget to fix the defects, as the script failures will constantly reminding you that a defect is present.</li> <li><strong>Disadvantage</strong>: Difficult to detect when a <em>new</em> defect is introduced, due to failure noise.</li> </ul></li> </ol> <p>I'd like to explore what the best practices are in this regard. Personally, I think a tri-state solution is the best for determining whether a script is passing. For example when you run a script, you could see the following:</p> <ul> <li>Percentage passed: 75%</li> <li>Percentage failed (expected): 20%</li> <li>Percentage failed (unexpected): 5%</li> </ul> <p>You would basically mark any test cases which you <em>expect</em> to fail (due to some defect) with some metadata. This ensures you still see the failure result at the end of the test, but immediately know if there is a <em>new</em> failure which you weren't expecting. This appears to take the best parts of the 2 proposals above.</p> <p>Does anyone have any best practices for managing this?</p>
[ { "answer_id": 155918, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 1, "selected": false, "text": "<p>I tend to leave these in, with an <a href=\"http://www.nunit.org/index.php?p=ignore&amp;r=2.2\" rel=\"nofollow noreferrer\">Ignore</a> attribute (this is using <a href=\"http://www.nunit.org/index.php?p=home\" rel=\"nofollow noreferrer\">NUnit</a>) - the test is mentioned in the test run output, so it's visible, hopefully meaning we won't forget it. Consider adding the issue/ticket ID in the \"ignore\" message. That way it will be resolved when the underlying problem is considered to be ripe - it'd be nice to fix failing tests right away, but sometimes small bugs have to wait until the time is right.</p>\n\n<p>I've considered the <a href=\"http://www.nunit.org/index.php?p=explicit&amp;r=2.2\" rel=\"nofollow noreferrer\">Explicit</a> attribute, which has the advantage of being able to be run without a recompile, but it doesn't take a \"reason\" argument, and in the version of NUnit we run, the test doesn't show up in the output as unrun.</p>\n" }, { "answer_id": 155942, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 4, "selected": true, "text": "<p>I would leave your test cases in. In my experience, commenting out code with something like</p>\n\n<pre><code>// TODO: fix test case\n</code></pre>\n\n<p>is akin to doing:</p>\n\n<pre><code>// HAHA: you'll never revisit me\n</code></pre>\n\n<p>In all seriousness, as you get closer to shipping, the desire to revisit TODO's in code tends to fade, especially with things like unit tests because you are concentrating on fixing other parts of the code.</p>\n\n<p>Leave the tests in perhaps with your \"tri-state\" solution. Howeveer, I would strongly encourage fixing those cases ASAP. My problem with constant reminders is that after people see them, they tend to gloss over them and say \"oh yeah, we get those errors all the time...\"</p>\n\n<p>Case in point -- in some of our code, we have introduced the idea of \"skippable asserts\" -- asserts which are there to let you know there is a problem, but allow our testers to move past them on into the rest of the code. We've come to find out that QA started saying things like \"oh yeah, we get that assert all the time and we were told it was skippable\" and bugs didn't get reported.</p>\n\n<p>I guess what I'm suggesting is that there is another alternative, which is to fix the bugs that your test cases find immediately. There may be practical reasons not to do so, but getting in that habit now could be more beneficial in the long run.</p>\n" }, { "answer_id": 155971, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 1, "selected": false, "text": "<p>We did the following: Put a hierarchy on the tests.</p>\n\n<p>Example: You have to test 3 things.</p>\n\n<ul>\n<li>Test the login (login, retrieve the user name, get the \"last login date\" or something familiar etc.)</li>\n<li>Test the database retrieval (search for a given \"schnitzelmitkartoffelsalat\" - tag, search the latest tags)</li>\n<li>Test web services (connect, get the version number, retrieve simple data, retrieve detailed data, change data)</li>\n</ul>\n\n<p>Every testing point has subpoints, as stated in brackets. We split these hierarchical. Take the last example:</p>\n\n<pre><code>3. Connect to a web service\n ...\n3.1. Get the version number\n ...\n3.2. Data:\n 3.2.1. Get the version number\n 3.2.2. Retrieve simple data\n 3.2.3. Retrieve detailed data\n 3.2.4. Change data\n</code></pre>\n\n<p>If a point fails (while developing) <strong>give one exact error message</strong>. I.e. 3.2.2. failed. Then the testing unit will not execute the tests for 3.2.3. and 3.2.4. . This way you get one (exact) error message: \"3.2.2 failed\". Thus leaving the programmer to solve that problem (first) and not handle 3.2.3. and 3.2.4. because this would not work out.</p>\n\n<p>That helped a lot to clarify the problem and to make clear what has to be done at first.</p>\n" }, { "answer_id": 156003, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>I think you need a TODO watcher that produces the \"TODO\" comments from the code base. The TODO <em>is</em> your test metadata. It's one line in front of the known failure message and very easy to correlate.</p>\n\n<p>TODO's are good. Use them. Actively management them by actually putting them into the backlog on a regular basis.</p>\n" }, { "answer_id": 156047, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>I generally work in Perl and Perl's Test::* modules allow you to insert TODO blocks:</p>\n\n<pre><code>TODO: {\n local $TODO = \"This has not been implemented yet.\"\n\n # Tests expected to fail go here\n}\n</code></pre>\n\n<p>In the detailed output of the test run, the message in $TODO is appended to the pass/fail report for each test in the TODO block, so as to explain why it was expected to fail. For the summary of test results, all TODO tests are treated as having succeeded, but, if any actually return a successful result, the summary will also count those up and report the number of tests which unexpectedly succeeded.</p>\n\n<p>My recommendation, then, would be to find a testing tool which has similar capabilities. (Or just use Perl for your testing, even if the code being tested is in another language...)</p>\n" }, { "answer_id": 156148, "author": "Zack Elan", "author_id": 2461, "author_profile": "https://Stackoverflow.com/users/2461", "pm_score": 0, "selected": false, "text": "<p>#5 on Joel's <a href=\"http://www.joelonsoftware.com/articles/fog0000000043.html\" rel=\"nofollow noreferrer\">&quot;12 Steps to Better Code&quot;</a> is fixing bugs before you write new code:</p>\n<blockquote>\n<p>When you have a bug in your code that you see the first time you try to run it, you will be able to fix it in no time at all, because all the code is still fresh in your mind.</p>\n<p>If you find a bug in some code that you wrote a few days ago, it will take you a while to hunt it down, but when you reread the code you wrote, you'll remember everything and you'll be able to fix the bug in a reasonable amount of time.</p>\n<p>But if you find a bug in code that you wrote a few months ago, you'll probably have forgotten a lot of things about that code, and it's much harder to fix. By that time you may be fixing somebody else's code, and they may be in Aruba on vacation, in which case, fixing the bug is like science: you have to be slow, methodical, and meticulous, and you can't be sure how long it will take to discover the cure.</p>\n<p>And if you find a bug in code that has already shipped, you're going to incur incredible expense getting it fixed.</p>\n</blockquote>\n<p>But if you really want to ignore failing tests, use the [Ignore] attribute or its equivalent in whatever test framework you use. In MbUnit's HTML output, ignored tests are displayed in yellow, compared to the red of failing tests. This lets you easily notice a newly-failing test, but you won't lose track of the known-failing tests.</p>\n" }, { "answer_id": 156192, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 3, "selected": false, "text": "<p>Fix the bug right away.</p>\n\n<p>If it's too complex to do right away, it's probably too large a unit for unit testing.</p>\n\n<p>Lose the unit test, and put the defect in your bug database. That way it has visibility, can be prioritized, etc.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
During software development, there may be bugs in the codebase which are known issues. These bugs will cause the regression/unit tests to fail, if the tests have been written well. There is constant debate in our teams about how failing tests should be managed: 1. Comment out failing test cases with a REVISIT or TODO comment. * **Advantage**: We will always know when a *new* defect has been introduced, and not one we are already aware of. * **Disadvantage**: May forget to REVISIT the commented-out test case, meaning that the defect could slip through the cracks. 2. Leave the test cases failing. * **Advantage**: Will not forget to fix the defects, as the script failures will constantly reminding you that a defect is present. * **Disadvantage**: Difficult to detect when a *new* defect is introduced, due to failure noise. I'd like to explore what the best practices are in this regard. Personally, I think a tri-state solution is the best for determining whether a script is passing. For example when you run a script, you could see the following: * Percentage passed: 75% * Percentage failed (expected): 20% * Percentage failed (unexpected): 5% You would basically mark any test cases which you *expect* to fail (due to some defect) with some metadata. This ensures you still see the failure result at the end of the test, but immediately know if there is a *new* failure which you weren't expecting. This appears to take the best parts of the 2 proposals above. Does anyone have any best practices for managing this?
I would leave your test cases in. In my experience, commenting out code with something like ``` // TODO: fix test case ``` is akin to doing: ``` // HAHA: you'll never revisit me ``` In all seriousness, as you get closer to shipping, the desire to revisit TODO's in code tends to fade, especially with things like unit tests because you are concentrating on fixing other parts of the code. Leave the tests in perhaps with your "tri-state" solution. Howeveer, I would strongly encourage fixing those cases ASAP. My problem with constant reminders is that after people see them, they tend to gloss over them and say "oh yeah, we get those errors all the time..." Case in point -- in some of our code, we have introduced the idea of "skippable asserts" -- asserts which are there to let you know there is a problem, but allow our testers to move past them on into the rest of the code. We've come to find out that QA started saying things like "oh yeah, we get that assert all the time and we were told it was skippable" and bugs didn't get reported. I guess what I'm suggesting is that there is another alternative, which is to fix the bugs that your test cases find immediately. There may be practical reasons not to do so, but getting in that habit now could be more beneficial in the long run.
155,912
<p>Calling <code>Validate()</code> on an <strong>XmlDocument</strong> requires passing in a <code>ValidationEventHandler</code> delegate. That event function gets a <code>ValidationEventArgs</code> parameter which in turn has an <code>Exception</code> property of the type <code>XmlSchemaException</code>. Whew!</p> <p>My current code looks like this:</p> <pre><code>ValidationEventHandler onValidationError = delegate(object sender, ValidationEventArgs args) { throw(args.Exception); } doc.Validate(onValidationError); </code></pre> <p>Is there some other method I'm overlooking which simply <em>throws</em> the <code>XmlSchemaException</code> if validation fails (warnings ignored entirely)?</p>
[ { "answer_id": 155925, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 3, "selected": true, "text": "<p>Because the Validate method takes the ValidationEventHandler delegate, it is left up to the developer to decide what to do with the excpetion. What you are doing is correct.</p>\n" }, { "answer_id": 57436064, "author": "Adam Porad", "author_id": 21353, "author_profile": "https://Stackoverflow.com/users/21353", "pm_score": 0, "selected": false, "text": "<p>Passing <code>null</code> for the <code>validationEventHandler</code> parameter will throw an exception if there are any errors.</p>\n\n<p>The MSDN documentation for the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.xml.schema.extensions.validate?#System_Xml_Schema_Extensions_Validate_System_Xml_Linq_XDocument_System_Xml_Schema_XmlSchemaSet_System_Xml_Schema_ValidationEventHandler_\" rel=\"nofollow noreferrer\">Extensions.Validate</a> method describes the <code>validationEventHandler</code> parameter as:</p>\n\n<blockquote>\n <p>A <code>ValidationEventHandler</code> for an event that occurs when the reader\n encounters validation errors. If <code>null</code>, throws an exception upon\n validation errors.</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
Calling `Validate()` on an **XmlDocument** requires passing in a `ValidationEventHandler` delegate. That event function gets a `ValidationEventArgs` parameter which in turn has an `Exception` property of the type `XmlSchemaException`. Whew! My current code looks like this: ``` ValidationEventHandler onValidationError = delegate(object sender, ValidationEventArgs args) { throw(args.Exception); } doc.Validate(onValidationError); ``` Is there some other method I'm overlooking which simply *throws* the `XmlSchemaException` if validation fails (warnings ignored entirely)?
Because the Validate method takes the ValidationEventHandler delegate, it is left up to the developer to decide what to do with the excpetion. What you are doing is correct.
155,920
<p>I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?</p> <p>Here is an example script that does not work on my hosts' server as of right now:</p> <pre><code>&lt;?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = ". $_SESSION['views']; echo '&lt;p&gt;&lt;a href="page1.php"&gt;Refresh&lt;/a&gt;&lt;/p&gt;'; ?&gt; </code></pre> <p>The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.</p> <p>Here is the phpinfo() for my hosts' server (PHP Version 4.4.7): <img src="https://i.stack.imgur.com/3bv0K.png" alt="alt text"></p>
[ { "answer_id": 155941, "author": "vIceBerg", "author_id": 17766, "author_profile": "https://Stackoverflow.com/users/17766", "pm_score": 3, "selected": false, "text": "<p>Use <code>phpinfo()</code> and check the <code>session.*</code> settings.</p>\n\n<p>Maybe the information is stored in cookies and your browser does not accept cookies, something like that.</p>\n\n<p>Check that first and come back with the results.</p>\n\n<p>You can also do a <code>print_r($_SESSION);</code> to have a dump of this variable and see the content....</p>\n\n<p>Regarding your <code>phpinfo()</code>, is the <code>session.save_path</code> a valid one? Does your web server have write access to this directory?</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 155945, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Check the value of \"views\" when before you increment it. If, for some bizarre reason, it's getting set to a string, then when you add 1 to it, it'll always return 1.</p>\n\n<pre><code>if (isset($_SESSION['views'])) {\n if (!is_numeric($_SESSION['views'])) {\n echo \"CRAP!\";\n }\n ++$_SESSION['views'];\n} else {\n $_SESSION['views'] = 1;\n}\n</code></pre>\n" }, { "answer_id": 155982, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 3, "selected": false, "text": "<p>Check to see if the session save path is writable by the web server.</p>\n\n<p>Make sure you have cookies turned on.. (I forget when I turn them off to test something)</p>\n\n<p>Use firefox with the firebug extension to see if the cookie is being set and transmitted back.</p>\n\n<p>And on a unrelated note, start looking at php5, because php 4.4.9 is the last of the php4 series.</p>\n" }, { "answer_id": 156254, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 2, "selected": false, "text": "<p>Well, we can eliminate code error because I tested the code on my own server (PHP 5).</p>\n\n<p>Here's what to check for:</p>\n\n<ol>\n<li><p>Are you calling session_unset() or session_destroy() anywhere? These functions will delete the session data immediately. If I put these at the end of my script, it begins behaving exactly like you describe.</p></li>\n<li><p>Does it act the same in all browsers? If it works on one browser and not another, you may have a configuration problem on the nonfunctioning browser (i.e. you turned off cookies and forgot to turn them on, or are blocking cookies by mistake).</p></li>\n<li><p>Is the session folder writable? You can't test this with is_writable(), so you'll need to go to the folder (from phpinfo() it looks like /var/php_sessions) and make sure sessions are actually getting created.</p></li>\n</ol>\n" }, { "answer_id": 156381, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<p>I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.</p>\n" }, { "answer_id": 156545, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 1, "selected": false, "text": "<p>Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.</p>\n" }, { "answer_id": 159948, "author": "Crackerjack", "author_id": 13556, "author_profile": "https://Stackoverflow.com/users/13556", "pm_score": 6, "selected": true, "text": "<p>Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare <code>ini_set(' session.save_path','SOME WRITABLE PATH');</code> in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.</p>\n" }, { "answer_id": 932099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Just wanted to add a little note that this can also occur if you accidentally miss the session_start() statement on your pages.</p>\n" }, { "answer_id": 1066267, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.</p>\n</blockquote>\n\n<p>Thanks for this one Darryl. This helped me out. I was deleting a session variable, and for some reason it was keeping the session from committing. now i'm just setting it to null instead (which is fine for my app), and it works. </p>\n" }, { "answer_id": 1212090, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out</p>\n" }, { "answer_id": 2613773, "author": "Harry", "author_id": 312833, "author_profile": "https://Stackoverflow.com/users/312833", "pm_score": 2, "selected": false, "text": "<p>If you set a session in php5, then try to read it on a php4 page, it might not look in the correct place! Make the pages the same php version or set the session_path.</p>\n" }, { "answer_id": 2616541, "author": "buzzy blogger", "author_id": 313829, "author_profile": "https://Stackoverflow.com/users/313829", "pm_score": 2, "selected": false, "text": "<p>Check who the group and owner are of the folder where the script runs. If the group id or user id are wrong, for example, set to root, it will cause sessions to not be saved properly.</p>\n" }, { "answer_id": 3908005, "author": "Shane N", "author_id": 224031, "author_profile": "https://Stackoverflow.com/users/224031", "pm_score": 3, "selected": false, "text": "<p>Had same problem - what happened to me is our server admin changed the session.cookie_secure boolean to On, which means that cookies will only be sent over a secure connection. Since the cookie was not being found, php was creating a new session every time, thus session variables were not being seen.</p>\n" }, { "answer_id": 6428807, "author": "Aleks G", "author_id": 717214, "author_profile": "https://Stackoverflow.com/users/717214", "pm_score": 2, "selected": false, "text": "<p>I spent ages looking for the answer for a similar problem. It wasn't an issue with the code or the setup, as a very similar code worked perfectly in another .php on the same server. Turned out the problem was caused by a very large amount of data being saved into the session in this page. In one place we had a line like this:<code>$_SESSION['full_list'] = $full_list</code> where <code>$full_list</code> was an array of data loaded from the database; each row was an array of about 150 elements. When the code was initially written a couple of years ago, the DB only contained about 1000 rows, so the <code>$full_list</code> contained about 100 elements, each being an array of about 20 elements. With time, the 20 elements turned into 150 and 1000 rows turned into 17000, so the code was storing close to 64 meg of data into the session. Apparently, with this amount of data being stored, it refused to store anything else. Once we changed the code to deal with data locally without saving it into the session, everything worked perfectly.</p>\n" }, { "answer_id": 6665571, "author": "Slawa", "author_id": 417153, "author_profile": "https://Stackoverflow.com/users/417153", "pm_score": 1, "selected": false, "text": "<p>I had session cookie path set to \"//\" instead of \"/\". Firebug is awesome.\nHope it helps somebody.</p>\n" }, { "answer_id": 6777970, "author": "harry", "author_id": 856186, "author_profile": "https://Stackoverflow.com/users/856186", "pm_score": 3, "selected": false, "text": "<p>I had following problem</p>\n\n<p>index.php</p>\n\n<pre><code>&lt;?\n session_start();\n $_SESSION['a'] = 123;\n header('location:index2.php');\n?&gt;\n</code></pre>\n\n<p>index2.php</p>\n\n<pre><code>&lt;?\n session_start();\n echo $_SESSION['a'];\n?&gt;\n</code></pre>\n\n<p>The variable <code>$_SESSION['a']</code> was not set correctly. Then I have changed the <code>index.php</code> acordingly</p>\n\n<pre><code>&lt;?\n session_start();\n $_SESSION['a'] = 123;\n session_write_close();\n header('location:index2.php');\n?&gt;\n</code></pre>\n\n<p>I dont know what this internally means, I just explain it to myself that the session variable change was not quick enough :)</p>\n" }, { "answer_id": 7883792, "author": "paul", "author_id": 1011931, "author_profile": "https://Stackoverflow.com/users/1011931", "pm_score": 4, "selected": false, "text": "<p>Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions.</p>\n" }, { "answer_id": 8839945, "author": "Sean Anderson", "author_id": 513905, "author_profile": "https://Stackoverflow.com/users/513905", "pm_score": 1, "selected": false, "text": "<p>I had this problem when using secure pages where I was coming from www.domain.com/auth.php that redirected to domain.com/destpage.php. I removed the www from the auth.php link and it worked. This threw me because everything worked otherwise; the session was not set when I arrived at the destination though.</p>\n" }, { "answer_id": 11118083, "author": "hyarion", "author_id": 1047535, "author_profile": "https://Stackoverflow.com/users/1047535", "pm_score": 1, "selected": false, "text": "<p>A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.</p>\n\n<p>I've had this issue before where I had a blank line before session_start() which caused it not to work properly.</p>\n" }, { "answer_id": 12554786, "author": "emaniacs", "author_id": 1286248, "author_profile": "https://Stackoverflow.com/users/1286248", "pm_score": 1, "selected": false, "text": "<p>Edit your php.ini.<br>\nI think the value of session.gc_probability is 1, so set it to 0.</p>\n\n<pre><code>session.gc_probability=0\n</code></pre>\n" }, { "answer_id": 26180998, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 1, "selected": false, "text": "<p>Adding my solution: </p>\n\n<p>Check if you access the <strong>correct domain</strong>. I was using <code>www.mysite.com</code> to start the session, and tried to receive it from <code>mysite.com</code> (without the <code>www</code>). </p>\n\n<p>I have solved this by adding a htaccess rewrite of all domains to www to be on the safe side/site.</p>\n\n<p>Also check if you use http or https.</p>\n" }, { "answer_id": 26191908, "author": "Pete855217", "author_id": 855217, "author_profile": "https://Stackoverflow.com/users/855217", "pm_score": 0, "selected": false, "text": "<p>Another few things I had to do (I had same problem: no sesson retention after PHP upgrade to 5.4). You many not need these, depending on what your server's php.ini contains (check phpinfio());</p>\n\n<pre><code>session.use_trans_sid=0 ; Do not add session id to URI (osc does this)\nsession.use_cookies=0; ; ensure cookies are not used\nsession.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT\nsession.save_path=~/tmp/osc; ; Set to same as admin setting\nsession.auto_start = off; Tell PHP not to start sessions, osc code will do this\n</code></pre>\n\n<p>Basically, your php.ini should be set to no cookies, and session parameters must be consistent with what osc wants.</p>\n\n<p>You may also need to change a few session code snippets in application_top.php - creating objects where none exist in the tep_session_is_registered(...) calls (e eg. navigation object), set $HTTP_ variables to the newer $_SERVER ones and a few other isset tests for empty objects (google for info). I ended up being able to use the original sessions.php files (includes/classes and includes/functions) with a slightly modified application_top.php to get things going again. The php.ini settings were the main problem, but this of course depends on what your server company has installed as the defaults.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13556/" ]
I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $\_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on? Here is an example script that does not work on my hosts' server as of right now: ``` <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = ". $_SESSION['views']; echo '<p><a href="page1.php">Refresh</a></p>'; ?> ``` The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first. Here is the phpinfo() for my hosts' server (PHP Version 4.4.7): ![alt text](https://i.stack.imgur.com/3bv0K.png)
Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php\_sessions which didn't exist anymore. A solution would have been to declare `ini_set(' session.save_path','SOME WRITABLE PATH');` in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.
155,930
<p>I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.</p> <p>Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running. </p> <p>For windows I use:</p> <pre><code>ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); </code></pre> <p>For Linux I currently use:</p> <pre><code>pid_t pid; char *args[2]; char *prog=0; char firefox[]={"/usr/bin/firefox"}; if(strstri(filename,".html")) prog=firefox; if(prog) { args[0]=(char *)filename; args[1]=0; pid=fork(); if(!pid) execvp(prog,args); } </code></pre>
[ { "answer_id": 155946, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "<p>If you're writing this for modern distros, you can use <code>xdg-open</code>:</p>\n\n<pre><code>$ xdg-open http://google.com/\n</code></pre>\n\n<p>If you're on an older version you'll have to use a desktop-specific command like <code>gnome-open</code> or <code>exo-open</code>.</p>\n" }, { "answer_id": 159102, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 0, "selected": false, "text": "<p>If you don't want to involve additional applications, just use the built-in remote control commands of firefox. E.g:</p>\n\n<pre><code>firefox -remote 'openurl(http://stackoverflow.com)'\n</code></pre>\n\n<p>Se detailed usage at <a href=\"http://www.mozilla.org/unix/remote.html\" rel=\"nofollow noreferrer\">http://www.mozilla.org/unix/remote.html</a></p>\n" }, { "answer_id": 159263, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>xdg-open is the new standard, and you should use it when possible. However, if the distro is more than a few years old, it may not exist, and alternative mechanisms include $BROWSER (older attempted standard), gnome-open (Gnome), kfmclient exec (KDE), exo-open (Xfce), or parsing mailcap yourself (the text/html handler will be likely be a browser).</p>\n\n<p>That being said, most applications don't bother with that much work -- if they're built for a particular environment, they use that environment's launch mechanisms. For example, Gnome has gnome&#95;url&#95;show, KDE has KRun, most terminal programs (for example, mutt) parse mailcap, etc. Hardcoding a browser and allowing the distributor or user to override the default is common too.</p>\n\n<p>I don't suggest hardcoding this, but if you really want to open a new tab in Firefox, you can use \"firefox -new-tab $URL\".</p>\n" }, { "answer_id": 173901, "author": "oliver", "author_id": 2148773, "author_profile": "https://Stackoverflow.com/users/2148773", "pm_score": 1, "selected": false, "text": "<p>A note for xdg-open: check <a href=\"http://portland.freedesktop.org/wiki/\" rel=\"nofollow noreferrer\">http://portland.freedesktop.org/wiki/</a> , section \"Using Xdg-utils\"; it states that you can include the xdg-open script in your own application and use that as fallback in case the target system doesn't have xdg-open already installed.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build. Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running. For windows I use: ``` ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); ``` For Linux I currently use: ``` pid_t pid; char *args[2]; char *prog=0; char firefox[]={"/usr/bin/firefox"}; if(strstri(filename,".html")) prog=firefox; if(prog) { args[0]=(char *)filename; args[1]=0; pid=fork(); if(!pid) execvp(prog,args); } ```
If you're writing this for modern distros, you can use `xdg-open`: ``` $ xdg-open http://google.com/ ``` If you're on an older version you'll have to use a desktop-specific command like `gnome-open` or `exo-open`.
155,932
<p>I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.</p>
[ { "answer_id": 155937, "author": "Michael Ratanapintha", "author_id": 1879, "author_profile": "https://Stackoverflow.com/users/1879", "pm_score": 3, "selected": false, "text": "<p>If you have an NT-family Windows (one with <code>cmd.exe</code> as the shell), try <a href=\"http://technet.microsoft.com/library/bb490909.aspx\" rel=\"noreferrer\">the FOR /F command</a>.</p>\n" }, { "answer_id": 155950, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 6, "selected": false, "text": "<p>From the Windows command line reference:</p>\n\n<p>To parse a file, ignoring commented lines, type:</p>\n\n<pre><code>for /F \"eol=; tokens=2,3* delims=,\" %i in (myfile.txt) do @echo %i %j %k\n</code></pre>\n\n<p>This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens. </p>\n\n<p>If the file names that you supply contain spaces, use quotation marks around the text (for example, \"File Name\"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.</p>\n\n<p>By the way, you can find the command-line help file on most Windows systems at:</p>\n\n<pre><code> \"C:\\WINDOWS\\Help\\ntcmds.chm\"\n</code></pre>\n" }, { "answer_id": 155954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here's a bat file I wrote to execute all SQL scripts in a folder:</p>\n\n<pre><code>REM ******************************************************************\nREM Runs all *.sql scripts sorted by filename in the current folder.\nREM To use integrated auth change -U &lt;user&gt; -P &lt;password&gt; to -E\nREM ******************************************************************\n\ndir /B /O:n *.sql &gt; RunSqlScripts.tmp\nfor /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A\ndel RunSqlScripts.tmp\n</code></pre>\n" }, { "answer_id": 163873, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 9, "selected": true, "text": "<p>I needed to process the entire line as a whole. Here is what I found to work.</p>\n<pre><code>for /F &quot;tokens=*&quot; %%A in (myfile.txt) do [process] %%A\n</code></pre>\n<p>The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.</p>\n<p><a href=\"http://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"noreferrer\">For Command on TechNet</a></p>\n<hr />\n<p>If there are spaces in your file path, you need to use <code>usebackq</code>. For example.</p>\n<pre><code>for /F &quot;usebackq tokens=*&quot; %%A in (&quot;my file.txt&quot;) do [process] %%A\n</code></pre>\n" }, { "answer_id": 1266109, "author": "Paul", "author_id": 121257, "author_profile": "https://Stackoverflow.com/users/121257", "pm_score": 4, "selected": false, "text": "<p>Or, you may exclude the options in quotes:</p>\n\n<pre><code>FOR /F %%i IN (myfile.txt) DO ECHO %%i\n</code></pre>\n" }, { "answer_id": 2766240, "author": "user332474", "author_id": 332474, "author_profile": "https://Stackoverflow.com/users/332474", "pm_score": 5, "selected": false, "text": "<p>In a Batch File you <strong>MUST</strong> use <code>%%</code> instead of <code>%</code> : (Type <code>help for</code>)</p>\n\n<pre><code>for /F \"tokens=1,2,3\" %%i in (myfile.txt) do call :process %%i %%j %%k\ngoto thenextstep\n:process\nset VAR1=%1\nset VAR2=%2\nset VAR3=%3\nCOMMANDS TO PROCESS INFORMATION\ngoto :EOF\n</code></pre>\n\n<p>What this does:\nThe \"do call :process %%i %%j %%k\" at the end of the for command passes the information acquired in the for command from myfile.txt to the \"process\" 'subroutine'.</p>\n\n<p>When you're using the for command in a batch program, you need to use double % signs for the variables.</p>\n\n<p>The following lines pass those variables from the for command to the process 'sub routine' and allow you to process this information.</p>\n\n<pre><code>set VAR1=%1\n set VAR2=%2\n set VAR3=%3\n</code></pre>\n\n<p>I have some pretty advanced uses of this exact setup that I would be willing to share if further examples are needed. Add in your EOL or Delims as needed of course.</p>\n" }, { "answer_id": 8976789, "author": "Yogesh Mahajan", "author_id": 1852508, "author_profile": "https://Stackoverflow.com/users/1852508", "pm_score": 5, "selected": false, "text": "<p>Improving the first \"FOR /F..\" answer:\nWhat I had to do was to call execute every script listed in MyList.txt, so it worked for me:</p>\n\n<pre><code>for /F \"tokens=*\" %A in (MyList.txt) do CALL %A ARG1\n</code></pre>\n\n<p>--OR, if you wish to do it over the multiple line: </p>\n\n<pre><code>for /F \"tokens=*\" %A in (MuList.txt) do (\nECHO Processing %A....\nCALL %A ARG1\n)\n</code></pre>\n\n<p>Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:</p>\n\n<pre><code>---START of MyScript.bat---\n@echo off\nfor /F \"tokens=*\" %%A in ( MyList.TXT) do (\n ECHO Processing %%A.... \n CALL %%A ARG1 \n)\n@echo on\n;---END of MyScript.bat---\n</code></pre>\n" }, { "answer_id": 14285280, "author": "DotDotJames", "author_id": 625754, "author_profile": "https://Stackoverflow.com/users/625754", "pm_score": 1, "selected": false, "text": "<p>Modded examples here to list our Rails apps on Heroku - thanks!</p>\n\n<pre><code>cmd /C \"heroku list &gt; heroku_apps.txt\"\nfind /v \"=\" heroku_apps.txt | find /v \".TXT\" | findstr /r /v /c:\"^$\" &gt; heroku_apps_list.txt\nfor /F \"tokens=1\" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i\n</code></pre>\n\n<p>Full code <a href=\"https://gist.github.com/4512454/\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 16792536, "author": "Marvin Thobejane", "author_id": 1358924, "author_profile": "https://Stackoverflow.com/users/1358924", "pm_score": 5, "selected": false, "text": "<p>@MrKraus's <a href=\"https://stackoverflow.com/a/163873/1358924\">answer</a> is instructive. Further, let me add that <strong>if you want to load a file located in the same directory</strong> as the batch file, prefix the file name with %~dp0. Here is an example:</p>\n\n<pre><code>cd /d %~dp0\nfor /F \"tokens=*\" %%A in (myfile.txt) do [process] %%A\n</code></pre>\n\n<p><strong>NB:</strong>: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. 'my file.txt' or 'c:\\Program Files'), use:</p>\n\n<pre><code>for /F \"tokens=*\" %%A in ('type \"my file.txt\"') do [process] %%A\n</code></pre>\n\n<p>, with the <strong>type</strong> keyword calling the <code>type</code> program, which displays the contents of a text file. If you don't want to suffer the overhead of calling the type command you should change the directory to the text file's directory. Note that type is still required for file names with spaces.</p>\n\n<p>I hope this helps someone!</p>\n" }, { "answer_id": 17723989, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 4, "selected": false, "text": "<p>The accepted answer is good, but has two limitations.<br>\nIt drops empty lines and lines beginning with <code>;</code></p>\n\n<p>To read lines of any content, you need the delayed expansion toggling technic. </p>\n\n<pre><code>@echo off\nSETLOCAL DisableDelayedExpansion\nFOR /F \"usebackq delims=\" %%a in (`\"findstr /n ^^ text.txt\"`) do (\n set \"var=%%a\"\n SETLOCAL EnableDelayedExpansion\n set \"var=!var:*:=!\"\n echo(!var!\n ENDLOCAL\n)\n</code></pre>\n\n<p>Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore. </p>\n\n<p>DelayedExpansion needs to be disabled, when accessing the <code>%%a</code> parameter, else exclamation marks <code>!</code> and carets <code>^</code> will be lost, as they have special meanings in that mode. </p>\n\n<p>But to remove the line number from the line, the delayed expansion needs to be enabled.<br>\n<code>set \"var=!var:*:=!\"</code> removes all up to the first colon (using <code>delims=:</code> would remove also all colons at the beginning of a line, not only the one from findstr).<br>\nThe endlocal disables the delayed expansion again for the next line.</p>\n\n<p>The only limitation is now the line length limit of ~8191, but there seems no way to overcome this. </p>\n" }, { "answer_id": 52806421, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 3, "selected": false, "text": "<p>The accepted anwser using <code>cmd.exe</code> and </p>\n\n<pre><code>for /F \"tokens=*\" %F in (file.txt) do whatever \"%F\" ...\n</code></pre>\n\n<p>works only for \"normal\" files. It fails miserably with huge files.</p>\n\n<p>For big files, you may need to use Powershell and something like this:</p>\n\n<pre><code>[IO.File]::ReadLines(\"file.txt\") | ForEach-Object { whatever \"$_\" }\n</code></pre>\n\n<p>or if you have enough memory:</p>\n\n<pre><code>foreach($line in [System.IO.File]::ReadLines(\"file.txt\")) { whatever \"$line\" } \n</code></pre>\n\n<p>This worked for me with a 250 MB file containing over 2 million lines, where the <code>for /F ...</code> command got stuck after a few thousand lines.</p>\n\n<p>For the differences between <code>foreach</code> and <code>ForEach-Object</code>, see <a href=\"https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/08/getting-to-know-foreach-and-foreach-object/\" rel=\"noreferrer\">Getting to Know ForEach and ForEach-Object</a>.</p>\n\n<p>(credits: <a href=\"https://stackoverflow.com/questions/33511772/read-file-line-by-line-in-powershell\">Read file line by line in PowerShell</a> )</p>\n" }, { "answer_id": 60025292, "author": "Zimba", "author_id": 5958708, "author_profile": "https://Stackoverflow.com/users/5958708", "pm_score": 1, "selected": false, "text": "<p>To print all lines in text file from command line (with delayedExpansion):</p>\n<pre><code>set input=&quot;path/to/file.txt&quot;\n\nfor /f &quot;tokens=* delims=[&quot; %i in ('type &quot;%input%&quot; ^| find /v /n &quot;&quot;') do (\nset a=%i\nset a=!a:*]=]!\necho:!a:~1!)\n</code></pre>\n<p>Works with leading whitespace, blank lines, whitespace lines.</p>\n<p>Tested on Win 10 CMD</p>\n<p><a href=\"https://i.stack.imgur.com/82ttF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/82ttF.png\" alt=\"Test text\" /></a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5132/" ]
I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.
I needed to process the entire line as a whole. Here is what I found to work. ``` for /F "tokens=*" %%A in (myfile.txt) do [process] %%A ``` The tokens keyword with an asterisk (\*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces. [For Command on TechNet](http://technet.microsoft.com/en-us/library/bb490909.aspx) --- If there are spaces in your file path, you need to use `usebackq`. For example. ``` for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A ```
155,934
<p>What GNU/Linux command-line tool would I use for performing a search and replace on a file? </p> <p>Can the search text, and replacement, be specified in a regex format?</p>
[ { "answer_id": 155939, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 5, "selected": false, "text": "<p>Perl was invented for this:</p>\n\n<pre><code>perl -pi -e 's/foo/bar/g;' *.txt\n</code></pre>\n\n<p>Any normal s/// pattern in those single quotes. You can keep a backup with something like this:</p>\n\n<pre><code>perl -pi.bak -e 's/foo/bar/g;' *.txt\n</code></pre>\n\n<p>Or pipeline:</p>\n\n<pre><code>cat file.txt | perl -ne 's/foo/bar/g;' | less\n</code></pre>\n\n<p>But that's really more sed's job.</p>\n" }, { "answer_id": 155944, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.grymoire.com/Unix/Sed.html\" rel=\"noreferrer\">sed</a>, the stream editor, and yes, it uses regex.</p>\n" }, { "answer_id": 155956, "author": "Cristian Ciupitu", "author_id": 12892, "author_profile": "https://Stackoverflow.com/users/12892", "pm_score": 7, "selected": true, "text": "<pre><code>sed 's/a.*b/xyz/g;' old_file &gt; new_file\n</code></pre>\n<p><a href=\"http://www.gnu.org/software/sed/\" rel=\"nofollow noreferrer\">GNU sed</a> (which you probably have) is even more versatile:</p>\n<pre><code>sed -r --in-place 's/a(.*)b/x\\1y/g;' your_file\n</code></pre>\n<p>Here is a brief explanation of those options:</p>\n<blockquote>\n<p><strong>-i[SUFFIX], --in-place[=SUFFIX]</strong>\nedit files in place (makes backup if extension supplied)</p>\n<p><strong>-r, --regexp-extended</strong>\nuse extended regular expressions in the script.</p>\n</blockquote>\n<p>The <a href=\"http://www.freebsd.org/cgi/man.cgi?query=sed&amp;sektion=1\" rel=\"nofollow noreferrer\">FreeBSD</a>, <a href=\"https://man.netbsd.org/sed.1\" rel=\"nofollow noreferrer\">NetBSD</a> and <a href=\"http://man.openbsd.org/sed.1\" rel=\"nofollow noreferrer\">OpenBSD</a> versions also supports these options.</p>\n<p>If you want to learn more about sed, <a href=\"https://stackoverflow.com/questions/155934/what-gnu-linux-command-line-tool-would-i-use-for-performing-a-search-and-replace/155944#155944\">Cori</a> has suggested <a href=\"http://www.grymoire.com/Unix/Sed.html\" rel=\"nofollow noreferrer\">this tutorial</a>.</p>\n" }, { "answer_id": 159354, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 3, "selected": false, "text": "<p>Consider Ruby as an alternative to Perl. It stole most of Perl's one-liner commandline args (<code>-i</code>, <code>-p</code>, <code>-l</code>, <code>-e</code>, <code>-n</code>) and auto-sets <code>$_</code> for you like Perl does and has plenty of regex goodness. Additionally Ruby's syntax may be more comfortable and easier to read or write than Perl's or sed's. (Or not, depending on your tastes.)</p>\n\n<p><code>ruby -pi.bak -e '$_.gsub!(/foo|bar/){|x| x.upcase}' *.txt</code></p>\n\n<p>vs.</p>\n\n<p><code>perl -pi.bak -e 's/(foo|bar)/\\U\\1/g' *.txt</code></p>\n\n<p>In many cases when dealing with one-liners, performance isn't enough of an issue to care whether you use lightweight sed or heavyweight Perl or heaveier-weight Ruby. Use whatever is easiest to write.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045/" ]
What GNU/Linux command-line tool would I use for performing a search and replace on a file? Can the search text, and replacement, be specified in a regex format?
``` sed 's/a.*b/xyz/g;' old_file > new_file ``` [GNU sed](http://www.gnu.org/software/sed/) (which you probably have) is even more versatile: ``` sed -r --in-place 's/a(.*)b/x\1y/g;' your_file ``` Here is a brief explanation of those options: > > **-i[SUFFIX], --in-place[=SUFFIX]** > edit files in place (makes backup if extension supplied) > > > **-r, --regexp-extended** > use extended regular expressions in the script. > > > The [FreeBSD](http://www.freebsd.org/cgi/man.cgi?query=sed&sektion=1), [NetBSD](https://man.netbsd.org/sed.1) and [OpenBSD](http://man.openbsd.org/sed.1) versions also supports these options. If you want to learn more about sed, [Cori](https://stackoverflow.com/questions/155934/what-gnu-linux-command-line-tool-would-i-use-for-performing-a-search-and-replace/155944#155944) has suggested [this tutorial](http://www.grymoire.com/Unix/Sed.html).
155,959
<p>The following code executes a simple insert command. If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown. Is there something else I should be doing to free up resources?</p> <pre><code>using (OleDbConnection conn = new OleDbConnection(connectionString)) using (OleDbCommand cmd = new OleDbCommand(commandText, conn)) { conn.Open(); cmd.ExecuteNonQuery(); } </code></pre>
[ { "answer_id": 155961, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "<p>The system resources exceeded error is not coming from the managed code, its coming from you killing your database (JET?)</p>\n<p>You are opening way too many connections, way too fast...</p>\n<p>Some tips:</p>\n<ul>\n<li>Avoid round trips by not opening a new connection for every single command, and perform the inserts using a single connection.</li>\n<li>Ensure that database connection pooling is working. (Not sure if that works with OLEDB connections.)</li>\n<li>Consider using a more optimized way to insert the data.</li>\n</ul>\n<p>Have you tried this?</p>\n<pre><code>using (OleDBConnection conn = new OleDBConnection(connstr))\n{\n while (IHaveData)\n {\n using (OldDBCommand cmd = new OldDBCommand())\n {\n cmd.Connection = conn;\n cmd.ExecuteScalar();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 156036, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 1, "selected": false, "text": "<p>I tested this code out with an Access 2007 database with no exceptions (I went as high as 13000 inserts).</p>\n\n<p>However, what I noticed is that it is terribly slow as you are creating a connection every time. If you put the \"using(connection)\" outside the loop, it goes much faster. </p>\n" }, { "answer_id": 156131, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 0, "selected": false, "text": "<p>In addition to the above (connecting to the database only once), I would also like to make sure you're closing and disposing of your connections. As most objects in c# are managed wrt memory, connections and streams don't have this luxury always, so if objects like this aren't disposed of, they are not guaranteed to be cleaned up. This has the added effect of leaving that connection open for the life of your program.</p>\n\n<p>Also, if possible, I'd look into using Transactions. I can't tell what you're using this code for, but OleDbTransactions are useful when inserting and updating many rows in a database.</p>\n" }, { "answer_id": 537505, "author": "Krucible", "author_id": 2835, "author_profile": "https://Stackoverflow.com/users/2835", "pm_score": 0, "selected": false, "text": "<p>I am not sure about the specifics but I have ran across a similar problem. We utilize an Access database with IIS to serve our clients. We do not have very many clients but there are alot of connections being opened and closed during a single session. After about a week of work, we recieve the same error and all connection attempts fail. To correct the problem, all we had to do was restart the worker processes. </p>\n\n<p>After some research, I found (of course) that Access does not perform well in this environment. Resources do not get released correctly and over time the executable will run out. To solve this problem, we are going to move to an Oracle database. If this does not fix the problem, I will keep you updated on my findings.</p>\n" }, { "answer_id": 21227708, "author": "jaymeht", "author_id": 1703129, "author_profile": "https://Stackoverflow.com/users/1703129", "pm_score": -1, "selected": false, "text": "<p>This could be occurring because you are not disposing the Connection and Command object created. Always Dispose the object at the end.</p>\n\n<pre><code>OledbCommand.Dispose();\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669/" ]
The following code executes a simple insert command. If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown. Is there something else I should be doing to free up resources? ``` using (OleDbConnection conn = new OleDbConnection(connectionString)) using (OleDbCommand cmd = new OleDbCommand(commandText, conn)) { conn.Open(); cmd.ExecuteNonQuery(); } ```
The system resources exceeded error is not coming from the managed code, its coming from you killing your database (JET?) You are opening way too many connections, way too fast... Some tips: * Avoid round trips by not opening a new connection for every single command, and perform the inserts using a single connection. * Ensure that database connection pooling is working. (Not sure if that works with OLEDB connections.) * Consider using a more optimized way to insert the data. Have you tried this? ``` using (OleDBConnection conn = new OleDBConnection(connstr)) { while (IHaveData) { using (OldDBCommand cmd = new OldDBCommand()) { cmd.Connection = conn; cmd.ExecuteScalar(); } } } ```
155,964
<p>I know about the <a href="http://developer.apple.com/library/mac/#documentation/UserExperience/Conceptual/AppleHIGuidelines/Intro/Intro.html" rel="noreferrer">HIG</a> (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).</p>
[ { "answer_id": 155966, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 6, "selected": false, "text": "<p>Golden Rule: If you <code>alloc</code> then you <code>release</code>!</p>\n\n<p>UPDATE: Unless you are using ARC</p>\n" }, { "answer_id": 156098, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 10, "selected": true, "text": "<p>There are a few things I have started to do that I do not think are standard:</p>\n\n<p>1) With the advent of properties, I no longer use \"_\" to prefix \"private\" class variables. After all, if a variable can be accessed by other classes shouldn't there be a property for it? I always disliked the \"_\" prefix for making code uglier, and now I can leave it out.</p>\n\n<p>2) Speaking of private things, I prefer to place private method definitions within the .m file in a class extension like so:</p>\n\n<pre><code>#import \"MyClass.h\"\n\n@interface MyClass ()\n- (void) someMethod;\n- (void) someOtherMethod;\n@end\n\n@implementation MyClass\n</code></pre>\n\n<p>Why clutter up the .h file with things outsiders should not care about? The empty () works for private categories in the .m file, and issues compile warnings if you do not implement the methods declared.</p>\n\n<p>3) I have taken to putting dealloc at the top of the .m file, just below the @synthesize directives. Shouldn't what you dealloc be at the top of the list of things you want to think about in a class? That is especially true in an environment like the iPhone.</p>\n\n<p>3.5) In table cells, make every element (including the cell itself) opaque for performance. That means setting the appropriate background color in everything.</p>\n\n<p>3.6) When using an NSURLConnection, as a rule you may well want to implement the delegate method:</p>\n\n<pre><code>- (NSCachedURLResponse *)connection:(NSURLConnection *)connection\n willCacheResponse:(NSCachedURLResponse *)cachedResponse\n{\n return nil;\n}\n</code></pre>\n\n<p>I find most web calls are very singular and it's more the exception than the rule you'll be wanting responses cached, especially for web service calls. Implementing the method as shown disables caching of responses.</p>\n\n<p>Also of interest, are some good iPhone specific tips from Joseph Mattiello (received in an iPhone mailing list). There are more, but these were the most generally useful I thought (note that a few bits have now been slightly edited from the original to include details offered in responses):</p>\n\n<p>4) Only use double precision if you have to, such as when working with CoreLocation. Make sure you end your constants in 'f' to make gcc store them as floats.</p>\n\n<pre><code>float val = someFloat * 2.2f;\n</code></pre>\n\n<p>This is mostly important when <code>someFloat</code> may actually be a double, you don't need the mixed-mode math, since you're losing precision in 'val' on storage. While floating-point numbers are supported in hardware on iPhones, it may still take more time to do double-precision arithmetic as opposed to single precision. References:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1622729/double-vs-float-on-the-iphone\">Double vs float on the iPhone</a></li>\n<li><a href=\"https://stackoverflow.com/questions/8854001/iphone-ipad-double-precision-math\">iPhone/iPad double precision math</a></li>\n</ul>\n\n<p>On the older phones supposedly calculations operate at the same speed but you can have more single precision components in registers than doubles, so for many calculations single precision will end up being faster.</p>\n\n<p>5) Set your properties as <code>nonatomic</code>. They're <code>atomic</code> by default and upon synthesis, semaphore code will be created to prevent multi-threading problems. 99% of you probably don't need to worry about this and the code is much less bloated and more memory-efficient when set to nonatomic.</p>\n\n<p>6) SQLite can be a very, very fast way to cache large data sets. A map application for instance can cache its tiles into SQLite files. The most expensive part is disk I/O. Avoid many small writes by sending <code>BEGIN;</code> and <code>COMMIT;</code> between large blocks. We use a 2 second timer for instance that resets on each new submit. When it expires, we send COMMIT; , which causes all your writes to go in one large chunk. SQLite stores transaction data to disk and doing this Begin/End wrapping avoids creation of many transaction files, grouping all of the transactions into one file.</p>\n\n<p>Also, SQL will block your GUI if it's on your main thread. If you have a very long query, It's a good idea to store your queries as static objects, and run your SQL on a separate thread. Make sure to wrap anything that modifies the database for query strings in <code>@synchronize() {}</code> blocks. For short queries just leave things on the main thread for easier convenience.</p>\n\n<p>More SQLite optimization tips are here, though the document appears out of date many of the points are probably still good;</p>\n\n<p><a href=\"http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html\" rel=\"nofollow noreferrer\">http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html</a></p>\n" }, { "answer_id": 156186, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 6, "selected": false, "text": "<p>@kendell</p>\n\n<p>Instead of:</p>\n\n<pre><code>@interface MyClass (private)\n- (void) someMethod\n- (void) someOtherMethod\n@end\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>@interface MyClass ()\n- (void) someMethod\n- (void) someOtherMethod\n@end\n</code></pre>\n\n<p>New in Objective-C 2.0.</p>\n\n<p>Class extensions are described in Apple's Objective-C 2.0 Reference.</p>\n\n<p><em>\"Class extensions allow you to declare additional required API for a class in locations other than within the primary class @interface block\"</em></p>\n\n<p>So they're part of the actual class - and NOT a (private) category in addition to the class. Subtle but important difference.</p>\n" }, { "answer_id": 156288, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 4, "selected": false, "text": "<p>Clean up in dealloc.</p>\n\n<p>This is one of the easiest things to forget - esp. when coding at 150mph. Always, always, always clean up your attributes/member variables in dealloc.</p>\n\n<p>I like to use Objc 2 attributes - <em>with</em> the new dot notation - so this makes the cleanup painless. Often as simple as:</p>\n\n<pre><code>- (void)dealloc\n{\n self.someAttribute = NULL;\n [super dealloc];\n}\n</code></pre>\n\n<p>This will take care of the release for you and set the attribute to NULL (which I consider defensive programming - in case another method further down in dealloc accesses the member variable again - rare but <em>could</em> happen).</p>\n\n<p>With GC turned on in 10.5, this isn't needed so much any more - but you might still need to clean up others resources you create, you can do that in the finalize method instead.</p>\n" }, { "answer_id": 156295, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 7, "selected": false, "text": "<p>This is subtle one but handy one. If you're passing yourself as a delegate to another object, reset that object's delegate before you <code>dealloc</code>.</p>\n\n<pre><code>- (void)dealloc\n{\nself.someObject.delegate = NULL;\nself.someObject = NULL;\n//\n[super dealloc];\n}\n</code></pre>\n\n<p>By doing this you're ensuring that no more delegate methods will get sent. As you're about to <code>dealloc</code> and disappear into the ether you want to make sure that nothing can send you any more messages by accident. Remember self.someObject could be retained by another object (it could be a singleton or on the autorelease pool or whatever) and until you tell it \"stop sending me messages!\", it thinks your just-about-to-be-dealloced object is fair game.</p>\n\n<p>Getting into this habit will save you from lots of weird crashes that are a pain to debug.</p>\n\n<p>The same principal applies to Key Value Observation, and NSNotifications too.</p>\n\n<p>Edit:</p>\n\n<p>Even more defensive, change:</p>\n\n<pre><code>self.someObject.delegate = NULL;\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>if (self.someObject.delegate == self)\n self.someObject.delegate = NULL;\n</code></pre>\n" }, { "answer_id": 156317, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 5, "selected": false, "text": "<p>Try to avoid what I have now decided to call Newbiecategoryaholism. When newcomers to Objective-C discover categories they often go hog wild, adding useful little categories to every class in existence (<em>\"What? i can add a method to convert a number to roman numerals to NSNumber rock on!\"</em>).</p>\n\n<p>Don't do this.</p>\n\n<p>Your code will be more portable and easier to understand with out dozens of little category methods sprinkled on top of two dozen foundation classes.</p>\n\n<p>Most of the time when you really think you need a category method to help streamline some code you'll find you never end up reusing the method.</p>\n\n<p>There are other dangers too, unless you're namespacing your category methods (and who besides the utterly insane ddribin is?) there is a chance that Apple, or a plugin, or something else running in your address space will also define the same category method with the same name with a slightly different side effect....</p>\n\n<p>OK. Now that you've been warned, ignore the \"don't do this part\". But exercise extreme restraint.</p>\n" }, { "answer_id": 156343, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 4, "selected": false, "text": "<p>Also, semi-related topic (with room for more responses!):</p>\n\n<p><a href=\"https://stackoverflow.com/questions/146297/what-are-those-little-xcode-tips-tricks-you-wish-you-knew-about-2-years-ago\">What are those little Xcode tips &amp; tricks you wish you knew about 2 years ago?</a>.</p>\n" }, { "answer_id": 156652, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 6, "selected": false, "text": "<p>Write unit tests. You can test a <strong>lot</strong> of things in Cocoa that might be harder in other frameworks. For example, with UI code, you can generally verify that things are connected as they should be and trust that they'll work when used. And you can set up state &amp; invoke delegate methods easily to test them.</p>\n\n<p>You also don't have public vs. protected vs. private method visibility getting in the way of writing tests for your internals.</p>\n" }, { "answer_id": 156665, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 5, "selected": false, "text": "<p>Resist subclassing the world. In Cocoa a lot is done through delegation and use of the underlying runtime that in other frameworks is done through subclassing.</p>\n\n<p>For example, in Java you use instances of anonymous <code>*Listener</code> subclasses a lot and in .NET you use your <code>EventArgs</code> subclasses a lot. In Cocoa, you don't do either — the target-action is used instead.</p>\n" }, { "answer_id": 158274, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 6, "selected": false, "text": "<p>Don't write Objective-C as if it were Java/C#/C++/etc.</p>\n\n<p>I once saw a team used to writing Java EE web applications try to write a Cocoa desktop application. As if it was a Java EE web application. There was a lot of AbstractFooFactory and FooFactory and IFoo and Foo flying around when all they really needed was a Foo class and possibly a Fooable protocol.</p>\n\n<p>Part of ensuring you don't do this is truly understanding the differences in the language. For example, you don't need the abstract factory and factory classes above because Objective-C class methods are dispatched just as dynamically as instance methods, and can be overridden in subclasses.</p>\n" }, { "answer_id": 158304, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 7, "selected": false, "text": "<p>Use standard Cocoa naming and formatting conventions and terminology rather than whatever you're used to from another environment. There <strong>are</strong> lots of Cocoa developers out there, and when another one of them starts working with your code, it'll be much more approachable if it looks and feels similar to other Cocoa code.</p>\n\n<p>Examples of what to do and what not to do:</p>\n\n<ul>\n<li>Don't declare <code>id m_something;</code> in an object's interface and call it a <em>member variable</em> or <em>field</em>; use <code>something</code> or <code>_something</code> for its name and call it an <em>instance variable</em>.</li>\n<li>Don't name a getter <code>-getSomething</code>; the proper Cocoa name is just <code>-something</code>.</li>\n<li>Don't name a setter <code>-something:</code>; it should be <code>-setSomething:</code></li>\n<li>The method name is interspersed with the arguments and includes colons; it's <code>-[NSObject performSelector:withObject:]</code>, not <code>NSObject::performSelector</code>.</li>\n<li>Use inter-caps (CamelCase) in method names, parameters, variables, class names, etc. rather than underbars (underscores).</li>\n<li>Class names start with an upper-case letter, variable and method names with lower-case.</li>\n</ul>\n\n<p>Whatever else you do, <strong>don't</strong> use Win16/Win32-style Hungarian notation. Even Microsoft gave up on that with the move to the .NET platform.</p>\n" }, { "answer_id": 158453, "author": "mj1531", "author_id": 17991, "author_profile": "https://Stackoverflow.com/users/17991", "pm_score": 3, "selected": false, "text": "<p>I know I overlooked this when first getting into Cocoa programming.</p>\n\n<p>Make sure you understand memory management responsibilities regarding NIB files. You are responsible for releasing the top-level objects in any NIB file you load. Read <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/chapter_3_section_6.html#//apple_ref/doc/uid/10000051i-CH4-DontLinkElementID_12\" rel=\"nofollow noreferrer\">Apple's Documentation</a> on the subject.</p>\n" }, { "answer_id": 158532, "author": "mj1531", "author_id": 17991, "author_profile": "https://Stackoverflow.com/users/17991", "pm_score": 6, "selected": false, "text": "<p>Make sure you bookmark the <a href=\"http://developer.apple.com/technotes/tn2004/tn2124.html\" rel=\"nofollow noreferrer\">Debugging Magic</a> page. This should be your first stop when banging your head against a wall while trying to find the source of a Cocoa bug.</p>\n\n<p>For example, it will tell you how to find the method where you first allocated memory that later is causing crashes (like during app termination).</p>\n" }, { "answer_id": 158627, "author": "mj1531", "author_id": 17991, "author_profile": "https://Stackoverflow.com/users/17991", "pm_score": 5, "selected": false, "text": "<p>If you're using Leopard (Mac OS X 10.5) or later, you can use the Instruments application to find and track memory leaks. After building your program in Xcode, select Run > Start with Performance Tool > Leaks.</p>\n\n<p>Even if your app doesn't show any leaks, you may be keeping objects around too long. In Instruments, you can use the ObjectAlloc instrument for this. Select the ObjectAlloc instrument in your Instruments document, and bring up the instrument's detail (if it isn't already showing) by choosing View > Detail (it should have a check mark next to it). Under \"Allocation Lifespan\" in the ObjectAlloc detail, make sure you choose the radio button next to \"Created &amp; Still Living\".</p>\n\n<p>Now whenever you stop recording your application, selecting the ObjectAlloc tool will show you how many references there are to each still-living object in your application in the \"# Net\" column. Make sure you not only look at your own classes, but also the classes of your NIB files' top-level objects. For example, if you have no windows on the screen, and you see references to a still-living NSWindow, you may have not released it in your code.</p>\n" }, { "answer_id": 158652, "author": "mj1531", "author_id": 17991, "author_profile": "https://Stackoverflow.com/users/17991", "pm_score": 4, "selected": false, "text": "<p>Don't forget that NSWindowController and NSViewController will release the top-level objects of the NIB files they govern.</p>\n\n<p>If you manually load a NIB file, you are responsible for releasing that NIB's top-level objects when you are done with them.</p>\n" }, { "answer_id": 167495, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "<h2>IBOutlets</h2>\n\n<p>Historically, memory management of outlets has been poor.\nCurrent best practice is to declare outlets as properties:</p>\n\n<pre><code>@interface MyClass :NSObject {\n NSTextField *textField;\n}\n@property (nonatomic, retain) IBOutlet NSTextField *textField;\n@end\n</code></pre>\n\n<p>Using properties makes the memory management semantics clear; it also provides a consistent pattern if you use instance variable synthesis.</p>\n" }, { "answer_id": 167536, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "<h2>Declared Properties</h2>\n\n<p>You should typically use the Objective-C 2.0 Declared Properties feature for all your properties. If they are not public, add them in a class extension. Using declared properties makes the memory management semantics immediately clear, and makes it easier for you to check your dealloc method -- if you group your property declarations together you can quickly scan them and compare with the implementation of your dealloc method.</p>\n\n<p>You should think hard before not marking properties as 'nonatomic'. As <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/chapter_1_section_1.html\" rel=\"noreferrer\">The Objective C Programming Language Guide</a> notes, properties are atomic by default, and incur considerable overhead. Moreover, simply making all your properties atomic does not make your application thread-safe. Also note, of course, that if you don't specify 'nonatomic' and implement your own accessor methods (rather than synthesising them), you must implement them in an atomic fashion.</p>\n" }, { "answer_id": 169783, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "<h2>Use the LLVM/Clang Static Analyzer</h2>\n\n<p>NOTE: Under Xcode 4 this is now built into the IDE.</p>\n\n<p>You use the <a href=\"http://clang.llvm.org/StaticAnalysis.html\" rel=\"nofollow noreferrer\">Clang Static Analyzer</a> to -- unsurprisingly -- analyse your C and Objective-C code (no C++ yet) on Mac OS X 10.5. It's trivial to install and use:</p>\n\n<ol>\n<li>Download the latest version from <a href=\"http://clang.llvm.org/StaticAnalysisUsage.html\" rel=\"nofollow noreferrer\">this page</a>.</li>\n<li>From the command-line, <code>cd</code> to your project directory.</li>\n<li>Execute <code>scan-build -k -V xcodebuild</code>.</li>\n</ol>\n\n<p>(There are some additional constraints etc., in particular you should analyze a project in its \"Debug\" configuration -- see <a href=\"http://clang.llvm.org/StaticAnalysisUsage.html\" rel=\"nofollow noreferrer\">http://clang.llvm.org/StaticAnalysisUsage.html</a> for details -- the but that's more-or-less what it boils down to.)</p>\n\n<p>The analyser then produces a set of web pages for you that shows likely memory management and other basic problems that the compiler is unable to detect.</p>\n" }, { "answer_id": 175118, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "<h2>Don't use unknown strings as format strings</h2>\n\n<p>When methods or functions take a format string argument, you should make sure that you have control over the content of the format string.</p>\n\n<p>For example, when logging strings, it is tempting to pass the string variable as the sole argument to <code>NSLog</code>:</p>\n\n<pre><code> NSString *aString = // get a string from somewhere;\n NSLog(aString);\n</code></pre>\n\n<p>The problem with this is that the string may contain characters that are interpreted as format strings. This can lead to erroneous output, crashes, and security problems. Instead, you should substitute the string variable into a format string:</p>\n\n<pre><code> NSLog(@\"%@\", aString);\n</code></pre>\n" }, { "answer_id": 175134, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "<h2>Sort strings as the user wants</h2>\n\n<p>When you sort strings to present to the user, you should not use the simple <code>compare:</code> method. Instead, you should always use localized comparison methods such as <code>localizedCompare:</code> or <code>localizedCaseInsensitiveCompare:</code>.</p>\n\n<p>For more details, see <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/SearchingStrings.html\" rel=\"nofollow noreferrer\">Searching, Comparing, and Sorting Strings</a>.</p>\n" }, { "answer_id": 175874, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": false, "text": "<h2>Avoid autorelease</h2>\n\n<p>Since you typically(1) don't have direct control over their lifetime, autoreleased objects can persist for a comparatively long time and unnecessarily increase the memory footprint of your application. Whilst on the desktop this may be of little consequence, on more constrained platforms this can be a significant issue. On all platforms, therefore, and especially on more constrained platforms, it is considered best practice to avoid using methods that would lead to autoreleased objects and instead you are encouraged to use the alloc/init pattern.</p>\n\n<p>Thus, rather than:</p>\n\n<pre><code>aVariable = [AClass convenienceMethod];\n</code></pre>\n\n<p>where able, you should instead use:</p>\n\n<pre><code>aVariable = [[AClass alloc] init];\n// do things with aVariable\n[aVariable release];\n</code></pre>\n\n<p>When you're writing your own methods that return a newly-created object, you can take advantage of <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html#//apple_ref/doc/uid/20000994\" rel=\"noreferrer\">Cocoa's naming convention</a> to flag to the receiver that it must be released by prepending the method name with \"new\".</p>\n\n<p>Thus, instead of:</p>\n\n<pre><code>- (MyClass *)convenienceMethod {\n MyClass *instance = [[[self alloc] init] autorelease];\n // configure instance\n return instance;\n}\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>- (MyClass *)newInstance {\n MyClass *instance = [[self alloc] init];\n // configure instance\n return instance;\n}\n</code></pre>\n\n<p>Since the method name begins with \"new\", consumers of your API know that they're responsible for releasing the received object (see, for example, <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSObjectController_Class/Reference/Reference.html#//apple_ref/doc/uid/20002044-BBCEAICF\" rel=\"noreferrer\">NSObjectController's <code>newObject</code> method</a>).</p>\n\n<p>(1) You can take control by using your own local autorelease pools. For more on this, see <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Concepts/AutoreleasePools.html#//apple_ref/doc/uid/20000047\" rel=\"noreferrer\">Autorelease Pools</a>.</p>\n" }, { "answer_id": 195969, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "<h2>Think about nil values</h2>\n\n<p>As <a href=\"https://stackoverflow.com/questions/156395/sending-a-message-to-nil\">this question</a> notes, messages to <code>nil</code> are valid in Objective-C. Whilst this is frequently an advantage -- leading to cleaner and more natural code -- the feature can occasionally lead to peculiar and difficult-to-track-down bugs if you get a <code>nil</code> value when you weren't expecting it. </p>\n" }, { "answer_id": 297307, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 6, "selected": false, "text": "<p>Some of these have already been mentioned, but here's what I can think of off the top of my head:</p>\n\n<ul>\n<li><strong>Follow KVO naming rules.</strong> Even if you don't use KVO now, in my experience often times it's still beneficial in the future. And if you are using KVO or bindings, you need to know things are going work the way they are supposed to. This covers not just accessor methods and instance variables, but to-many relationships, validation, auto-notifying dependent keys, and so on.</li>\n<li><strong>Put private methods in a category.</strong> Not just the interface, but the implementation as well. It's good to have some distance conceptually between private and non-private methods. I include everything in my .m file.</li>\n<li><strong>Put background thread methods in a category.</strong> Same as above. I've found it's good to keep a clear conceptual barrier when you're thinking about what's on the main thread and what's not.</li>\n<li><strong>Use <code>#pragma mark [section]</code>.</strong> Usually I group by my own methods, each subclass's overrides, and any information or formal protocols. This makes it a lot easier to jump to exactly what I'm looking for. On the same topic, group similar methods (like a table view's delegate methods) together, don't just stick them anywhere.</li>\n<li><strong>Prefix private methods &amp; ivars with _.</strong> I like the way it looks, and I'm less likely to use an ivar when I mean a property by accident.</li>\n<li><strong>Don't use mutator methods / properties in init &amp; dealloc.</strong> I've never had anything bad happen because of it, but I can see the logic if you change the method to do something that depends on the state of your object.</li>\n<li><strong>Put IBOutlets in properties.</strong> I actually just read this one here, but I'm going to start doing it. Regardless of any memory benefits, it seems better stylistically (at least to me).</li>\n<li><strong>Avoid writing code you don't absolutely need.</strong> This really covers a lot of things, like making ivars when a <code>#define</code> will do, or caching an array instead of sorting it each time the data is needed. There's a lot I could say about this, but the bottom line is don't write code until you need it, or the profiler tells you to. It makes things a lot easier to maintain in the long run.</li>\n<li><strong>Finish what you start.</strong> Having a lot of half-finished, buggy code is the fastest way to kill a project dead. If you need a stub method that's fine, just indicate it by putting <code>NSLog( @\"stub\" )</code> inside, or however you want to keep track of things.</li>\n</ul>\n" }, { "answer_id": 372381, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 4, "selected": false, "text": "<p>All these comments are great, but I'm really surprised nobody mentioned <a href=\"http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml\" rel=\"nofollow noreferrer\">Google's Objective-C Style Guide</a> that was published a while back. I think they have done a very thorough job.</p>\n" }, { "answer_id": 837006, "author": "NikWest", "author_id": 103149, "author_profile": "https://Stackoverflow.com/users/103149", "pm_score": 5, "selected": false, "text": "<p>Use NSAssert and friends.\nI use nil as valid object all the time ... especially sending messages to nil is perfectly valid in Obj-C. \nHowever if I really want to make sure about the state of a variable, I use NSAssert and NSParameterAssert, which helps to track down problems easily.</p>\n" }, { "answer_id": 890625, "author": "bbrown", "author_id": 20595, "author_profile": "https://Stackoverflow.com/users/20595", "pm_score": 3, "selected": false, "text": "<p>The Apple-provided samples I saw treated the App delegate as a global data store, a data manager of sorts. That's wrongheaded. Create a singleton and maybe instantiate it in the App delegate, but stay away from using the App delegate as anything more than application-level event handling. I heartily second the recommendations in <a href=\"http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html\" rel=\"nofollow noreferrer\">this blog entry</a>. <a href=\"https://stackoverflow.com/questions/338734/iphone-proper-usage-of-application-delegate\">This thread</a> tipped me off.</p>\n" }, { "answer_id": 1585606, "author": "oefe", "author_id": 49793, "author_profile": "https://Stackoverflow.com/users/49793", "pm_score": 3, "selected": false, "text": "<p>Turn on all GCC warnings, then turn off those that are regularly caused by Apple's headers to reduce noise. </p>\n\n<p>Also run Clang static analysis frequently; you can enable it for all builds via the \"Run Static Analyzer\" build setting.</p>\n\n<p>Write unit tests and run them with each build.</p>\n" }, { "answer_id": 3231437, "author": "iwasrobbed", "author_id": 308315, "author_profile": "https://Stackoverflow.com/users/308315", "pm_score": 4, "selected": false, "text": "<p>One rather obvious one for a beginner to use: utilize Xcode's auto-indentation feature for your code. Even if you are copy/pasting from another source, once you have pasted the code, you can select the entire block of code, right click on it, and then choose the option to re-indent everything within that block. </p>\n\n<p>Xcode will actually parse through that section and indent it based on brackets, loops, etc. It's a lot more efficient than hitting the space bar or tab key for each and every line.</p>\n" }, { "answer_id": 3583204, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 5, "selected": false, "text": "<p>Simple but oft-forgotten one. According to spec:</p>\n\n<blockquote>\n <p>In general, methods in different\n classes that have the same selector\n (the same name) must also share the\n same return and argument types. This\n constraint is imposed by the compiler\n to allow dynamic binding.</p>\n</blockquote>\n\n<p>in which case all the same named selectors, <strong>even if in different classes</strong>, will be regarded as to have identical return/argument types. Here is a simple example.</p>\n\n<pre><code>@interface FooInt:NSObject{}\n-(int) print;\n@end\n\n@implementation FooInt\n-(int) print{\n return 5;\n}\n@end\n\n@interface FooFloat:NSObject{}\n-(float) print;\n@end\n\n@implementation FooFloat\n-(float) print{\n return 3.3;\n}\n@end\n\nint main (int argc, const char * argv[]) {\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; \n id f1=[[FooFloat alloc]init];\n //prints 0, runtime considers [f1 print] to return int, as f1's type is \"id\" and FooInt precedes FooBar\n NSLog(@\"%f\",[f1 print]);\n\n FooFloat* f2=[[FooFloat alloc]init];\n //prints 3.3 expectedly as the static type is FooFloat\n NSLog(@\"%f\",[f2 print]);\n\n [f1 release];\n [f2 release]\n [pool drain];\n\n return 0;\n} \n</code></pre>\n" }, { "answer_id": 5476751, "author": "eonil", "author_id": 246776, "author_profile": "https://Stackoverflow.com/users/246776", "pm_score": 3, "selected": false, "text": "<p>Be more <strong>functional</strong>.</p>\n\n<p>Objective-C is object-oriented language, but Cocoa framework functional-style aware, and is designed functional style in many cases.</p>\n\n<ol>\n<li><p>There is separation of mutability. Use <em>immutable</em> classes as primary, and mutable object as secondary. For instance, use NSArray primarily, and use NSMutableArray only when you need. </p></li>\n<li><p>There is pure functions. Not so many, buy many of framework APIs are designed like pure function. Look at functions such as <code>CGRectMake()</code> or <code>CGAffineTransformMake()</code>. Obviously pointer form looks more efficient. However indirect argument with pointers can't offer side-effect-free. Design structures purely as much as possible. \nSeparate even state objects. Use <code>-copy</code> instead of <code>-retain</code> when passing a value to other object. Because shared state can influence mutation to value in other object silently. So can't be side-effect-free. If you have a value from external from object, copy it. So it's also important designing shared state as minimal as possible. </p></li>\n</ol>\n\n<p>However don't be afraid of using impure functions too. </p>\n\n<ol>\n<li><p>There is lazy evaluation. See something like <code>-[UIViewController view]</code> property. The view won't be created when the object is created. It'll be created when caller reading <code>view</code> property at first time. <code>UIImage</code> will not be loaded until it actually being drawn. There are many implementation like this design. This kind of designs are very helpful for resource management, but if you don't know the concept of lazy evaluation, it's not easy to understand behavior of them. </p></li>\n<li><p>There is closure. Use C-blocks as much as possible. This will simplify your life greatly. But read once more about block-memory-management before using it.</p></li>\n<li><p>There is semi-auto GC. NSAutoreleasePool. Use <code>-autorelease</code> primary. Use manual <code>-retain/-release</code> secondary when you really need. (ex: memory optimization, explicit resource deletion)</p></li>\n</ol>\n" }, { "answer_id": 6977572, "author": "Tuan Nguyen", "author_id": 504257, "author_profile": "https://Stackoverflow.com/users/504257", "pm_score": 2, "selected": false, "text": "<p>Only release a <em>property</em> in <em>dealloc</em> method. If you want to release memory that the <em>property</em> is holding, just set it as nil:</p>\n\n<pre><code>self.&lt;property&gt; = nil;\n</code></pre>\n" }, { "answer_id": 7816085, "author": "Sulthan", "author_id": 669586, "author_profile": "https://Stackoverflow.com/users/669586", "pm_score": 3, "selected": false, "text": "<p><strong>Variables and properties</strong></p>\n\n<p>1/ Keeping your headers clean, hiding implementation<br>\nDon't include instance variables in your header. Private variables put into class continuation as properties. Public variables declare as public properties in your header.\nIf it should be only read, declare it as readonly and overwrite it as readwrite in class continutation.\nBasically I am not using variables at all, only properties.</p>\n\n<p>2/ Give your properties a non-default variable name, example:</p>\n\n<pre><code>\n@synthesize property = property_;\n</code></pre>\n\n<p>Reason 1: You will catch errors caused by forgetting \"self.\" when assigning the property.\nReason 2: From my experiments, Leak Analyzer in Instruments has problems to detect leaking property with default name.</p>\n\n<p>3/ Never use retain or release directly on properties (or only in very exceptional situations). In your dealloc just assign them a nil. Retain properties are meant to handle retain/release by themselves. You never know if a setter is not, for example, adding or removing observers. You should use the variable directly only inside its setter and getter.</p>\n\n<p><strong>Views</strong></p>\n\n<p>1/ Put every view definition into a xib, if you can (the exception is usually dynamic content and layer settings). It saves time (it's easier than writing code), it's easy to change and it keeps your code clean.</p>\n\n<p>2/ Don't try to optimize views by decreasing the number of views. Don't create UIImageView in your code instead of xib just because you want to add subviews into it. Use UIImageView as background instead. The view framework can handle hundreds of views without problems.</p>\n\n<p>3/ IBOutlets don't have to be always retained (or strong). Note that most of your IBOutlets are part of your view hierarchy and thus implicitly retained.</p>\n\n<p>4/ Release all IBOutlets in viewDidUnload</p>\n\n<p>5/ Call viewDidUnload from your dealloc method. It is not implicitly called.</p>\n\n<p><strong>Memory</strong></p>\n\n<p>1/ Autorelease objects when you create them. Many bugs are caused by moving your release call into one if-else branch or after a return statement. Release instead of autorelease should be used only in exceptional situations - e.g. when you are waiting for a runloop and you don't want your object to be autoreleased too early.</p>\n\n<p>2/ Even if you are using Authomatic Reference Counting, you have to understand perfectly how retain-release methods work. Using retain-release manually is not more complicated than ARC, in both cases you have to thing about leaks and retain-cycles.\nConsider using retain-release manually on big projects or complicated object hierarchies.</p>\n\n<p><strong>Comments</strong></p>\n\n<p>1/ Make your code autodocumented.\nEvery variable name and method name should tell what it is doing. If code is written correctly (you need a lot of practice in this), you won't need any code comments (not the same as documentation comments). Algorithms can be complicated but the code should be always simple.</p>\n\n<p>2/ Sometimes, you'll need a comment. Usually to describe a non apparent code behavior or hack. If you feel you have to write a comment, first try to rewrite the code to be simpler and without the need of comments. </p>\n\n<p><strong>Indentation</strong></p>\n\n<p>1/ Don't increase indentation too much.\nMost of your method code should be indented on the method level. Nested blocks (if, for etc.) decrease readability. If you have three nested blocks, you should try to put the inner blocks into a separate method. Four or more nested blocks should be never used.\nIf most of your method code is inside of an if, negate the if condition, example:</p>\n\n<pre><code>\nif (self) {\n //... long initialization code ...\n}\n\nreturn self;\n\n</code></pre>\n\n<pre><code>\nif (!self) {\n return nil;\n}\n\n//... long initialization code ...\n\nreturn self;\n\n</code></pre>\n\n<p><strong>Understand C code, mainly C structs</strong></p>\n\n<p>Note that Obj-C is only a light OOP layer over C language. You should understand how basic code structures in C work (enums, structs, arrays, pointers etc).\nExample:</p>\n\n<pre><code>\nview.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height + 20);\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>\nCGRect frame = view.frame;\nframe.size.height += 20;\nview.frame = frame;\n</code></pre>\n\n<p><strong>And many more</strong></p>\n\n<p>Mantain your own coding standards document and update it often. Try to learn from your bugs. Understand why a bug was created and try to avoid it using coding standards.</p>\n\n<p>Our coding standards have currently about 20 pages, a mix of Java Coding Standards, Google Obj-C/C++ Standards and our own addings. Document your code, use standard standard indentation, white spaces and blank lines on the right places etc.</p>\n" }, { "answer_id": 10314854, "author": "Nirmit Pathak", "author_id": 1302622, "author_profile": "https://Stackoverflow.com/users/1302622", "pm_score": 0, "selected": false, "text": "<pre><code>#import \"MyClass.h\"\n\n@interface MyClass ()\n- (void) someMethod;\n- (void) someOtherMethod;\n@end\n\n@implementation MyClass\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21804/" ]
I know about the [HIG](http://developer.apple.com/library/mac/#documentation/UserExperience/Conceptual/AppleHIGuidelines/Intro/Intro.html) (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).
There are a few things I have started to do that I do not think are standard: 1) With the advent of properties, I no longer use "\_" to prefix "private" class variables. After all, if a variable can be accessed by other classes shouldn't there be a property for it? I always disliked the "\_" prefix for making code uglier, and now I can leave it out. 2) Speaking of private things, I prefer to place private method definitions within the .m file in a class extension like so: ``` #import "MyClass.h" @interface MyClass () - (void) someMethod; - (void) someOtherMethod; @end @implementation MyClass ``` Why clutter up the .h file with things outsiders should not care about? The empty () works for private categories in the .m file, and issues compile warnings if you do not implement the methods declared. 3) I have taken to putting dealloc at the top of the .m file, just below the @synthesize directives. Shouldn't what you dealloc be at the top of the list of things you want to think about in a class? That is especially true in an environment like the iPhone. 3.5) In table cells, make every element (including the cell itself) opaque for performance. That means setting the appropriate background color in everything. 3.6) When using an NSURLConnection, as a rule you may well want to implement the delegate method: ``` - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return nil; } ``` I find most web calls are very singular and it's more the exception than the rule you'll be wanting responses cached, especially for web service calls. Implementing the method as shown disables caching of responses. Also of interest, are some good iPhone specific tips from Joseph Mattiello (received in an iPhone mailing list). There are more, but these were the most generally useful I thought (note that a few bits have now been slightly edited from the original to include details offered in responses): 4) Only use double precision if you have to, such as when working with CoreLocation. Make sure you end your constants in 'f' to make gcc store them as floats. ``` float val = someFloat * 2.2f; ``` This is mostly important when `someFloat` may actually be a double, you don't need the mixed-mode math, since you're losing precision in 'val' on storage. While floating-point numbers are supported in hardware on iPhones, it may still take more time to do double-precision arithmetic as opposed to single precision. References: * [Double vs float on the iPhone](https://stackoverflow.com/questions/1622729/double-vs-float-on-the-iphone) * [iPhone/iPad double precision math](https://stackoverflow.com/questions/8854001/iphone-ipad-double-precision-math) On the older phones supposedly calculations operate at the same speed but you can have more single precision components in registers than doubles, so for many calculations single precision will end up being faster. 5) Set your properties as `nonatomic`. They're `atomic` by default and upon synthesis, semaphore code will be created to prevent multi-threading problems. 99% of you probably don't need to worry about this and the code is much less bloated and more memory-efficient when set to nonatomic. 6) SQLite can be a very, very fast way to cache large data sets. A map application for instance can cache its tiles into SQLite files. The most expensive part is disk I/O. Avoid many small writes by sending `BEGIN;` and `COMMIT;` between large blocks. We use a 2 second timer for instance that resets on each new submit. When it expires, we send COMMIT; , which causes all your writes to go in one large chunk. SQLite stores transaction data to disk and doing this Begin/End wrapping avoids creation of many transaction files, grouping all of the transactions into one file. Also, SQL will block your GUI if it's on your main thread. If you have a very long query, It's a good idea to store your queries as static objects, and run your SQL on a separate thread. Make sure to wrap anything that modifies the database for query strings in `@synchronize() {}` blocks. For short queries just leave things on the main thread for easier convenience. More SQLite optimization tips are here, though the document appears out of date many of the points are probably still good; <http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html>
155,977
<p>I have the following markup, and I want to make the <code>All</code> radio button checked.</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;input type="radio" value="All" name="Foo"/&gt;All&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="New" name="Foo"/&gt;New&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="Removed" name="Foo"/&gt;Removed&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="Updated" name="Foo"/&gt;Updated&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I'd like to match via attribute, but I need to match on 2 attributes, <code>@name='Foo'</code> and <code>@value='All'</code>.</p> <p>Something like this:</p> <pre><code>$("input[@name='Foo' @value='all']").attr('checked','checked'); </code></pre> <p>Can someone show how this can be done?</p>
[ { "answer_id": 156027, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 7, "selected": true, "text": "<p>The following HTML file shows how you can do this:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type=\"text/javascript\" src=\"jquery-1.2.6.pack.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"input[name='Foo'][value='All']\").attr('checked','checked');\n event.preventDefault();\n });\n });\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;input type=\"radio\" value=\"All\" name=\"Foo\" /&gt;All&lt;/li&gt;\n &lt;li&gt;&lt;input type=\"radio\" value=\"New\" name=\"Foo\" /&gt;New&lt;/li&gt;\n &lt;li&gt;&lt;input type=\"radio\" value=\"Removed\" name=\"Foo\" /&gt;Removed&lt;/li&gt;\n &lt;li&gt;&lt;input type=\"radio\" value=\"Updated\" name=\"Foo\" /&gt;Updated&lt;/li&gt;\n &lt;/ul&gt;\n &lt;a href=\"\" &gt;Click here&lt;/a&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>When you click on the link, the desired radio button is selected. The important line is the one setting the <code>checked</code> attribute.</p>\n" }, { "answer_id": 771618, "author": "easel", "author_id": 16706, "author_profile": "https://Stackoverflow.com/users/16706", "pm_score": 4, "selected": false, "text": "<p>I was beating my head against a wall similar to this and just want to point out that in jQuery 1.3 the syntax used in the accepted answer is the ONLY syntax that will work. The questioner uses the @ syntax for the expression which does not work at all in jQuery. Hopefully this helps the next guy to come across this question via Google =p</p>\n\n<p>To be clear, you have to use </p>\n\n<pre><code>jQuery('input[name=field1][val=checked]') \n</code></pre>\n\n<p>and not </p>\n\n<pre><code>jQuery('input[@name=field1][@val=checked]')\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410357/" ]
I have the following markup, and I want to make the `All` radio button checked. ``` <ul> <li><input type="radio" value="All" name="Foo"/>All</li> <li><input type="radio" value="New" name="Foo"/>New</li> <li><input type="radio" value="Removed" name="Foo"/>Removed</li> <li><input type="radio" value="Updated" name="Foo"/>Updated</li> </ul> ``` I'd like to match via attribute, but I need to match on 2 attributes, `@name='Foo'` and `@value='All'`. Something like this: ``` $("input[@name='Foo' @value='all']").attr('checked','checked'); ``` Can someone show how this can be done?
The following HTML file shows how you can do this: ``` <html> <head> <script type="text/javascript" src="jquery-1.2.6.pack.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(event){ $("input[name='Foo'][value='All']").attr('checked','checked'); event.preventDefault(); }); }); </script> </head> <body> <ul> <li><input type="radio" value="All" name="Foo" />All</li> <li><input type="radio" value="New" name="Foo" />New</li> <li><input type="radio" value="Removed" name="Foo" />Removed</li> <li><input type="radio" value="Updated" name="Foo" />Updated</li> </ul> <a href="" >Click here</a> </body> </html> ``` When you click on the link, the desired radio button is selected. The important line is the one setting the `checked` attribute.
155,996
<p>I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box.</p> <p>The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form:</p> <pre><code>MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) </code></pre> <p>Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property.</p> <p>Any ideas?</p>
[ { "answer_id": 156039, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 2, "selected": false, "text": "<p>Remove the <code>MessageBoxOptions.DefaultDesktopOnly</code> parameter and it will work correctly.</p>\n\n<p><code>DefaultDesktopOnly</code> specifies that \"<strong>The message box is displayed on the active desktop</strong>\" which causes the focus loss.</p>\n" }, { "answer_id": 156040, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": "<p>Remove the last parameter, <code>MessageBoxOptions.DefaultDesktopOnly</code>. </p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxoptions(VS.80).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>DefaultDesktopOnly will cause the\n application that raised the MessageBox\n to lose focus. The MessageBox that is\n displayed will not use visual styles.\n For more information, see Rendering\n Controls with Visual Styles.</p>\n</blockquote>\n\n<p>The last parameter allows communication of a background Windows Service with the active desktop through means of csrss.exe! See Bart de Smet's <a href=\"http://bartdesmet.net/blogs/bart/archive/2004/12/03/488.aspx\" rel=\"noreferrer\">blog post</a> for details.</p>\n" }, { "answer_id": 54539467, "author": "ccampj", "author_id": 333086, "author_profile": "https://Stackoverflow.com/users/333086", "pm_score": 1, "selected": false, "text": "<p>These answers are correct, but I wanted to add another point. I came across this question while working with someone else's code. A simple message box was causing the front most window to move to the back:</p>\n\n<p>MessageBox.Show(\"Hello\").</p>\n\n<p>Turns out, there was a BindingSource.Endedit command before the MessageBox. The BindingSource wasn't connected to any controls yet, but it caused the window to change z-positions. </p>\n\n<p>I am only including this note since my search brought me to this question and I thought it might be helpful to someone else.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10224/" ]
I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box. The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form: ``` MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) ``` Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property. Any ideas?
Remove the last parameter, `MessageBoxOptions.DefaultDesktopOnly`. From [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxoptions(VS.80).aspx): > > DefaultDesktopOnly will cause the > application that raised the MessageBox > to lose focus. The MessageBox that is > displayed will not use visual styles. > For more information, see Rendering > Controls with Visual Styles. > > > The last parameter allows communication of a background Windows Service with the active desktop through means of csrss.exe! See Bart de Smet's [blog post](http://bartdesmet.net/blogs/bart/archive/2004/12/03/488.aspx) for details.
155,998
<p>Given this:</p> <pre><code>Public Sub timReminder_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) If DateTime.Now() &gt; g_RemindTime Then Reminders.ShowDialog() timReminder.Enabled = False End If End Sub </code></pre> <p>I want to be able to say this (as I would in Delphi):</p> <pre><code>timReminder.Tick = timReminder_Tick </code></pre> <p>But I get errors when I try it.</p> <p>Does anyone know how I can assign a custom event to a timer's on-tick event at runtime in VB.NET?</p>
[ { "answer_id": 156008, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 3, "selected": true, "text": "<p>Use the 'AddHandler' and 'AddressOf' keywords to add a handler to the Tick event.</p>\n\n<pre>\nAddHandler timeReminder.Tick, AddressOf timeReminder_Tick\n</pre>\n" }, { "answer_id": 354784, "author": "Jon Winstanley", "author_id": 42106, "author_profile": "https://Stackoverflow.com/users/42106", "pm_score": 0, "selected": false, "text": "<p>The <code>addHandler</code> is a very powerful tool.</p>\n\n<p>Try using it to add an event to a series of controls within a collection.</p>\n\n<p>The handler can add validation or error checking to all types of controls and will work with whatever you add to the form.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
Given this: ``` Public Sub timReminder_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) If DateTime.Now() > g_RemindTime Then Reminders.ShowDialog() timReminder.Enabled = False End If End Sub ``` I want to be able to say this (as I would in Delphi): ``` timReminder.Tick = timReminder_Tick ``` But I get errors when I try it. Does anyone know how I can assign a custom event to a timer's on-tick event at runtime in VB.NET?
Use the 'AddHandler' and 'AddressOf' keywords to add a handler to the Tick event. ``` AddHandler timeReminder.Tick, AddressOf timeReminder_Tick ```
156,009
<p>Because of the more tedious way of adding hosts to be monitored in Nagios (it requires defining a host object, as opposed to the previous program which only required the IP and hostname), I figured it'd be best to automate this, and it'd be a great time to learn Perl, because all I know at the moment is C/C++ and Java. </p> <p>The file I read from looks like this:</p> <pre><code>xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about </code></pre> <p>All I want are the first 2 bunches of characters. These are obviously space delimited, but for the sake of generality, it might as well be anything. To make it more general, why not the first and third, or fourth and tenth? Surely there must be some regex action involved, but I'll leave that tag off for the moment, just in case.</p>
[ { "answer_id": 156020, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "<p>A simple one-liner is</p>\n\n<pre><code>perl -nae 'print \"$F[0] $F[1]\\n\";'\n</code></pre>\n\n<p>you can change the delimiter with <code>-F</code></p>\n" }, { "answer_id": 156025, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>Let's turn this into code golf! Based on David's excellent answer, here's mine:</p>\n\n<pre><code>perl -ane 'print \"@F[0,1]\\n\";'\n</code></pre>\n\n<p>Edit: A real golf submission would look more like this (shaving off five strokes):</p>\n\n<pre><code>perl -ape '$_=\"@F[0,1]\n\"'\n</code></pre>\n\n<p>but that's less readable for this question's purposes. :-P</p>\n" }, { "answer_id": 156034, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 2, "selected": false, "text": "<p>David Nehme said:</p>\n\n<pre><code>perl -nae 'print \"$F[0] $F[1}\\n\";\n</code></pre>\n\n<p>which uses the <code>-a</code> switch. I had to look that one up:</p>\n\n<pre><code>-a turns on autosplit mode when used with a -n or -p. An implicit split\n command to the @F array is done as the first thing inside the implicit\n while loop produced by the -n or -p.\n</code></pre>\n\n<p>you learn something every day. -n causes each line to be passed to</p>\n\n<pre><code>LINE:\n while (&lt;&gt;) {\n ... # your program goes here\n }\n</code></pre>\n\n<p>And finally <code>-e</code> is a way to directly enter a single line of a program. You can have more than <code>-e</code>. Most of this was a rip of the <code>perlrun(1)</code> manpage.</p>\n" }, { "answer_id": 156037, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>Here's a general solution (if we step away from code-golfing a bit).</p>\n\n<pre><code>#!/usr/bin/perl -n\nchop; # strip newline (in case next line doesn't strip it)\ns/#.*//; # strip comments\nnext unless /\\S/; # don't process line if it has nothing (left)\n@fields = (split)[0,1]; # split line, and get wanted fields\nprint join(' ', @fields), \"\\n\";\n</code></pre>\n\n<p>Normally <code>split</code> splits by whitespace. If that's not what you want (e.g., parsing <code>/etc/passwd</code>), you can pass a delimiter as a regex:</p>\n\n<pre><code>@fields = (split /:/)[0,2,4..6];\n</code></pre>\n\n<p>Of course, if you're parsing colon-delimited files, chances are also good that such files don't have comments and you don't have to strip them.</p>\n" }, { "answer_id": 156063, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 4, "selected": true, "text": "<p>The one-liner is great, if you're not writing more Perl to handle the result.</p>\n\n<p>More generally though, in the context of a larger Perl program, you would either write a custom regular expression, for example:</p>\n\n<pre><code>if($line =~ m/(\\S+)\\s+(\\S+)/) {\n $ip = $1;\n $hostname = $2;\n}\n</code></pre>\n\n<p>... or you would use the <em>split</em> operator.</p>\n\n<pre><code>my @arr = split(/ /, $line);\n$ip = $arr[0];\n$hostname = $arr[1];\n</code></pre>\n\n<p>Either way, add logic to check for invalid input.</p>\n" }, { "answer_id": 160230, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<p>Since ray asked, I thought I'd rewrite my whole program without using Perl's implicitness (except the use of <code>&lt;ARGV&gt;</code>; that's hard to write out by hand). This will probably make Python people happier (braces notwithstanding :-P):</p>\n\n<pre><code>while (my $line = &lt;ARGV&gt;) {\n chop $line;\n $line =~ s/#.*//;\n next unless $line =~ /\\S/;\n @fields = (split ' ', $line)[0,1];\n print join(' ', @fields), \"\\n\";\n}\n</code></pre>\n\n<p>Is there anything I missed? Hopefully not. The <code>ARGV</code> filehandle is special. It causes each named file on the command line to be read, unless none are specified, in which case it reads standard input.</p>\n\n<p>Edit: Oh, I forgot. <code>split ' '</code> is magical too, unlike <code>split / /</code>. The latter just matches a space. The former matches any amount of any whitespace. This magical behaviour is used by default if no pattern is specified for <code>split</code>. (Some would say, <em>but what about <code>/\\s+/</code></em>? <code>' '</code> and <code>/\\s+/</code> are similar, except for how whitespace at the beginning of a line is treated. So <code>' '</code> really is magical.)</p>\n\n<p>The moral of the story is, Perl is great if you like lots of magical behaviour. If you don't have a bar of it, use Python. :-P</p>\n" }, { "answer_id": 20851920, "author": "Amit", "author_id": 2857960, "author_profile": "https://Stackoverflow.com/users/2857960", "pm_score": 0, "selected": false, "text": "<h1>To Find Nth to Mth Character In Line No. L --- Example For Finding Label</h1>\n\n<hr>\n\n<pre><code>@echo off\n\nREM Next line = Set command value to a file OR Just Choose Your File By Skipping The Line\nvol E: &gt; %temp%\\justtmp.txt\nREM Vol E: = Find Volume Lable Of Drive E\n\nREM Next Line to choose line line no. +0 = line no. 1 \nfor /f \"usebackq delims=\" %%a in (`more +0 %temp%\\justtmp.txt`) DO (set findstringline=%%a&amp; goto :nextstep)\n\n:nextstep\n\nREM Next line to read nth to mth Character here 22th Character to 40th Character\nset result=%findstringline:~22,40%\n\necho %result%\npause\nexit /b\n</code></pre>\n\n<p>Save as find label.cmd</p>\n\n<p>The Result Will Be Your Drive E Label</p>\n\n<p>Enjoy</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3879/" ]
Because of the more tedious way of adding hosts to be monitored in Nagios (it requires defining a host object, as opposed to the previous program which only required the IP and hostname), I figured it'd be best to automate this, and it'd be a great time to learn Perl, because all I know at the moment is C/C++ and Java. The file I read from looks like this: ``` xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about ``` All I want are the first 2 bunches of characters. These are obviously space delimited, but for the sake of generality, it might as well be anything. To make it more general, why not the first and third, or fourth and tenth? Surely there must be some regex action involved, but I'll leave that tag off for the moment, just in case.
The one-liner is great, if you're not writing more Perl to handle the result. More generally though, in the context of a larger Perl program, you would either write a custom regular expression, for example: ``` if($line =~ m/(\S+)\s+(\S+)/) { $ip = $1; $hostname = $2; } ``` ... or you would use the *split* operator. ``` my @arr = split(/ /, $line); $ip = $arr[0]; $hostname = $arr[1]; ``` Either way, add logic to check for invalid input.